text
stringlengths
54
60.6k
<commit_before><commit_msg>Fix crashing bug due to browser being NULL. BUG=None TEST=None Review URL: http://codereview.chromium.org/400015<commit_after><|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * https://lxqt.org * * Copyright: 2012 Razor team * Authors: * Petr Vanek <[email protected]> * * This program or 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 Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include <QPainter> #include <QUrl> #include <QFile> #include <QDateTime> #include <QtDBus/QDBusArgument> #include <QDebug> #include <XdgIcon> #include <KWindowSystem/KWindowSystem> #include <QMouseEvent> #include <QPushButton> #include <QStyle> #include <QStyleOption> #include "notification.h" #include "notificationwidgets.h" #define ICONSIZE QSize(32, 32) Notification::Notification(const QString &application, const QString &summary, const QString &body, const QString &icon, int timeout, const QStringList& actions, const QVariantMap& hints, QWidget *parent) : QWidget(parent), m_timer(0), m_linkHovered(false), m_actionWidget(0), m_icon(icon), m_timeout(timeout), m_actions(actions), m_hints(hints) { setupUi(this); setObjectName(QSL("Notification")); setMouseTracking(true); setMaximumWidth(parent->width()); setMinimumWidth(parent->width()); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); setValues(application, summary, body, icon, timeout, actions, hints); connect(closeButton, &QPushButton::clicked, this, &Notification::closeButton_clicked); for (QLabel *label : {bodyLabel, summaryLabel}) { connect(label, &QLabel::linkHovered, this, &Notification::linkHovered); label->installEventFilter(this); } } void Notification::setValues(const QString &application, const QString &summary, const QString &body, const QString &icon, int timeout, const QStringList& actions, const QVariantMap& hints) { // Basic properties ********************* // Notifications spec set real order here: // An implementation which only displays one image or icon must // choose which one to display using the following order: // - "image-data" // - "image-path" // - app_icon parameter // - for compatibility reason, "icon_data", "image_data" and "image_path" if (!hints[QL1S("image-data")].isNull()) { m_pixmap = getPixmapFromHint(hints[QL1S("image-data")]); } else if (!hints[QL1S("image_data")].isNull()) { m_pixmap = getPixmapFromHint(hints[QL1S("image_data")]); } else if (!hints[QL1S("image-path")].isNull()) { m_pixmap = getPixmapFromHint(hints[QL1S("image-path")]); } else if (!hints[QL1S("image_path")].isNull()) { m_pixmap = getPixmapFromString(hints[QL1S("image_path")].toString()); } else if (!icon.isEmpty()) { m_pixmap = getPixmapFromString(icon); } else if (!hints[QL1S("icon_data")].isNull()) { m_pixmap = getPixmapFromHint(hints[QL1S("icon_data")]); } // issue #325: Do not display icon if it's not found... if (m_pixmap.isNull()) { iconLabel->hide(); } else { if (m_pixmap.size().width() > ICONSIZE.width() || m_pixmap.size().height() > ICONSIZE.height()) { m_pixmap = m_pixmap.scaled(ICONSIZE, Qt::KeepAspectRatio, Qt::SmoothTransformation); } iconLabel->setPixmap(m_pixmap); iconLabel->show(); } //XXX: workaround to properly set text labels widths (for correct sizeHints after setText) adjustSize(); // application appLabel->setVisible(!application.isEmpty()); appLabel->setFixedWidth(appLabel->width()); appLabel->setText(application); // summary summaryLabel->setVisible(!summary.isEmpty() && application != summary); summaryLabel->setFixedWidth(summaryLabel->width()); summaryLabel->setText(summary); // body bodyLabel->setVisible(!body.isEmpty()); bodyLabel->setFixedWidth(bodyLabel->width()); //https://developer.gnome.org/notification-spec //Body - This is a multi-line body of text. Each line is a paragraph, server implementations are free to word wrap them as they see fit. //XXX: remove all unsupported tags?!? (supported <b>, <i>, <u>, <a>, <img>) QString formatted(body); bodyLabel->setText(formatted.replace(QL1C('\n'), QStringLiteral("<br/>"))); // Timeout // Special values: // < 0: server decides timeout // 0: infifite if (m_timer) { m_timer->stop(); m_timer->deleteLater(); } // -1 for server decides is handled in notifyd to save QSettings instance if (timeout > 0) { m_timer = new NotificationTimer(this); connect(m_timer, &NotificationTimer::timeout, this, &Notification::timeout); m_timer->start(timeout); } // Categories ********************* if (!hints[QL1S("category")].isNull()) { // TODO/FIXME: Categories - how to handle it? } // Urgency Levels ********************* // Type Description // 0 Low // 1 Normal // 2 Critical if (!hints[QL1S("urgency")].isNull()) { // TODO/FIXME: Urgencies - how to handle it? } // Actions if (actions.count() && m_actionWidget == 0) { if (actions.count()/2 < 4) m_actionWidget = new NotificationActionsButtonsWidget(actions, this); else m_actionWidget = new NotificationActionsComboWidget(actions, this); connect(m_actionWidget, &NotificationActionsWidget::actionTriggered, this, &Notification::actionTriggered); actionsLayout->addWidget(m_actionWidget); m_actionWidget->show(); } adjustSize(); // ensure layout expansion setMinimumHeight(qMax(rect().height(), childrenRect().height())); } QString Notification::application() const { return appLabel->text(); } QString Notification::summary() const { return summaryLabel->text(); } QString Notification::body() const { return bodyLabel->text(); } void Notification::closeButton_clicked() { if (m_timer) m_timer->stop(); emit userCanceled(); } void Notification::paintEvent(QPaintEvent *) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); } QPixmap Notification::getPixmapFromHint(const QVariant &argument) const { int width, height, rowstride, bitsPerSample, channels; bool hasAlpha; QByteArray data; const QDBusArgument arg = argument.value<QDBusArgument>(); arg.beginStructure(); arg >> width; arg >> height; arg >> rowstride; arg >> hasAlpha; arg >> bitsPerSample; arg >> channels; arg >> data; arg.endStructure(); bool rgb = !hasAlpha && channels == 3 && bitsPerSample == 8; QImage::Format imageFormat = rgb ? QImage::Format_RGB888 : QImage::Format_ARGB32; QImage img = QImage((uchar*)data.constData(), width, height, imageFormat); if (!rgb) img = img.rgbSwapped(); return QPixmap::fromImage(img); } QPixmap Notification::getPixmapFromString(const QString &str) const { QUrl url(str); if (url.isValid() && QFile::exists(url.toLocalFile())) { // qDebug() << " getPixmapFromString by URL" << url; return QPixmap(url.toLocalFile()); } else { // qDebug() << " getPixmapFromString by XdgIcon theme" << str << ICONSIZE << XdgIcon::themeName(); // qDebug() << " " << XdgIcon::fromTheme(str) << "isnull:" << XdgIcon::fromTheme(str).isNull(); // They say: do not display an icon if it;s not found - see #325 return XdgIcon::fromTheme(str/*, XdgIcon::defaultApplicationIcon()*/).pixmap(ICONSIZE); } } void Notification::enterEvent(QEvent * event) { if (m_timer) m_timer->pause(); } void Notification::leaveEvent(QEvent * event) { if (m_timer) m_timer->resume(); } bool Notification::eventFilter(QObject *obj, QEvent *event) { // Catch mouseReleaseEvent on child labels if a link is not currently being hovered. // // This workarounds QTBUG-49025 where clicking on text does not propagate the mouseReleaseEvent // to the parent even though the text is not selectable and no link is being clicked. if (event->type() == QEvent::MouseButtonRelease && !m_linkHovered) { mouseReleaseEvent(static_cast<QMouseEvent*>(event)); return true; } return false; } void Notification::linkHovered(const QString& link) { m_linkHovered = !link.isEmpty(); } void Notification::mouseReleaseEvent(QMouseEvent * event) { // qDebug() << "CLICKED" << event; QString appName; QString windowTitle; if (m_actionWidget && m_actionWidget->hasDefaultAction()) { emit actionTriggered(m_actionWidget->defaultAction()); return; } const auto ids = KWindowSystem::stackingOrder(); for (const WId &i : ids) { KWindowInfo info = KWindowInfo(i, NET::WMName | NET::WMVisibleName); appName = info.name(); windowTitle = info.visibleName(); // qDebug() << " " << i << "APPNAME" << appName << "TITLE" << windowTitle; if (appName.isEmpty()) { QWidget::mouseReleaseEvent(event); return; } if (appName == appLabel->text() || windowTitle == appLabel->text()) { KWindowSystem::raiseWindow(i); closeButton_clicked(); return; } } } NotificationTimer::NotificationTimer(QObject *parent) : QTimer(parent), m_intervalMsec(-1) { } void NotificationTimer::start(int msec) { m_startTime = QDateTime::currentDateTime(); m_intervalMsec = msec; QTimer::start(msec); } void NotificationTimer::pause() { if (!isActive()) return; stop(); m_intervalMsec = m_startTime.msecsTo(QDateTime::currentDateTime()); } void NotificationTimer::resume() { if (isActive()) return; start(m_intervalMsec); } <commit_msg>Silent compiler warning about unused parameters<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * https://lxqt.org * * Copyright: 2012 Razor team * Authors: * Petr Vanek <[email protected]> * * This program or 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 Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include <QPainter> #include <QUrl> #include <QFile> #include <QDateTime> #include <QtDBus/QDBusArgument> #include <QDebug> #include <XdgIcon> #include <KWindowSystem/KWindowSystem> #include <QMouseEvent> #include <QPushButton> #include <QStyle> #include <QStyleOption> #include "notification.h" #include "notificationwidgets.h" #define ICONSIZE QSize(32, 32) Notification::Notification(const QString &application, const QString &summary, const QString &body, const QString &icon, int timeout, const QStringList& actions, const QVariantMap& hints, QWidget *parent) : QWidget(parent), m_timer(0), m_linkHovered(false), m_actionWidget(0), m_icon(icon), m_timeout(timeout), m_actions(actions), m_hints(hints) { setupUi(this); setObjectName(QSL("Notification")); setMouseTracking(true); setMaximumWidth(parent->width()); setMinimumWidth(parent->width()); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); setValues(application, summary, body, icon, timeout, actions, hints); connect(closeButton, &QPushButton::clicked, this, &Notification::closeButton_clicked); for (QLabel *label : {bodyLabel, summaryLabel}) { connect(label, &QLabel::linkHovered, this, &Notification::linkHovered); label->installEventFilter(this); } } void Notification::setValues(const QString &application, const QString &summary, const QString &body, const QString &icon, int timeout, const QStringList& actions, const QVariantMap& hints) { // Basic properties ********************* // Notifications spec set real order here: // An implementation which only displays one image or icon must // choose which one to display using the following order: // - "image-data" // - "image-path" // - app_icon parameter // - for compatibility reason, "icon_data", "image_data" and "image_path" if (!hints[QL1S("image-data")].isNull()) { m_pixmap = getPixmapFromHint(hints[QL1S("image-data")]); } else if (!hints[QL1S("image_data")].isNull()) { m_pixmap = getPixmapFromHint(hints[QL1S("image_data")]); } else if (!hints[QL1S("image-path")].isNull()) { m_pixmap = getPixmapFromHint(hints[QL1S("image-path")]); } else if (!hints[QL1S("image_path")].isNull()) { m_pixmap = getPixmapFromString(hints[QL1S("image_path")].toString()); } else if (!icon.isEmpty()) { m_pixmap = getPixmapFromString(icon); } else if (!hints[QL1S("icon_data")].isNull()) { m_pixmap = getPixmapFromHint(hints[QL1S("icon_data")]); } // issue #325: Do not display icon if it's not found... if (m_pixmap.isNull()) { iconLabel->hide(); } else { if (m_pixmap.size().width() > ICONSIZE.width() || m_pixmap.size().height() > ICONSIZE.height()) { m_pixmap = m_pixmap.scaled(ICONSIZE, Qt::KeepAspectRatio, Qt::SmoothTransformation); } iconLabel->setPixmap(m_pixmap); iconLabel->show(); } //XXX: workaround to properly set text labels widths (for correct sizeHints after setText) adjustSize(); // application appLabel->setVisible(!application.isEmpty()); appLabel->setFixedWidth(appLabel->width()); appLabel->setText(application); // summary summaryLabel->setVisible(!summary.isEmpty() && application != summary); summaryLabel->setFixedWidth(summaryLabel->width()); summaryLabel->setText(summary); // body bodyLabel->setVisible(!body.isEmpty()); bodyLabel->setFixedWidth(bodyLabel->width()); //https://developer.gnome.org/notification-spec //Body - This is a multi-line body of text. Each line is a paragraph, server implementations are free to word wrap them as they see fit. //XXX: remove all unsupported tags?!? (supported <b>, <i>, <u>, <a>, <img>) QString formatted(body); bodyLabel->setText(formatted.replace(QL1C('\n'), QStringLiteral("<br/>"))); // Timeout // Special values: // < 0: server decides timeout // 0: infifite if (m_timer) { m_timer->stop(); m_timer->deleteLater(); } // -1 for server decides is handled in notifyd to save QSettings instance if (timeout > 0) { m_timer = new NotificationTimer(this); connect(m_timer, &NotificationTimer::timeout, this, &Notification::timeout); m_timer->start(timeout); } // Categories ********************* if (!hints[QL1S("category")].isNull()) { // TODO/FIXME: Categories - how to handle it? } // Urgency Levels ********************* // Type Description // 0 Low // 1 Normal // 2 Critical if (!hints[QL1S("urgency")].isNull()) { // TODO/FIXME: Urgencies - how to handle it? } // Actions if (actions.count() && m_actionWidget == 0) { if (actions.count()/2 < 4) m_actionWidget = new NotificationActionsButtonsWidget(actions, this); else m_actionWidget = new NotificationActionsComboWidget(actions, this); connect(m_actionWidget, &NotificationActionsWidget::actionTriggered, this, &Notification::actionTriggered); actionsLayout->addWidget(m_actionWidget); m_actionWidget->show(); } adjustSize(); // ensure layout expansion setMinimumHeight(qMax(rect().height(), childrenRect().height())); } QString Notification::application() const { return appLabel->text(); } QString Notification::summary() const { return summaryLabel->text(); } QString Notification::body() const { return bodyLabel->text(); } void Notification::closeButton_clicked() { if (m_timer) m_timer->stop(); emit userCanceled(); } void Notification::paintEvent(QPaintEvent *) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); } QPixmap Notification::getPixmapFromHint(const QVariant &argument) const { int width, height, rowstride, bitsPerSample, channels; bool hasAlpha; QByteArray data; const QDBusArgument arg = argument.value<QDBusArgument>(); arg.beginStructure(); arg >> width; arg >> height; arg >> rowstride; arg >> hasAlpha; arg >> bitsPerSample; arg >> channels; arg >> data; arg.endStructure(); bool rgb = !hasAlpha && channels == 3 && bitsPerSample == 8; QImage::Format imageFormat = rgb ? QImage::Format_RGB888 : QImage::Format_ARGB32; QImage img = QImage((uchar*)data.constData(), width, height, imageFormat); if (!rgb) img = img.rgbSwapped(); return QPixmap::fromImage(img); } QPixmap Notification::getPixmapFromString(const QString &str) const { QUrl url(str); if (url.isValid() && QFile::exists(url.toLocalFile())) { // qDebug() << " getPixmapFromString by URL" << url; return QPixmap(url.toLocalFile()); } else { // qDebug() << " getPixmapFromString by XdgIcon theme" << str << ICONSIZE << XdgIcon::themeName(); // qDebug() << " " << XdgIcon::fromTheme(str) << "isnull:" << XdgIcon::fromTheme(str).isNull(); // They say: do not display an icon if it;s not found - see #325 return XdgIcon::fromTheme(str/*, XdgIcon::defaultApplicationIcon()*/).pixmap(ICONSIZE); } } void Notification::enterEvent(QEvent * /*event*/) { if (m_timer) m_timer->pause(); } void Notification::leaveEvent(QEvent * /*event*/) { if (m_timer) m_timer->resume(); } bool Notification::eventFilter(QObject * /*obj*/, QEvent * event) { // Catch mouseReleaseEvent on child labels if a link is not currently being hovered. // // This workarounds QTBUG-49025 where clicking on text does not propagate the mouseReleaseEvent // to the parent even though the text is not selectable and no link is being clicked. if (event->type() == QEvent::MouseButtonRelease && !m_linkHovered) { mouseReleaseEvent(static_cast<QMouseEvent*>(event)); return true; } return false; } void Notification::linkHovered(const QString& link) { m_linkHovered = !link.isEmpty(); } void Notification::mouseReleaseEvent(QMouseEvent * event) { // qDebug() << "CLICKED" << event; QString appName; QString windowTitle; if (m_actionWidget && m_actionWidget->hasDefaultAction()) { emit actionTriggered(m_actionWidget->defaultAction()); return; } const auto ids = KWindowSystem::stackingOrder(); for (const WId &i : ids) { KWindowInfo info = KWindowInfo(i, NET::WMName | NET::WMVisibleName); appName = info.name(); windowTitle = info.visibleName(); // qDebug() << " " << i << "APPNAME" << appName << "TITLE" << windowTitle; if (appName.isEmpty()) { QWidget::mouseReleaseEvent(event); return; } if (appName == appLabel->text() || windowTitle == appLabel->text()) { KWindowSystem::raiseWindow(i); closeButton_clicked(); return; } } } NotificationTimer::NotificationTimer(QObject *parent) : QTimer(parent), m_intervalMsec(-1) { } void NotificationTimer::start(int msec) { m_startTime = QDateTime::currentDateTime(); m_intervalMsec = msec; QTimer::start(msec); } void NotificationTimer::pause() { if (!isActive()) return; stop(); m_intervalMsec = m_startTime.msecsTo(QDateTime::currentDateTime()); } void NotificationTimer::resume() { if (isActive()) return; start(m_intervalMsec); } <|endoftext|>
<commit_before>#ifndef STAN_MATH_GPU_MULTIPLY_HPP #define STAN_MATH_GPU_MULTIPLY_HPP #ifdef STAN_OPENCL #include <stan/math/gpu/matrix_gpu.hpp> #include <stan/math/gpu/kernels/scalar_mul.hpp> #include <stan/math/gpu/kernels/matrix_multiply.hpp> #include <Eigen/Dense> namespace stan { namespace math { /** * Multiplies the specified matrix on the GPU * with the specified scalar. * * @param A matrix * @param scalar scalar * @return matrix multipled with scalar */ inline matrix_gpu multiply(const matrix_gpu& A, const double scalar) { matrix_gpu temp(A.rows(), A.cols()); if (A.size() == 0) return temp; try { opencl_kernels::scalar_mul(cl::NDRange(A.rows(), A.cols()), temp.buffer(), A.buffer(), scalar, A.rows(), A.cols()); } catch (const cl::Error& e) { check_opencl_error("multiply scalar", e); } return temp; } /** * Multiplies the specified matrix on the GPU * with the specified scalar. * * @param scalar scalar * @param A matrix * @return matrix multipled with scalar */ inline auto multiply(const double scalar, const matrix_gpu& A) { return multiply(A, scalar); } /** * Computes the product of the specified GPU matrices. * * Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K] * * @param A first matrix * @param B second matrix * @return the product of the first and second matrix * * @throw <code>std::invalid_argument</code> if the * number of columns in A and rows in B do not match */ inline auto multiply(const matrix_gpu& A, const matrix_gpu& B) { check_size_match("multiply (GPU)", "A.cols()", A.cols(), "B.rows()", B.rows()); matrix_gpu temp(A.rows(), B.cols()); if (A.size() == 0 || B.size() == 0) { temp.zeros(); return temp; } int local = opencl_kernels::matrix_multiply.make_functor.get_opts().at( "THREAD_BLOCK_SIZE"); int Mpad = ((A.rows() + local - 1) / local) * local; int Npad = ((B.cols() + local - 1) / local) * local; int Kpad = ((A.cols() + local - 1) / local) * local; // padding the matrices so the dimensions are divisible with local // improves performance and readability because we can omit // if statements in the // multiply kernel matrix_gpu tempPad(Mpad, Npad); matrix_gpu Apad(Mpad, Kpad); matrix_gpu Bpad(Kpad, Npad); opencl_kernels::zeros(cl::NDRange(Mpad, Kpad), Apad.buffer(), Mpad, Kpad, TriangularViewGPU::Entire); opencl_kernels::zeros(cl::NDRange(Kpad, Npad), Bpad.buffer(), Kpad, Npad, TriangularViewGPU::Entire); Apad.sub_block(A, 0, 0, 0, 0, A.rows(), A.cols()); Bpad.sub_block(B, 0, 0, 0, 0, B.rows(), B.cols()); int wpt = opencl_kernels::matrix_multiply.make_functor.get_opts().at( "WORK_PER_THREAD"); try { opencl_kernels::matrix_multiply( cl::NDRange(Mpad, Npad / wpt), cl::NDRange(local, local / wpt), Apad.buffer(), Bpad.buffer(), tempPad.buffer(), Apad.rows(), Bpad.cols(), Bpad.rows()); } catch (cl::Error& e) { check_opencl_error("multiply", e); } // unpadding the result matrix temp.sub_block(tempPad, 0, 0, 0, 0, temp.rows(), temp.cols()); return temp; } /** * Templated product operator for GPU matrices. * * Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K]. * * @param A A matrix or scalar * @param B A matrix or scalar * @return the product of the first and second arguments * * @throw <code>std::invalid_argument</code> if the * number of columns in A and rows in B do not match */ inline matrix_gpu operator*(const matrix_gpu& A, const matrix_gpu& B) { return multiply(A, B); } inline matrix_gpu operator*(const matrix_gpu& B, const double scalar) { return multiply(B, scalar); } inline matrix_gpu operator*(const double scalar, const matrix_gpu& B) { return multiply(scalar, B); } } // namespace math } // namespace stan #endif #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.0-3~16.04.1 (tags/RELEASE_500/final)<commit_after>#ifndef STAN_MATH_GPU_MULTIPLY_HPP #define STAN_MATH_GPU_MULTIPLY_HPP #ifdef STAN_OPENCL #include <stan/math/gpu/matrix_gpu.hpp> #include <stan/math/gpu/kernels/scalar_mul.hpp> #include <stan/math/gpu/kernels/matrix_multiply.hpp> #include <Eigen/Dense> namespace stan { namespace math { /** * Multiplies the specified matrix on the GPU * with the specified scalar. * * @param A matrix * @param scalar scalar * @return matrix multipled with scalar */ inline matrix_gpu multiply(const matrix_gpu& A, const double scalar) { matrix_gpu temp(A.rows(), A.cols()); if (A.size() == 0) return temp; try { opencl_kernels::scalar_mul(cl::NDRange(A.rows(), A.cols()), temp.buffer(), A.buffer(), scalar, A.rows(), A.cols()); } catch (const cl::Error& e) { check_opencl_error("multiply scalar", e); } return temp; } /** * Multiplies the specified matrix on the GPU * with the specified scalar. * * @param scalar scalar * @param A matrix * @return matrix multipled with scalar */ inline auto multiply(const double scalar, const matrix_gpu& A) { return multiply(A, scalar); } /** * Computes the product of the specified GPU matrices. * * Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K] * * @param A first matrix * @param B second matrix * @return the product of the first and second matrix * * @throw <code>std::invalid_argument</code> if the * number of columns in A and rows in B do not match */ inline auto multiply(const matrix_gpu& A, const matrix_gpu& B) { check_size_match("multiply (GPU)", "A.cols()", A.cols(), "B.rows()", B.rows()); matrix_gpu temp(A.rows(), B.cols()); if (A.size() == 0 || B.size() == 0) { temp.zeros(); return temp; } int local = opencl_kernels::matrix_multiply.make_functor.get_opts().at( "THREAD_BLOCK_SIZE"); int Mpad = ((A.rows() + local - 1) / local) * local; int Npad = ((B.cols() + local - 1) / local) * local; int Kpad = ((A.cols() + local - 1) / local) * local; // padding the matrices so the dimensions are divisible with local // improves performance and readability because we can omit // if statements in the // multiply kernel matrix_gpu tempPad(Mpad, Npad); matrix_gpu Apad(Mpad, Kpad); matrix_gpu Bpad(Kpad, Npad); opencl_kernels::zeros(cl::NDRange(Mpad, Kpad), Apad.buffer(), Mpad, Kpad, TriangularViewGPU::Entire); opencl_kernels::zeros(cl::NDRange(Kpad, Npad), Bpad.buffer(), Kpad, Npad, TriangularViewGPU::Entire); Apad.sub_block(A, 0, 0, 0, 0, A.rows(), A.cols()); Bpad.sub_block(B, 0, 0, 0, 0, B.rows(), B.cols()); int wpt = opencl_kernels::matrix_multiply.make_functor.get_opts().at( "WORK_PER_THREAD"); try { opencl_kernels::matrix_multiply( cl::NDRange(Mpad, Npad / wpt), cl::NDRange(local, local / wpt), Apad.buffer(), Bpad.buffer(), tempPad.buffer(), Apad.rows(), Bpad.cols(), Bpad.rows()); } catch (cl::Error& e) { check_opencl_error("multiply", e); } // unpadding the result matrix temp.sub_block(tempPad, 0, 0, 0, 0, temp.rows(), temp.cols()); return temp; } /** * Templated product operator for GPU matrices. * * Computes the matrix multiplication C[M, K] = A[M, N] x B[N, K]. * * @param A A matrix or scalar * @param B A matrix or scalar * @return the product of the first and second arguments * * @throw <code>std::invalid_argument</code> if the * number of columns in A and rows in B do not match */ inline matrix_gpu operator*(const matrix_gpu& A, const matrix_gpu& B) { return multiply(A, B); } inline matrix_gpu operator*(const matrix_gpu& B, const double scalar) { return multiply(B, scalar); } inline matrix_gpu operator*(const double scalar, const matrix_gpu& B) { return multiply(scalar, B); } } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. 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. #ifndef IOX_POSH_ROUDI_INTROSPECTION_TYPES_HPP #define IOX_POSH_ROUDI_INTROSPECTION_TYPES_HPP #include "iceoryx_posh/capro/service_description.hpp" #include "iceoryx_posh/iceoryx_posh_types.hpp" #include "iceoryx_posh/mepoo/mepoo_config.hpp" #include "iceoryx_utils/cxx/vector.hpp" namespace iox { namespace roudi { constexpr const char INTROSPECTION_SERVICE_ID[] = "Introspection"; constexpr const char INTROSPECTION_MQ_APP_NAME[] = "/introspection"; const capro::ServiceDescription IntrospectionMempoolService(INTROSPECTION_SERVICE_ID, "RouDi_ID", "MemPool"); constexpr int MAX_GROUP_NAME_LENGTH = 32; /// @brief struct for the storage of mempool usage information. /// This data container is used by the introstpection::MemPoolInfoContainer array /// to store information on all available memmpools. struct MemPoolInfo { uint32_t m_usedChunks{0}; uint32_t m_minFreeChunks{0}; uint32_t m_numChunks{0}; uint32_t m_chunkSize{0}; uint32_t m_payloadSize{0}; }; /// @brief container for MemPoolInfo structs of all available mempools. using MemPoolInfoContainer = cxx::vector<MemPoolInfo, MAX_NUMBER_OF_MEMPOOLS>; /// @brief the topic for the mempool introspection that a user can subscribe to struct MemPoolIntrospectionInfo { uint32_t m_id; char m_writerGroupName[MAX_GROUP_NAME_LENGTH]; char m_readerGroupName[MAX_GROUP_NAME_LENGTH]; MemPoolInfoContainer m_mempoolInfo; }; /// @brief container for MemPoolInfo structs of all available mempools. using MemPoolIntrospectionInfoContainer = cxx::vector<MemPoolIntrospectionInfo, MAX_SHM_SEGMENTS + 1>; /// @brief sender/receiver port information consisting of a process name,a capro service description string /// and a runnable name const capro::ServiceDescription IntrospectionPortService(INTROSPECTION_SERVICE_ID, "RouDi_ID", "Port"); /// @todo if future fixed string is aligned to 8 byte, the alignment here can be removed struct PortData { alignas(8) ProcessName_t m_name; alignas(8) capro::IdString m_caproInstanceID; alignas(8) capro::IdString m_caproServiceID; alignas(8) capro::IdString m_caproEventMethodID; alignas(8) RunnableName_t m_runnable; }; /// @brief container for receiver port introspection data. struct ReceiverPortData : public PortData { /// @brief identifier of the sender port to which this receiver port is connected. /// If no matching sender port exists, this should equal -1. int32_t m_senderIndex{-1}; }; /// @brief container for sender port introspection data. struct SenderPortData : public PortData { uint64_t m_senderPortID{0}; iox::capro::Interfaces m_sourceInterface{iox::capro::Interfaces::INTERFACE_END}; }; /// @brief the topic for the port introspection that a user can subscribe to struct PortIntrospectionFieldTopic { cxx::vector<ReceiverPortData, MAX_SUBSCRIBERS> m_receiverList; cxx::vector<SenderPortData, MAX_PUBLISHERS> m_senderList; }; const capro::ServiceDescription IntrospectionPortThroughputService(INTROSPECTION_SERVICE_ID, "RouDi_ID", "PortThroughput"); struct PortThroughputData { uint64_t m_senderPortID{0}; uint32_t m_sampleSize{0}; uint32_t m_chunkSize{0}; double m_chunksPerMinute{0}; uint64_t m_lastSendIntervalInNanoseconds{0}; bool m_isField{false}; }; /// @brief the topic for the port throughput that a user can subscribe to struct PortThroughputIntrospectionFieldTopic { cxx::vector<PortThroughputData, MAX_PUBLISHERS> m_throughputList; }; const capro::ServiceDescription IntrospectionReceiverPortChangingDataService(INTROSPECTION_SERVICE_ID, "RouDi_ID", "ReceiverPortsData"); struct ReceiverPortChangingData { // index used to identify receiver is same as in PortIntrospectionFieldTopic->receiverList uint64_t fifoSize{0}; uint64_t fifoCapacity{0}; iox::SubscribeState subscriptionState{iox::SubscribeState::NOT_SUBSCRIBED}; bool sampleSendCallbackActive{false}; capro::Scope propagationScope{capro::Scope::INVALID}; }; struct ReceiverPortChangingIntrospectionFieldTopic { cxx::vector<ReceiverPortChangingData, MAX_SUBSCRIBERS> receiverPortChangingDataList; }; const capro::ServiceDescription IntrospectionProcessService(INTROSPECTION_SERVICE_ID, "RouDi_ID", "Process"); struct ProcessIntrospectionData { int m_pid{0}; ProcessName_t m_name; cxx::vector<RunnableName_t, MAX_RUNNABLE_PER_PROCESS> m_runnables; }; /// @brief the topic for the process introspection that a user can subscribe to struct ProcessIntrospectionFieldTopic { cxx::vector<ProcessIntrospectionData, MAX_PROCESS_NUMBER> m_processList; }; } // namespace roudi } // namespace iox #endif // IOX_POSH_ROUDI_INTROSPECTION_TYPES_HPP <commit_msg>iox-#260 remove unnecessary alignments from PortData members<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. 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. #ifndef IOX_POSH_ROUDI_INTROSPECTION_TYPES_HPP #define IOX_POSH_ROUDI_INTROSPECTION_TYPES_HPP #include "iceoryx_posh/capro/service_description.hpp" #include "iceoryx_posh/iceoryx_posh_types.hpp" #include "iceoryx_posh/mepoo/mepoo_config.hpp" #include "iceoryx_utils/cxx/vector.hpp" namespace iox { namespace roudi { constexpr const char INTROSPECTION_SERVICE_ID[] = "Introspection"; constexpr const char INTROSPECTION_MQ_APP_NAME[] = "/introspection"; const capro::ServiceDescription IntrospectionMempoolService(INTROSPECTION_SERVICE_ID, "RouDi_ID", "MemPool"); constexpr int MAX_GROUP_NAME_LENGTH = 32; /// @brief struct for the storage of mempool usage information. /// This data container is used by the introstpection::MemPoolInfoContainer array /// to store information on all available memmpools. struct MemPoolInfo { uint32_t m_usedChunks{0}; uint32_t m_minFreeChunks{0}; uint32_t m_numChunks{0}; uint32_t m_chunkSize{0}; uint32_t m_payloadSize{0}; }; /// @brief container for MemPoolInfo structs of all available mempools. using MemPoolInfoContainer = cxx::vector<MemPoolInfo, MAX_NUMBER_OF_MEMPOOLS>; /// @brief the topic for the mempool introspection that a user can subscribe to struct MemPoolIntrospectionInfo { uint32_t m_id; char m_writerGroupName[MAX_GROUP_NAME_LENGTH]; char m_readerGroupName[MAX_GROUP_NAME_LENGTH]; MemPoolInfoContainer m_mempoolInfo; }; /// @brief container for MemPoolInfo structs of all available mempools. using MemPoolIntrospectionInfoContainer = cxx::vector<MemPoolIntrospectionInfo, MAX_SHM_SEGMENTS + 1>; /// @brief sender/receiver port information consisting of a process name,a capro service description string /// and a runnable name const capro::ServiceDescription IntrospectionPortService(INTROSPECTION_SERVICE_ID, "RouDi_ID", "Port"); /// @brief container for common port data which is related to the receiver port as well as the sender port struct PortData { ProcessName_t m_name; capro::IdString m_caproInstanceID; capro::IdString m_caproServiceID; capro::IdString m_caproEventMethodID; RunnableName_t m_runnable; }; /// @brief container for receiver port introspection data. struct ReceiverPortData : public PortData { /// @brief identifier of the sender port to which this receiver port is connected. /// If no matching sender port exists, this should equal -1. int32_t m_senderIndex{-1}; }; /// @brief container for sender port introspection data. struct SenderPortData : public PortData { uint64_t m_senderPortID{0}; iox::capro::Interfaces m_sourceInterface{iox::capro::Interfaces::INTERFACE_END}; }; /// @brief the topic for the port introspection that a user can subscribe to struct PortIntrospectionFieldTopic { cxx::vector<ReceiverPortData, MAX_SUBSCRIBERS> m_receiverList; cxx::vector<SenderPortData, MAX_PUBLISHERS> m_senderList; }; const capro::ServiceDescription IntrospectionPortThroughputService(INTROSPECTION_SERVICE_ID, "RouDi_ID", "PortThroughput"); struct PortThroughputData { uint64_t m_senderPortID{0}; uint32_t m_sampleSize{0}; uint32_t m_chunkSize{0}; double m_chunksPerMinute{0}; uint64_t m_lastSendIntervalInNanoseconds{0}; bool m_isField{false}; }; /// @brief the topic for the port throughput that a user can subscribe to struct PortThroughputIntrospectionFieldTopic { cxx::vector<PortThroughputData, MAX_PUBLISHERS> m_throughputList; }; const capro::ServiceDescription IntrospectionReceiverPortChangingDataService(INTROSPECTION_SERVICE_ID, "RouDi_ID", "ReceiverPortsData"); struct ReceiverPortChangingData { // index used to identify receiver is same as in PortIntrospectionFieldTopic->receiverList uint64_t fifoSize{0}; uint64_t fifoCapacity{0}; iox::SubscribeState subscriptionState{iox::SubscribeState::NOT_SUBSCRIBED}; bool sampleSendCallbackActive{false}; capro::Scope propagationScope{capro::Scope::INVALID}; }; struct ReceiverPortChangingIntrospectionFieldTopic { cxx::vector<ReceiverPortChangingData, MAX_SUBSCRIBERS> receiverPortChangingDataList; }; const capro::ServiceDescription IntrospectionProcessService(INTROSPECTION_SERVICE_ID, "RouDi_ID", "Process"); struct ProcessIntrospectionData { int m_pid{0}; ProcessName_t m_name; cxx::vector<RunnableName_t, MAX_RUNNABLE_PER_PROCESS> m_runnables; }; /// @brief the topic for the process introspection that a user can subscribe to struct ProcessIntrospectionFieldTopic { cxx::vector<ProcessIntrospectionData, MAX_PROCESS_NUMBER> m_processList; }; } // namespace roudi } // namespace iox #endif // IOX_POSH_ROUDI_INTROSPECTION_TYPES_HPP <|endoftext|>
<commit_before>/* * Copyright (C) 2009-2012, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #include <urbi/kernel/userver.hh> #include <urbi/object/global.hh> #include <object/ioservice.hh> #include <object/server.hh> #include <object/socket.hh> #include <urbi/object/symbols.hh> #include <runner/job.hh> namespace urbi { namespace object { Socket::Socket() : CxxObject() , libport::Socket(*get_default_io_service().get()) , server_() , disconnect_() , io_service_(get_default_io_service()) { proto_add(Object::proto); // FIXME: call slots_create here when uobjects load order is fixed } Socket::Socket(rServer server) : CxxObject() , libport::Socket(*server->getIoService().get()) , server_(server) , disconnect_() , io_service_(server->getIoService()) { proto_add(proto); init(); } Socket::Socket(rSocket) : CxxObject() , libport::Socket(*get_default_io_service().get()) , server_() , disconnect_() , io_service_(get_default_io_service()) { proto_add(proto); // FIXME: call slots_create here when uobjects load order is fixed } Socket::Socket(rIoService io_service) : CxxObject() , libport::Socket(*io_service.get()) , io_service_(io_service) { proto_add(proto); init(); } Socket::~Socket() { close(); wasDestroyed(); while (!checkDestructionPermission()) ::kernel::runner().yield_for(1000); } OVERLOAD_TYPE( socket_connect_overload, 2, 2, String, (void (Socket::*)(const std::string&, const std::string&)) &Socket::connect, Float, (void (Socket::*)(const std::string&, unsigned)) &Socket::connect) URBI_CXX_OBJECT_INIT(Socket) : libport::Socket(*get_default_io_service().get()) , io_service_(get_default_io_service()) { // Uncomment the line below when overloading works. //BIND(connectSerial, // connectSerial, void, (const std::string&, unsigned int)) BIND(connectSerial, connectSerial, void, (const std::string&, unsigned int, bool)); BIND(disconnect); BIND(getAutoRead); BIND(getIoService); BIND(host); BIND(init); BIND(isConnected); BIND(localHost); BIND(localPort); BIND(openFile); BIND(poll); BIND(port); BIND(read); BIND(readOnce); BIND(setAutoRead); BIND(syncWrite); BIND(write); setSlot(SYMBOL(connect), new Primitive(socket_connect_overload)); } void Socket::init() { slots_create(); } #define BOUNCE(Type, From, To) \ Type \ Socket::From() const \ { \ if (isConnected()) \ return To(); \ else \ RAISE("unconnected socket"); \ } BOUNCE(std::string, host, getRemoteHost); BOUNCE(unsigned short, port, getRemotePort); BOUNCE(std::string, localHost, getLocalHost); BOUNCE(unsigned short, localPort, getLocalPort); #undef BOUNCE void Socket::slots_create() { CAPTURE_GLOBAL(Event); #define EVENT(Name) \ { \ rObject val = Event->call(SYMBOL(new)); \ slot_set_value(Name, val); \ } EVENT(SYMBOL(connected)); EVENT(SYMBOL(disconnected)); EVENT(SYMBOL(error)); EVENT(SYMBOL(received)); #undef EVENT } void Socket::connect(const std::string& host, const std::string& port) { if (boost::system::error_code err = libport::Socket::connect(host, port)) RAISE(err.message()); } void Socket::connect(const std::string& host, unsigned port) { if (boost::system::error_code err = libport::Socket::connect(host, port)) RAISE(err.message()); } void Socket::connectSerial(const std::string& device, unsigned int baudrate) { connectSerial(device, baudrate, true); } void Socket::connectSerial(const std::string& device, unsigned int baudrate, bool asyncRead) { if (boost::system::error_code error = libport::Socket::open_serial(device, baudrate, asyncRead)) RAISE(error.message()); } void Socket::disconnect() { close(); } #define EMIT(Name) \ slot_get_value(SYMBOL_(Name))->call(SYMBOL(emit)) #define EMIT1(Name, Arg) \ slot_get_value(SYMBOL_(Name))->call(SYMBOL(emit), to_urbi(Arg)) void Socket::onConnect() { disconnect_ = slot_get_value(SYMBOL(connected))->call(SYMBOL(trigger)); if (server_) server_->socket_ready(this); } void Socket::onError(boost::system::error_code err) { EMIT1(error, err.message()); EMIT(disconnected); aver(disconnect_); disconnect_->call(SYMBOL(stop)); } bool Socket::isConnected() const { return libport::Socket::isConnected(); } size_t Socket::onRead(const void* data, size_t length) { std::string str(reinterpret_cast<const char*>(data), length); if (slot_has(SYMBOL(receive))) call(SYMBOL(receive), to_urbi(str)); else EMIT1(received, str); return length; } void Socket::write(const std::string& data) { if (!isConnected()) RAISE("socket not connected"); libport::Socket::send(data); } void Socket::syncWrite(const std::string& data) { if (!isConnected()) RAISE("socket not connected"); libport::Socket::syncWrite(data); } std::string Socket::read(size_t len) { return libport::Socket::syncRead(len); } void Socket::readOnce() { libport::Socket::readOnce(); } void Socket::poll() { getIoService()->poll(); } rIoService Socket::getIoService() const { return io_service_; } rIoService Socket::get_default_io_service() { static rIoService ios(new IoService); return ios; } void Socket::setAutoRead(bool enable) { libport::Socket::setAutoRead(enable); } bool Socket::getAutoRead() { return libport::Socket::getAutoRead(); } void Socket::openFile(const std::string&s, int m) { libport::Socket::open_file(s, (libport::Socket::OpenMode)m); } } } <commit_msg>Socket: Fix abort() when throwing from Socket.receive().<commit_after>/* * Copyright (C) 2009-2012, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #include <urbi/kernel/userver.hh> #include <urbi/object/global.hh> #include <object/ioservice.hh> #include <object/server.hh> #include <object/socket.hh> #include <urbi/object/symbols.hh> #include <runner/job.hh> #include <eval/send-message.hh> namespace urbi { namespace object { Socket::Socket() : CxxObject() , libport::Socket(*get_default_io_service().get()) , server_() , disconnect_() , io_service_(get_default_io_service()) { proto_add(Object::proto); // FIXME: call slots_create here when uobjects load order is fixed } Socket::Socket(rServer server) : CxxObject() , libport::Socket(*server->getIoService().get()) , server_(server) , disconnect_() , io_service_(server->getIoService()) { proto_add(proto); init(); } Socket::Socket(rSocket) : CxxObject() , libport::Socket(*get_default_io_service().get()) , server_() , disconnect_() , io_service_(get_default_io_service()) { proto_add(proto); // FIXME: call slots_create here when uobjects load order is fixed } Socket::Socket(rIoService io_service) : CxxObject() , libport::Socket(*io_service.get()) , io_service_(io_service) { proto_add(proto); init(); } Socket::~Socket() { close(); wasDestroyed(); while (!checkDestructionPermission()) ::kernel::runner().yield_for(1000); } OVERLOAD_TYPE( socket_connect_overload, 2, 2, String, (void (Socket::*)(const std::string&, const std::string&)) &Socket::connect, Float, (void (Socket::*)(const std::string&, unsigned)) &Socket::connect) URBI_CXX_OBJECT_INIT(Socket) : libport::Socket(*get_default_io_service().get()) , io_service_(get_default_io_service()) { // Uncomment the line below when overloading works. //BIND(connectSerial, // connectSerial, void, (const std::string&, unsigned int)) BIND(connectSerial, connectSerial, void, (const std::string&, unsigned int, bool)); BIND(disconnect); BIND(getAutoRead); BIND(getIoService); BIND(host); BIND(init); BIND(isConnected); BIND(localHost); BIND(localPort); BIND(openFile); BIND(poll); BIND(port); BIND(read); BIND(readOnce); BIND(setAutoRead); BIND(syncWrite); BIND(write); setSlot(SYMBOL(connect), new Primitive(socket_connect_overload)); } void Socket::init() { slots_create(); } #define BOUNCE(Type, From, To) \ Type \ Socket::From() const \ { \ if (isConnected()) \ return To(); \ else \ RAISE("unconnected socket"); \ } BOUNCE(std::string, host, getRemoteHost); BOUNCE(unsigned short, port, getRemotePort); BOUNCE(std::string, localHost, getLocalHost); BOUNCE(unsigned short, localPort, getLocalPort); #undef BOUNCE void Socket::slots_create() { CAPTURE_GLOBAL(Event); #define EVENT(Name) \ { \ rObject val = Event->call(SYMBOL(new)); \ slot_set_value(Name, val); \ } EVENT(SYMBOL(connected)); EVENT(SYMBOL(disconnected)); EVENT(SYMBOL(error)); EVENT(SYMBOL(received)); #undef EVENT } void Socket::connect(const std::string& host, const std::string& port) { if (boost::system::error_code err = libport::Socket::connect(host, port)) RAISE(err.message()); } void Socket::connect(const std::string& host, unsigned port) { if (boost::system::error_code err = libport::Socket::connect(host, port)) RAISE(err.message()); } void Socket::connectSerial(const std::string& device, unsigned int baudrate) { connectSerial(device, baudrate, true); } void Socket::connectSerial(const std::string& device, unsigned int baudrate, bool asyncRead) { if (boost::system::error_code error = libport::Socket::open_serial(device, baudrate, asyncRead)) RAISE(error.message()); } void Socket::disconnect() { close(); } #define EMIT(Name) \ slot_get_value(SYMBOL_(Name))->call(SYMBOL(emit)) #define EMIT1(Name, Arg) \ slot_get_value(SYMBOL_(Name))->call(SYMBOL(emit), to_urbi(Arg)) void Socket::onConnect() { disconnect_ = slot_get_value(SYMBOL(connected))->call(SYMBOL(trigger)); if (server_) server_->socket_ready(this); } void Socket::onError(boost::system::error_code err) { EMIT1(error, err.message()); EMIT(disconnected); aver(disconnect_); disconnect_->call(SYMBOL(stop)); } bool Socket::isConnected() const { return libport::Socket::isConnected(); } size_t Socket::onRead(const void* data, size_t length) { bool mustExit = false; std::string str(reinterpret_cast<const char*>(data), length); try { if (slot_has(SYMBOL(receive))) call(SYMBOL(receive), to_urbi(str)); else EMIT1(received, str); } catch(const UrbiException& e) { mustExit = true; eval::show_exception(e); } catch(const std::exception& e) { mustExit = true; eval::send_error((std::string)"Unexpected exception caught: " + e.what()); } catch(...) { eval::send_error("Unknown exception caught"); } if (mustExit) { eval::send_error("Exceptiong caught in receive, closing connection."); close(); } return length; } void Socket::write(const std::string& data) { if (!isConnected()) RAISE("socket not connected"); libport::Socket::send(data); } void Socket::syncWrite(const std::string& data) { if (!isConnected()) RAISE("socket not connected"); libport::Socket::syncWrite(data); } std::string Socket::read(size_t len) { return libport::Socket::syncRead(len); } void Socket::readOnce() { libport::Socket::readOnce(); } void Socket::poll() { getIoService()->poll(); } rIoService Socket::getIoService() const { return io_service_; } rIoService Socket::get_default_io_service() { static rIoService ios(new IoService); return ios; } void Socket::setAutoRead(bool enable) { libport::Socket::setAutoRead(enable); } bool Socket::getAutoRead() { return libport::Socket::getAutoRead(); } void Socket::openFile(const std::string&s, int m) { libport::Socket::open_file(s, (libport::Socket::OpenMode)m); } } } <|endoftext|>
<commit_before>#include <NeuralNetwork/LearningAlgorithm/BackPropagation/BepAlgorithm.h> #include <NeuralNetwork/NeuralLayer/ConvolutionLayer.h> #include <NeuralNetwork/NeuralLayer/NeuralLayer.h> #include <NeuralNetwork/Neuron/ActivationFunction/BiopolarSigmoidFunction.h> #include <NeuralNetwork/Neuron/ActivationFunction/LogScaleSoftmaxFunction.h> #include <NeuralNetwork/Neuron/ActivationFunction/SigmoidFunction.h> #include <NeuralNetwork/Neuron/ActivationFunction/SoftmaxFunction.h> #include <NeuralNetwork/Neuron/ActivationFunction/TanhFunction.h> #include <NeuralNetwork/Neuron/ActivationFunction/ReluFunction.h> #include <NeuralNetwork/Neuron/Neuron.h> #include <NeuralNetwork/Perceptron/Perceptron.h> //#include <NeuralNetwork/NeuralLayer/OpenCLNeuralLayer.h> #include <NeuralNetwork/Config.h> #include <Utilities/MPL/Tuple.h> #ifndef BOOST_SYSTEM_NO_DEPRECATED #define BOOST_SYSTEM_NO_DEPRECATED 1 #include <boost/filesystem.hpp> #undef BOOST_SYSTEM_NO_DEPRECATED #endif #define png_infopp_NULL (png_infopp) NULL #define int_p_NULL (int*)NULL #if defined(NN_CC_MSVC) #pragma warning(push) // This function or variable may be unsafe #pragma warning(disable : 4996) #endif #include <boost/gil/channel_algorithm.hpp> #include <boost/gil/channel.hpp> #include <boost/gil/gil_all.hpp> #include <boost/gil/image.hpp> #include <boost/gil/extension/io/png/old.hpp> #include <boost/gil/extension/numeric/sampler.hpp> #include <boost/gil/extension/numeric/resample.hpp> #include <boost/gil/extension/dynamic_image/any_image.hpp> #include <boost/gil/extension/dynamic_image/dynamic_image_all.hpp> #include <tuple> #include <cmath> #include <fstream> #include <iomanip> #include <iostream> #include <set> typedef long double VarType; namespace { using namespace boost::gil; using namespace boost::gil::detail; const std::string alphabet("0123456789"); constexpr std::size_t width = 49; constexpr std::size_t height = 67; constexpr std::size_t inputsNumber = width * height; constexpr std::size_t margin = 15; constexpr std::size_t stride = 10; } // namespace using ConvolutionGrid = typename nn::ConvolutionGrid< width, height, stride, margin >::define; using ConvolutionGrid2 = typename nn::ConvolutionGrid< width / stride, height / stride, 2, 5 >::define; using Perceptron = nn::Perceptron< VarType, nn::ConvolutionLayer< nn::NeuralLayer, nn::Neuron, nn::ReluFunction, inputsNumber, ConvolutionGrid >, nn::NeuralLayer< nn::Neuron, nn::SoftmaxFunction, 10, 1000 > >; using Algo = nn::bp::BepAlgorithm< Perceptron, nn::bp::CrossEntropyError >; template< typename Out > struct halfdiff_cast_channels { template< typename T > Out operator()(const T& in1, const T& in2) const { return Out((in1 - in2) / 2); } }; template< typename SrcView, typename DstView > void convert_color(const SrcView& src, const DstView& dst) { typedef typename channel_type< DstView >::type d_channel_t; typedef typename channel_convert_to_unsigned< d_channel_t >::type channel_t; typedef pixel< channel_t, gray_layout_t > gray_pixel_t; copy_pixels(color_converted_view< gray_pixel_t >(src), dst); } template< typename Iterator > void readImage(std::string fileName, Iterator out) { using namespace boost::gil; using namespace nn; using namespace nn::bp; rgb8_image_t srcImg; png_read_image(fileName.c_str(), srcImg); gray8_image_t dstImg(srcImg.dimensions()); gray8_pixel_t white(255); fill_pixels(view(dstImg), white); gray8_image_t grayImage(srcImg.dimensions()); convert_color(view(srcImg), view(grayImage)); auto grayView = view(grayImage); gray8_image_t scaledImage(width, height); resize_view(grayView, view(scaledImage), bilinear_sampler()); auto srcView = view(scaledImage); for(int y = 0; y < srcView.height(); ++y) { gray8c_view_t::x_iterator src_it(srcView.row_begin(y)); for(int x = 0; x < srcView.width(); ++x) { *out = src_it[x]; out++; } } } Perceptron readPerceptron(std::string fileName) { Perceptron perceptron; if(boost::filesystem::exists(fileName.c_str())) { std::ifstream file(fileName); if(file.good()) { Perceptron::Memento memento; cereal::XMLInputArchive ia(file); ia >> memento; perceptron.setMemento(memento); } else { throw std::logic_error("Invalid perceptron file name"); } } return perceptron; } void recognize(std::string perceptron, std::string image) { try { std::array< VarType, inputsNumber > inputs = {0}; readImage(image, inputs.begin()); std::vector< VarType > result(alphabet.length(), VarType(0.f)); readPerceptron(perceptron) .calculate(inputs.begin(), inputs.end(), result.begin()); for(unsigned int i = 0; i < result.size(); i++) { std::cout << "Symbol: " << alphabet[i] << " " << result[i] << std::endl; } } catch(const std::exception& e) { std::cout << e.what() << std::endl; } catch(...) { std::cout << "Unknown error" << std::endl; } } template< typename Perc > void save(const Perc& perc, std::string name) { typename Perc::Memento memento = perc.getMemento(); std::ofstream strm(name); cereal::XMLOutputArchive oa(strm); oa << memento; strm.flush(); } void calculateWeights(std::string imagesPath) { using namespace boost::filesystem; path directory(imagesPath); directory_iterator end_iter; std::vector< std::string > files; if(exists(directory) && is_directory(directory)) { for(directory_iterator dir_iter(directory); dir_iter != end_iter; ++dir_iter) { if(is_regular_file(dir_iter->status())) { files.push_back(dir_iter->path().string()); } } } std::cout << "Perceptron calculation started" << std::endl; static Perceptron tmp = readPerceptron("perceptron.xml"); static Algo algorithm(0.05f); algorithm.setMemento(tmp.getMemento()); std::vector< Algo::Prototype > prototypes; for(auto image : files) { if(!boost::filesystem::is_directory(image)) { try { Algo::Prototype proto; readImage(image, std::get< 0 >(proto).begin()); std::fill(std::get< 1 >(proto).begin(), std::get< 1 >(proto).end(), 0.f); char ch = path(image).filename().string()[0]; size_t pos = alphabet.find(ch); std::get< 1 >(proto)[pos] = 1.0f; prototypes.push_back(proto); } catch(const std::exception&) { std::cout << "Invalid image found :" << image << std::endl; } } } auto errorFunc = [](unsigned int epoch, VarType error) { // if(epoch % 3 == 0) { std::cout << "Epoch:" << epoch << " error:" << error << std::endl; //} return error > 0.001f; }; static Perceptron perceptron = algorithm.calculate(prototypes.begin(), prototypes.end(), errorFunc); save(perceptron, "perceptron.xml"); } int main(int argc, char** argv) { int result = -1; if(argc == 3) { recognize(argv[1], argv[2]); result = 0; } else if(argc == 2) { calculateWeights(argv[1]); result = 0; } else { std::cout << std::endl << "Usage : " << std::endl << std::endl; std::cout << "./ocr [folder] where [folder] is a directory with your " "samples, this command will generate a perceptron.xml file" << std::endl << std::endl; std::cout << "./ocr perceptron.xml [file] where [file] is a png image " "which has to be recognized" << std::endl << std::endl; } return result; } <commit_msg>Fix build break<commit_after>#include <NeuralNetwork/LearningAlgorithm/BackPropagation/BepAlgorithm.h> #include <NeuralNetwork/NeuralLayer/ConvolutionLayer.h> #include <NeuralNetwork/NeuralLayer/NeuralLayer.h> #include <NeuralNetwork/Neuron/ActivationFunction/BiopolarSigmoidFunction.h> #include <NeuralNetwork/Neuron/ActivationFunction/LogScaleSoftmaxFunction.h> #include <NeuralNetwork/Neuron/ActivationFunction/SigmoidFunction.h> #include <NeuralNetwork/Neuron/ActivationFunction/SoftmaxFunction.h> #include <NeuralNetwork/Neuron/ActivationFunction/TanhFunction.h> #include <NeuralNetwork/Neuron/ActivationFunction/ReluFunction.h> #include <NeuralNetwork/Neuron/Neuron.h> #include <NeuralNetwork/Perceptron/Perceptron.h> //#include <NeuralNetwork/NeuralLayer/OpenCLNeuralLayer.h> #include <NeuralNetwork/Config.h> #include <Utilities/MPL/Tuple.h> #ifndef BOOST_SYSTEM_NO_DEPRECATED #define BOOST_SYSTEM_NO_DEPRECATED 1 #include <boost/filesystem.hpp> #undef BOOST_SYSTEM_NO_DEPRECATED #endif #define png_infopp_NULL (png_infopp) NULL #define int_p_NULL (int*)NULL #if defined(NN_CC_MSVC) #pragma warning(push) // This function or variable may be unsafe #pragma warning(disable : 4996) #endif #include <boost/gil/channel_algorithm.hpp> #include <boost/gil/channel.hpp> #include <boost/gil/gil_all.hpp> #include <boost/gil/image.hpp> #include <boost/gil/extension/io/png/old.hpp> #include <boost/gil/extension/numeric/sampler.hpp> #include <boost/gil/extension/numeric/resample.hpp> #include <boost/gil/extension/dynamic_image/any_image.hpp> #include <boost/gil/extension/dynamic_image/dynamic_image_all.hpp> #include <cereal/archives/xml.hpp> #include <cereal/types/array.hpp> #include <cereal/types/tuple.hpp> #include <cereal/types/vector.hpp> #include <tuple> #include <cmath> #include <fstream> #include <iomanip> #include <iostream> #include <set> typedef long double VarType; namespace { using namespace boost::gil; using namespace boost::gil::detail; const std::string alphabet("0123456789"); constexpr std::size_t width = 49; constexpr std::size_t height = 67; constexpr std::size_t inputsNumber = width * height; constexpr std::size_t margin = 15; constexpr std::size_t stride = 10; } // namespace using ConvolutionGrid = typename nn::ConvolutionGrid< width, height, stride, margin >::define; using ConvolutionGrid2 = typename nn::ConvolutionGrid< width / stride, height / stride, 2, 5 >::define; using Perceptron = nn::Perceptron< VarType, nn::ConvolutionLayer< nn::NeuralLayer, nn::Neuron, nn::ReluFunction, inputsNumber, ConvolutionGrid >, nn::NeuralLayer< nn::Neuron, nn::SoftmaxFunction, 10, 1000 > >; using Algo = nn::bp::BepAlgorithm< Perceptron, nn::bp::CrossEntropyError >; template< typename Out > struct halfdiff_cast_channels { template< typename T > Out operator()(const T& in1, const T& in2) const { return Out((in1 - in2) / 2); } }; template< typename SrcView, typename DstView > void convert_color(const SrcView& src, const DstView& dst) { typedef typename channel_type< DstView >::type d_channel_t; typedef typename channel_convert_to_unsigned< d_channel_t >::type channel_t; typedef pixel< channel_t, gray_layout_t > gray_pixel_t; copy_pixels(color_converted_view< gray_pixel_t >(src), dst); } template< typename Iterator > void readImage(std::string fileName, Iterator out) { using namespace boost::gil; using namespace nn; using namespace nn::bp; rgb8_image_t srcImg; png_read_image(fileName.c_str(), srcImg); gray8_image_t dstImg(srcImg.dimensions()); gray8_pixel_t white(255); fill_pixels(view(dstImg), white); gray8_image_t grayImage(srcImg.dimensions()); convert_color(view(srcImg), view(grayImage)); auto grayView = view(grayImage); gray8_image_t scaledImage(width, height); resize_view(grayView, view(scaledImage), bilinear_sampler()); auto srcView = view(scaledImage); for(int y = 0; y < srcView.height(); ++y) { gray8c_view_t::x_iterator src_it(srcView.row_begin(y)); for(int x = 0; x < srcView.width(); ++x) { *out = src_it[x]; out++; } } } Perceptron readPerceptron(std::string fileName) { Perceptron perceptron; if(boost::filesystem::exists(fileName.c_str())) { std::ifstream file(fileName); if(file.good()) { Perceptron::Memento memento; cereal::XMLInputArchive ia(file); ia >> memento; perceptron.setMemento(memento); } else { throw std::logic_error("Invalid perceptron file name"); } } return perceptron; } void recognize(std::string perceptron, std::string image) { try { std::array< VarType, inputsNumber > inputs = {0}; readImage(image, inputs.begin()); std::vector< VarType > result(alphabet.length(), VarType(0.f)); readPerceptron(perceptron) .calculate(inputs.begin(), inputs.end(), result.begin()); for(unsigned int i = 0; i < result.size(); i++) { std::cout << "Symbol: " << alphabet[i] << " " << result[i] << std::endl; } } catch(const std::exception& e) { std::cout << e.what() << std::endl; } catch(...) { std::cout << "Unknown error" << std::endl; } } template< typename Perc > void save(const Perc& perc, std::string name) { typename Perc::Memento memento = perc.getMemento(); std::ofstream strm(name); cereal::XMLOutputArchive oa(strm); oa << memento; strm.flush(); } void calculateWeights(std::string imagesPath) { using namespace boost::filesystem; path directory(imagesPath); directory_iterator end_iter; std::vector< std::string > files; if(exists(directory) && is_directory(directory)) { for(directory_iterator dir_iter(directory); dir_iter != end_iter; ++dir_iter) { if(is_regular_file(dir_iter->status())) { files.push_back(dir_iter->path().string()); } } } std::cout << "Perceptron calculation started" << std::endl; static Perceptron tmp = readPerceptron("perceptron.xml"); static Algo algorithm(0.05f); algorithm.setMemento(tmp.getMemento()); std::vector< Algo::Prototype > prototypes; for(auto image : files) { if(!boost::filesystem::is_directory(image)) { try { Algo::Prototype proto; readImage(image, std::get< 0 >(proto).begin()); std::fill(std::get< 1 >(proto).begin(), std::get< 1 >(proto).end(), 0.f); char ch = path(image).filename().string()[0]; size_t pos = alphabet.find(ch); std::get< 1 >(proto)[pos] = 1.0f; prototypes.push_back(proto); } catch(const std::exception&) { std::cout << "Invalid image found :" << image << std::endl; } } } auto errorFunc = [](unsigned int epoch, VarType error) { // if(epoch % 3 == 0) { std::cout << "Epoch:" << epoch << " error:" << error << std::endl; //} return error > 0.001f; }; static Perceptron perceptron = algorithm.calculate(prototypes.begin(), prototypes.end(), errorFunc); save(perceptron, "perceptron.xml"); } int main(int argc, char** argv) { int result = -1; if(argc == 3) { recognize(argv[1], argv[2]); result = 0; } else if(argc == 2) { calculateWeights(argv[1]); result = 0; } else { std::cout << std::endl << "Usage : " << std::endl << std::endl; std::cout << "./ocr [folder] where [folder] is a directory with your " "samples, this command will generate a perceptron.xml file" << std::endl << std::endl; std::cout << "./ocr perceptron.xml [file] where [file] is a png image " "which has to be recognized" << std::endl << std::endl; } return result; } <|endoftext|>
<commit_before>#include "skp_local_application.h" #include "skpLog.h" #include "gmock/gmock.h" //#include <gperftools/profiler.h> //#include <gperftools/heap-profiler.h> SkpLog *g_log = skp_null; int main(int argc, char *argv[]) { //ProfilerStart(NULL); //HeapProfilerStart(NULL); g_log = new SkpLog("", "main_server_", Skp::LOG_ERROR, /*Skp::LOG_TO_FILE | */Skp::LOG_TO_STDERR,skp_true,0,1024 * 1024 *100, skp_true); // testing::InitGoogleMock(&argc, argv); // return RUN_ALL_TESTS(); SkpLocalApplication app(argc, argv); int res = app.exec(); //ProfilerStop(); //HeapProfilerStop(); return res; } <commit_msg>update<commit_after>#include "skp_local_application.h" #include "skpLog.h" #include "gmock/gmock.h" #include <gperftools/profiler.h> #include <gperftools/heap-profiler.h> SkpLog *g_log = skp_null; int main(int argc, char *argv[]) { //ProfilerStart(NULL); //HeapProfilerStart(NULL); g_log = new SkpLog("", "main_server_", Skp::LOG_ERROR, /*Skp::LOG_TO_FILE | */Skp::LOG_TO_STDERR,skp_true,0,1024 * 1024 *100, skp_true); // testing::InitGoogleMock(&argc, argv); // return RUN_ALL_TESTS(); SkpLocalApplication app(argc, argv); int res = app.exec(); //ProfilerStop(); //HeapProfilerStop(); return res; } <|endoftext|>
<commit_before>/* * CrissCross * A multi-purpose cross-platform library. * * A product of Uplink Laboratories. * * (c) 2006-2009 Steven Noonan. * Licensed under the New BSD License. * */ #include <crisscross/universal_include.h> #include <crisscross/debug.h> #include <crisscross/filewriter.h> using namespace CrissCross::IO; #ifdef TARGET_OS_MACOSX #include <dlfcn.h> #endif #ifndef ENABLE_SYMBOL_ENGINE #ifdef TARGET_OS_WINDOWS #pragma warning (disable: 4311) #endif #else #include <dbghelp.h> #pragma warning (disable: 4312) #pragma comment( lib, "dbghelp" ) class SymbolEngine { public: static SymbolEngine & instance(); std::string addressToString(DWORD address); void StackTrace(PCONTEXT _pContext, CoreIOWriter * _outputBuffer); private: SymbolEngine(SymbolEngine const &); SymbolEngine & operator=(SymbolEngine const &); SymbolEngine(); HANDLE hProcess; public: ~SymbolEngine(); private: }; SymbolEngine & SymbolEngine::instance() { static SymbolEngine theEngine; return theEngine; } SymbolEngine::SymbolEngine() { hProcess = GetCurrentProcess(); DWORD dwOpts = SymGetOptions(); dwOpts |= SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS; SymSetOptions(dwOpts); ::SymInitialize(hProcess, 0, true); } SymbolEngine::~SymbolEngine() { ::SymCleanup(hProcess); } std::string SymbolEngine::addressToString(DWORD address) { char buffer[4096]; /* First the raw address */ sprintf(buffer, "0x%08x", address); /* Then any name for the symbol */ struct tagSymInfo { IMAGEHLP_SYMBOL symInfo; char nameBuffer[4 * 256]; } SymInfo = { { sizeof(IMAGEHLP_SYMBOL) } }; IMAGEHLP_SYMBOL * pSym = &SymInfo.symInfo; pSym->MaxNameLength = sizeof(SymInfo) - offsetof(tagSymInfo, symInfo.Name); DWORD dwDisplacement; if (SymGetSymFromAddr(GetCurrentProcess(), ( DWORD )address, &dwDisplacement, pSym)) { strcat(buffer, " "); strcat(buffer, pSym->Name); /*if ( dwDisplacement != 0 ) * oss << "+0x" << std::hex << dwDisplacement << std::dec; */ } /* Finally any file/line number */ IMAGEHLP_LINE lineInfo = { sizeof(IMAGEHLP_LINE) }; if (SymGetLineFromAddr (GetCurrentProcess(), ( DWORD )address, &dwDisplacement, &lineInfo)) { const char *pDelim = strrchr(lineInfo.FileName, '\\'); char temp[1024]; sprintf(temp, " at %s(%u)", (pDelim ? pDelim + 1 : lineInfo.FileName), lineInfo.LineNumber); strcat(buffer, temp); } return std::string(buffer); } void SymbolEngine::StackTrace(PCONTEXT _pContext, CoreIOWriter * _outputBuffer) { _outputBuffer->WriteLine(" Frame Address Code"); STACKFRAME stackFrame = { 0 }; stackFrame.AddrPC.Offset = _pContext->Eip; stackFrame.AddrPC.Mode = AddrModeFlat; stackFrame.AddrFrame.Offset = _pContext->Ebp; stackFrame.AddrFrame.Mode = AddrModeFlat; stackFrame.AddrStack.Offset = _pContext->Esp; stackFrame.AddrStack.Mode = AddrModeFlat; while (::StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, GetCurrentThread(), /* this value doesn't matter much if previous one is a real handle */ &stackFrame, _pContext, NULL, ::SymFunctionTableAccess, ::SymGetModuleBase, NULL)) { _outputBuffer->WriteLine(" 0x%08xd %s", stackFrame.AddrFrame.Offset, addressToString(stackFrame.AddrPC. Offset).c_str()); } } #endif void CrissCross::Debug::PrintStackTrace(CrissCross::IO::CoreIOWriter * _outputBuffer) { #if !defined (TARGET_OS_NETBSD) && !defined (TARGET_OS_FREEBSD) && !defined (TARGET_OS_OPENBSD) #ifdef ENABLE_SYMBOL_ENGINE CONTEXT context = { CONTEXT_FULL }; ::GetThreadContext(GetCurrentThread(), &context); _asm call $ + 5; _asm pop eax; _asm mov context.Eip, eax; _asm mov eax, esp; _asm mov context.Esp, eax; _asm mov context.Ebp, ebp; SymbolEngine::instance().StackTrace(&context, _outputBuffer); #elif defined (ENABLE_BACKTRACE) #if defined (TARGET_OS_MACOSX) int (*backtrace)(void * *, int); char * *(*backtrace_symbols)(void * const *, int); backtrace = (int(*) (void * *, int))dlsym(RTLD_DEFAULT, "backtrace"); backtrace_symbols = (char * *(*)(void * const *, int))dlsym(RTLD_DEFAULT, "backtrace_symbols"); #endif void *array[256]; int size; char * *strings; int i; memset(array, 0, sizeof(void *) * 256); /* use -rdynamic flag when compiling */ size = backtrace(array, 256); strings = backtrace_symbols(array, size); _outputBuffer->WriteLine("Obtained %d stack frames.", size); std::string bt = ""; for (i = 0; i < size; i++) { #if defined (TARGET_OS_LINUX) bt += strings[i]; int status; /* extract the identifier from strings[i]. It's inside of parens. */ char * firstparen = ::strchr(strings[i], '('); char * lastparen = ::strchr(strings[i], '+'); if (firstparen != 0 && lastparen != 0 && firstparen < lastparen) { bt += ": "; *lastparen = '\0'; char * realname = abi::__cxa_demangle(firstparen + 1, 0, 0, &status); if (realname != NULL) { bt += realname; } free(realname); } #elif defined (TARGET_OS_MACOSX) char *addr = ::strstr(strings[i], "0x"); char *mangled = ::strchr(addr, ' ') + 1; char *postmangle = ::strchr(mangled, ' '); bt += addr; int status; if (addr && mangled) { if (postmangle) *postmangle = '\0'; char *realname = abi::__cxa_demangle(mangled, 0, 0, &status); if (realname) { bt += ": "; bt += realname; } free(realname); } #endif bt += "\n"; } _outputBuffer->WriteLine("%s\n", bt.c_str()); free(strings); #else /* defined(ENABLE_SYMBOL_ENGINE) || defined(ENABLE_BACKTRACE) */ _outputBuffer->WriteLine("FAIL: backtrace() function not available."); #endif #else /* !defined (TARGET_OS_NETBSD) && !defined (TARGET_OS_FREEBSD) && !defined (TARGET_OS_OPENBSD) */ _outputBuffer->WriteLine("Stack traces are not implemented for this platform."); #endif } #ifndef USE_FAST_ASSERT void Assert(bool _condition, const char *_testcase, const char *_file, int _line) { if (!_condition) { char buffer[10240]; sprintf(buffer, "Assertion failed : '%s'\nFile: %s\nLine: %d\n\n", _testcase, _file, _line); fprintf(stderr, "%s", buffer); fprintf(stderr, "=== STACK TRACE ===\n"); CoreIOWriter *stderror = new CoreIOWriter(stderr, false, CC_LN_LF); PrintStackTrace(stderror); delete stderror; #ifndef _DEBUG abort(); #else _ASSERT(_condition); #endif } } #endif <commit_msg>addressToString: fix awkward line breaks in SymGetLineFromAddr call<commit_after>/* * CrissCross * A multi-purpose cross-platform library. * * A product of Uplink Laboratories. * * (c) 2006-2009 Steven Noonan. * Licensed under the New BSD License. * */ #include <crisscross/universal_include.h> #include <crisscross/debug.h> #include <crisscross/filewriter.h> using namespace CrissCross::IO; #ifdef TARGET_OS_MACOSX #include <dlfcn.h> #endif #ifndef ENABLE_SYMBOL_ENGINE #ifdef TARGET_OS_WINDOWS #pragma warning (disable: 4311) #endif #else #include <dbghelp.h> #pragma warning (disable: 4312) #pragma comment( lib, "dbghelp" ) class SymbolEngine { public: static SymbolEngine & instance(); std::string addressToString(DWORD address); void StackTrace(PCONTEXT _pContext, CoreIOWriter * _outputBuffer); private: SymbolEngine(SymbolEngine const &); SymbolEngine & operator=(SymbolEngine const &); SymbolEngine(); HANDLE hProcess; public: ~SymbolEngine(); private: }; SymbolEngine & SymbolEngine::instance() { static SymbolEngine theEngine; return theEngine; } SymbolEngine::SymbolEngine() { hProcess = GetCurrentProcess(); DWORD dwOpts = SymGetOptions(); dwOpts |= SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS; SymSetOptions(dwOpts); ::SymInitialize(hProcess, 0, true); } SymbolEngine::~SymbolEngine() { ::SymCleanup(hProcess); } std::string SymbolEngine::addressToString(DWORD address) { char buffer[4096]; /* First the raw address */ sprintf(buffer, "0x%08x", address); /* Then any name for the symbol */ struct tagSymInfo { IMAGEHLP_SYMBOL symInfo; char nameBuffer[4 * 256]; } SymInfo = { { sizeof(IMAGEHLP_SYMBOL) } }; IMAGEHLP_SYMBOL * pSym = &SymInfo.symInfo; pSym->MaxNameLength = sizeof(SymInfo) - offsetof(tagSymInfo, symInfo.Name); DWORD dwDisplacement; if (SymGetSymFromAddr(GetCurrentProcess(), ( DWORD )address, &dwDisplacement, pSym)) { strcat(buffer, " "); strcat(buffer, pSym->Name); /*if ( dwDisplacement != 0 ) * oss << "+0x" << std::hex << dwDisplacement << std::dec; */ } /* Finally any file/line number */ IMAGEHLP_LINE lineInfo = { sizeof(IMAGEHLP_LINE) }; if (SymGetLineFromAddr(GetCurrentProcess(), (DWORD)address, &dwDisplacement, &lineInfo)) { const char *pDelim = strrchr(lineInfo.FileName, '\\'); char temp[1024]; sprintf(temp, " at %s(%u)", (pDelim ? pDelim + 1 : lineInfo.FileName), lineInfo.LineNumber); strcat(buffer, temp); } return std::string(buffer); } void SymbolEngine::StackTrace(PCONTEXT _pContext, CoreIOWriter * _outputBuffer) { _outputBuffer->WriteLine(" Frame Address Code"); STACKFRAME stackFrame = { 0 }; stackFrame.AddrPC.Offset = _pContext->Eip; stackFrame.AddrPC.Mode = AddrModeFlat; stackFrame.AddrFrame.Offset = _pContext->Ebp; stackFrame.AddrFrame.Mode = AddrModeFlat; stackFrame.AddrStack.Offset = _pContext->Esp; stackFrame.AddrStack.Mode = AddrModeFlat; while (::StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, GetCurrentThread(), /* this value doesn't matter much if previous one is a real handle */ &stackFrame, _pContext, NULL, ::SymFunctionTableAccess, ::SymGetModuleBase, NULL)) { _outputBuffer->WriteLine(" 0x%08xd %s", stackFrame.AddrFrame.Offset, addressToString(stackFrame.AddrPC. Offset).c_str()); } } #endif void CrissCross::Debug::PrintStackTrace(CrissCross::IO::CoreIOWriter * _outputBuffer) { #if !defined (TARGET_OS_NETBSD) && !defined (TARGET_OS_FREEBSD) && !defined (TARGET_OS_OPENBSD) #ifdef ENABLE_SYMBOL_ENGINE CONTEXT context = { CONTEXT_FULL }; ::GetThreadContext(GetCurrentThread(), &context); _asm call $ + 5; _asm pop eax; _asm mov context.Eip, eax; _asm mov eax, esp; _asm mov context.Esp, eax; _asm mov context.Ebp, ebp; SymbolEngine::instance().StackTrace(&context, _outputBuffer); #elif defined (ENABLE_BACKTRACE) #if defined (TARGET_OS_MACOSX) int (*backtrace)(void * *, int); char * *(*backtrace_symbols)(void * const *, int); backtrace = (int(*) (void * *, int))dlsym(RTLD_DEFAULT, "backtrace"); backtrace_symbols = (char * *(*)(void * const *, int))dlsym(RTLD_DEFAULT, "backtrace_symbols"); #endif void *array[256]; int size; char * *strings; int i; memset(array, 0, sizeof(void *) * 256); /* use -rdynamic flag when compiling */ size = backtrace(array, 256); strings = backtrace_symbols(array, size); _outputBuffer->WriteLine("Obtained %d stack frames.", size); std::string bt = ""; for (i = 0; i < size; i++) { #if defined (TARGET_OS_LINUX) bt += strings[i]; int status; /* extract the identifier from strings[i]. It's inside of parens. */ char * firstparen = ::strchr(strings[i], '('); char * lastparen = ::strchr(strings[i], '+'); if (firstparen != 0 && lastparen != 0 && firstparen < lastparen) { bt += ": "; *lastparen = '\0'; char * realname = abi::__cxa_demangle(firstparen + 1, 0, 0, &status); if (realname != NULL) { bt += realname; } free(realname); } #elif defined (TARGET_OS_MACOSX) char *addr = ::strstr(strings[i], "0x"); char *mangled = ::strchr(addr, ' ') + 1; char *postmangle = ::strchr(mangled, ' '); bt += addr; int status; if (addr && mangled) { if (postmangle) *postmangle = '\0'; char *realname = abi::__cxa_demangle(mangled, 0, 0, &status); if (realname) { bt += ": "; bt += realname; } free(realname); } #endif bt += "\n"; } _outputBuffer->WriteLine("%s\n", bt.c_str()); free(strings); #else /* defined(ENABLE_SYMBOL_ENGINE) || defined(ENABLE_BACKTRACE) */ _outputBuffer->WriteLine("FAIL: backtrace() function not available."); #endif #else /* !defined (TARGET_OS_NETBSD) && !defined (TARGET_OS_FREEBSD) && !defined (TARGET_OS_OPENBSD) */ _outputBuffer->WriteLine("Stack traces are not implemented for this platform."); #endif } #ifndef USE_FAST_ASSERT void Assert(bool _condition, const char *_testcase, const char *_file, int _line) { if (!_condition) { char buffer[10240]; sprintf(buffer, "Assertion failed : '%s'\nFile: %s\nLine: %d\n\n", _testcase, _file, _line); fprintf(stderr, "%s", buffer); fprintf(stderr, "=== STACK TRACE ===\n"); CoreIOWriter *stderror = new CoreIOWriter(stderr, false, CC_LN_LF); PrintStackTrace(stderror); delete stderror; #ifndef _DEBUG abort(); #else _ASSERT(_condition); #endif } } #endif <|endoftext|>
<commit_before>#include <cstdio> #include <vector> #include <algorithm> using namespace std; int bsearch(vector<int> v, int lower, int upper, int target) { int pos = (upper + lower) / 2; if (target == v[pos]) return pos; else if (upper == lower) return -1; else { if (target < v[pos]) return bsearch(v, lower, pos, target); else return bsearch(v, pos + 1, upper, target); } } int main() { int a, b, kase = 1; while (1) { scanf ("%d %d ", &a, &b); if (!a && !b) break; int x; vector<int> v; for (int i = 0; i < a; i++) { scanf ("%d ", &x); v.push_back(x); } sort(v.begin(), v.end()); printf ("CASE# %d:\n", kase); for (int i = 0; i < b; i++) { scanf ("%d ", &x); int pos = bsearch(v, 0, v.size() - 1, x); if (pos != -1) { printf ("%d found at %d\n", x, pos + 1); } else { printf ("%d not found\n", x); } } kase++; } return 0; } <commit_msg>remove p1025.cpp TLE<commit_after><|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2013-2015 winlin 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 <htl_stdinc.hpp> // system #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <sys/time.h> #include <inttypes.h> // socket #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> // dns #include <netdb.h> #include <string> using namespace std; #include <htl_core_error.hpp> #include <htl_core_log.hpp> #include <htl_os_st.hpp> StStatistic::StStatistic(){ starttime = StUtility::GetCurrentTime(); task_duration = 0; threads = alive = 0; nread = nwrite = 0; tasks = err_tasks = sub_tasks = err_sub_tasks = 0; } StStatistic::~StStatistic(){ } void StStatistic::OnRead(int /*tid*/, ssize_t nread_bytes){ this->nread += nread_bytes; } void StStatistic::OnWrite(int /*tid*/, ssize_t nwrite_bytes){ this->nwrite += nwrite_bytes; } void StStatistic::OnThreadRun(int /*tid*/){ threads++; } void StStatistic::OnThreadQuit(int /*tid*/){ threads--; } void StStatistic::OnTaskStart(int /*tid*/, std::string /*task_url*/){ alive++; tasks++; } void StStatistic::OnTaskError(int /*tid*/, int duration_seconds){ alive--; err_tasks++; this->task_duration += duration_seconds * 1000; } void StStatistic::OnTaskEnd(int /*tid*/, int duration_seconds){ alive--; this->task_duration += duration_seconds * 1000; } void StStatistic::OnSubTaskStart(int /*tid*/, std::string /*sub_task_url*/){ sub_tasks++; } void StStatistic::OnSubTaskError(int /*tid*/, int duration_seconds){ err_sub_tasks++; this->task_duration += duration_seconds * 1000; } void StStatistic::OnSubTaskEnd(int /*tid*/, int duration_seconds){ this->task_duration += duration_seconds * 1000; } void StStatistic::DoReport(double sleep_ms){ for(;;){ int64_t duration = StUtility::GetCurrentTime() - starttime; double read_mbps = 0, write_mbps = 0; if(duration > 0){ read_mbps = nread * 8.0 / duration / 1000; write_mbps = nwrite * 8.0 / duration / 1000; } double avarage_duration = task_duration/1000.0; if(tasks > 0){ avarage_duration /= tasks; } LReport("[report] [%d] threads:%d alive:%d duration:%.0f tduration:%.0f nread:%.2f nwrite:%.2f " "tasks:%"PRId64" etasks:%"PRId64" stasks:%"PRId64" estasks:%"PRId64, getpid(), threads, alive, duration/1000.0, avarage_duration, read_mbps, write_mbps, tasks, err_tasks, sub_tasks, err_sub_tasks); st_usleep((st_utime_t)(sleep_ms * 1000)); } } StStatistic* statistic = new StStatistic(); StTask::StTask(){ static int _id = 0; id = ++_id; } StTask::~StTask(){ } int StTask::GetId(){ return id; } StFarm::StFarm(){ } StFarm::~StFarm(){ } int StFarm::Initialize(double report){ int ret = ERROR_SUCCESS; report_seconds = report; // use linux epoll. if(st_set_eventsys(ST_EVENTSYS_ALT) == -1){ ret = ERROR_ST_INITIALIZE; Error("st_set_eventsys use linux epoll failed. ret=%d", ret); return ret; } if(st_init() != 0){ ret = ERROR_ST_INITIALIZE; Error("st_init failed. ret=%d", ret); return ret; } StUtility::InitRandom(); return ret; } int StFarm::Spawn(StTask* task){ int ret = ERROR_SUCCESS; if(st_thread_create(st_thread_function, task, 0, 0) == NULL){ ret = ERROR_ST_THREAD_CREATE; Error("crate st_thread failed, ret=%d", ret); return ret; } Trace("create thread for task #%d success", task->GetId()); return ret; } int StFarm::WaitAll(){ int ret = ERROR_SUCCESS; // main thread turn to a report therad. statistic->DoReport(report_seconds * 1000); st_thread_exit(NULL); return ret; } void* StFarm::st_thread_function(void* args){ StTask* task = (StTask*)args; context->SetId(task->GetId()); statistic->OnThreadRun(task->GetId()); int ret = task->Process(); statistic->OnThreadQuit(task->GetId()); if(ret != ERROR_SUCCESS){ Warn("st task terminate with ret=%d", ret); } else{ Trace("st task terminate with ret=%d", ret); } delete task; return NULL; } StSocket::StSocket(){ sock_nfd = NULL; status = SocketInit; } StSocket::~StSocket(){ Close(); } st_netfd_t StSocket::GetStfd(){ return sock_nfd; } SocketStatus StSocket::Status(){ return status; } int StSocket::Connect(const char* ip, int port){ int ret = ERROR_SUCCESS; Close(); int sock = socket(AF_INET, SOCK_STREAM, 0); if(sock == -1){ ret = ERROR_SOCKET; Error("create socket error. ret=%d", ret); return ret; } int reuse_socket = 1; if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse_socket, sizeof(int)) == -1){ ret = ERROR_SOCKET; Error("setsockopt reuse-addr error. ret=%d", ret); return ret; } int keepalive_socket = 1; if(setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &keepalive_socket, sizeof(int)) == -1){ ret = ERROR_SOCKET; Error("setsockopt keep-alive error. ret=%d", ret); return ret; } sock_nfd = st_netfd_open_socket(sock); if(sock_nfd == NULL){ ret = ERROR_OPEN_SOCKET; Error("st_netfd_open_socket failed. ret=%d", ret); return ret; } Info("create socket(%d) success", sock); // connect to server sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = inet_addr(ip); if(st_connect(sock_nfd, (const struct sockaddr*)&addr, sizeof(sockaddr_in), ST_UTIME_NO_TIMEOUT) == -1){ ret = ERROR_CONNECT; Error("connect to server(%s:%d) error. ret=%d", ip, port, ret); return ret; } Info("connec to server %s at port %d success", ip, port); status = SocketConnected; return ret; } int StSocket::Read(const void* buf, size_t size, ssize_t* nread){ int ret = ERROR_SUCCESS; ssize_t got = st_read(sock_nfd, (void*)buf, size, ST_UTIME_NO_TIMEOUT); // On success a non-negative integer indicating the number of bytes actually read is returned // (a value of 0 means the network connection is closed or end of file is reached). if(got <= 0){ if(got == 0){ errno = ECONNRESET; } ret = ERROR_READ; status = SocketDisconnected; } if(got > 0){ statistic->OnRead(context->GetId(), got); } if (nread) { *nread = got; } return ret; } int StSocket::Readv(const iovec *iov, int iov_size, ssize_t* nread){ int ret = ERROR_SUCCESS; ssize_t got = st_readv(sock_nfd, iov, iov_size, ST_UTIME_NO_TIMEOUT); // On success a non-negative integer indicating the number of bytes actually read is returned // (a value of 0 means the network connection is closed or end of file is reached). if(got <= 0){ if(got == 0){ errno = ECONNRESET; } ret = ERROR_READ; status = SocketDisconnected; } if(got > 0){ statistic->OnRead(context->GetId(), got); } if (nread) { *nread = got; } return ret; } int StSocket::ReadFully(const void* buf, size_t size, ssize_t* nread){ int ret = ERROR_SUCCESS; ssize_t got = st_read_fully(sock_nfd, (void*)buf, size, ST_UTIME_NO_TIMEOUT); // On success a non-negative integer indicating the number of bytes actually read is returned // (a value less than nbyte means the network connection is closed or end of file is reached) if(got != (ssize_t)size){ if(got >= 0){ errno = ECONNRESET; } ret = ERROR_READ; status = SocketDisconnected; } if(got > 0){ statistic->OnRead(context->GetId(), got); } if (nread) { *nread = got; } return ret; } int StSocket::Write(const void* buf, size_t size, ssize_t* nwrite){ int ret = ERROR_SUCCESS; ssize_t writen = st_write(sock_nfd, (void*)buf, size, ST_UTIME_NO_TIMEOUT); if(writen <= 0){ ret = ERROR_SEND; status = SocketDisconnected; } if(writen > 0){ statistic->OnWrite(context->GetId(), writen); } if (nwrite) { *nwrite = writen; } return ret; } int StSocket::Writev(const iovec *iov, int iov_size, ssize_t* nwrite){ int ret = ERROR_SUCCESS; ssize_t writen = st_writev(sock_nfd, iov, iov_size, ST_UTIME_NO_TIMEOUT); if(writen <= 0){ ret = ERROR_SEND; status = SocketDisconnected; } if(writen > 0){ statistic->OnWrite(context->GetId(), writen); } if (nwrite) { *nwrite = writen; } return ret; } int StSocket::Close(){ int ret = ERROR_SUCCESS; if(sock_nfd == NULL){ return ret; } int fd = st_netfd_fileno(sock_nfd); if(st_netfd_close(sock_nfd) != 0){ ret = ERROR_CLOSE; } sock_nfd = NULL; status = SocketDisconnected; ::close(fd); return ret; } int64_t StUtility::GetCurrentTime(){ timeval now; int ret = gettimeofday(&now, NULL); if(ret == -1){ Warn("gettimeofday error, ret=%d", ret); } // we must convert the tv_sec/tv_usec to int64_t. return ((int64_t)now.tv_sec)*1000 + ((int64_t)now.tv_usec) / 1000; } void StUtility::InitRandom(){ timeval now; if(gettimeofday(&now, NULL) == -1){ srand(0); return; } srand(now.tv_sec * 1000000 + now.tv_usec); } st_utime_t StUtility::BuildRandomMTime(double sleep_seconds){ if(sleep_seconds <= 0){ return 0 * 1000; } // 80% consts value. // 40% random value. // to get more graceful random time to mocking HLS client. st_utime_t sleep_ms = (int)(sleep_seconds * 1000 * 0.7) + rand() % (int)(sleep_seconds * 1000 * 0.4); return sleep_ms; } int StUtility::DnsResolve(string host, string& ip){ int ret = ERROR_SUCCESS; if(inet_addr(host.c_str()) != INADDR_NONE){ ip = host; Info("dns resolve %s to %s", host.c_str(), ip.c_str()); return ret; } hostent* answer = gethostbyname(host.c_str()); if(answer == NULL){ ret = ERROR_DNS_RESOLVE; Error("dns resolve host %s error. ret=%d", host.c_str(), ret); return ret; } char ipv4[16]; memset(ipv4, 0, sizeof(ipv4)); for(int i = 0; i < answer->h_length; i++){ inet_ntop(AF_INET, answer->h_addr_list[i], ipv4, sizeof(ipv4)); Info("dns resolve host %s to %s.", host.c_str(), ipv4); break; } ip = ipv4; Info("dns resolve %s to %s", host.c_str(), ip.c_str()); return ret; } StLogContext::StLogContext(){ } StLogContext::~StLogContext(){ } void StLogContext::SetId(int id){ cache[st_thread_self()] = id; } int StLogContext::GetId(){ return cache[st_thread_self()]; } <commit_msg>Use 8MB stack for each st thread<commit_after>/* The MIT License (MIT) Copyright (c) 2013-2015 winlin 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 <htl_stdinc.hpp> // system #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <sys/time.h> #include <inttypes.h> // socket #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> // dns #include <netdb.h> #include <string> using namespace std; #include <htl_core_error.hpp> #include <htl_core_log.hpp> #include <htl_os_st.hpp> StStatistic::StStatistic(){ starttime = StUtility::GetCurrentTime(); task_duration = 0; threads = alive = 0; nread = nwrite = 0; tasks = err_tasks = sub_tasks = err_sub_tasks = 0; } StStatistic::~StStatistic(){ } void StStatistic::OnRead(int /*tid*/, ssize_t nread_bytes){ this->nread += nread_bytes; } void StStatistic::OnWrite(int /*tid*/, ssize_t nwrite_bytes){ this->nwrite += nwrite_bytes; } void StStatistic::OnThreadRun(int /*tid*/){ threads++; } void StStatistic::OnThreadQuit(int /*tid*/){ threads--; } void StStatistic::OnTaskStart(int /*tid*/, std::string /*task_url*/){ alive++; tasks++; } void StStatistic::OnTaskError(int /*tid*/, int duration_seconds){ alive--; err_tasks++; this->task_duration += duration_seconds * 1000; } void StStatistic::OnTaskEnd(int /*tid*/, int duration_seconds){ alive--; this->task_duration += duration_seconds * 1000; } void StStatistic::OnSubTaskStart(int /*tid*/, std::string /*sub_task_url*/){ sub_tasks++; } void StStatistic::OnSubTaskError(int /*tid*/, int duration_seconds){ err_sub_tasks++; this->task_duration += duration_seconds * 1000; } void StStatistic::OnSubTaskEnd(int /*tid*/, int duration_seconds){ this->task_duration += duration_seconds * 1000; } void StStatistic::DoReport(double sleep_ms){ for(;;){ int64_t duration = StUtility::GetCurrentTime() - starttime; double read_mbps = 0, write_mbps = 0; if(duration > 0){ read_mbps = nread * 8.0 / duration / 1000; write_mbps = nwrite * 8.0 / duration / 1000; } double avarage_duration = task_duration/1000.0; if(tasks > 0){ avarage_duration /= tasks; } LReport("[report] [%d] threads:%d alive:%d duration:%.0f tduration:%.0f nread:%.2f nwrite:%.2f " "tasks:%"PRId64" etasks:%"PRId64" stasks:%"PRId64" estasks:%"PRId64, getpid(), threads, alive, duration/1000.0, avarage_duration, read_mbps, write_mbps, tasks, err_tasks, sub_tasks, err_sub_tasks); st_usleep((st_utime_t)(sleep_ms * 1000)); } } StStatistic* statistic = new StStatistic(); StTask::StTask(){ static int _id = 0; id = ++_id; } StTask::~StTask(){ } int StTask::GetId(){ return id; } StFarm::StFarm(){ } StFarm::~StFarm(){ } int StFarm::Initialize(double report){ int ret = ERROR_SUCCESS; report_seconds = report; // use linux epoll. if(st_set_eventsys(ST_EVENTSYS_ALT) == -1){ ret = ERROR_ST_INITIALIZE; Error("st_set_eventsys use linux epoll failed. ret=%d", ret); return ret; } if(st_init() != 0){ ret = ERROR_ST_INITIALIZE; Error("st_init failed. ret=%d", ret); return ret; } StUtility::InitRandom(); return ret; } int StFarm::Spawn(StTask* task){ int ret = ERROR_SUCCESS; if(st_thread_create(st_thread_function, task, 0, 8 * 1024 * 1024) == NULL){ ret = ERROR_ST_THREAD_CREATE; Error("crate st_thread failed, ret=%d", ret); return ret; } Trace("create thread for task #%d success", task->GetId()); return ret; } int StFarm::WaitAll(){ int ret = ERROR_SUCCESS; // main thread turn to a report therad. statistic->DoReport(report_seconds * 1000); st_thread_exit(NULL); return ret; } void* StFarm::st_thread_function(void* args){ StTask* task = (StTask*)args; context->SetId(task->GetId()); statistic->OnThreadRun(task->GetId()); int ret = task->Process(); statistic->OnThreadQuit(task->GetId()); if(ret != ERROR_SUCCESS){ Warn("st task terminate with ret=%d", ret); } else{ Trace("st task terminate with ret=%d", ret); } delete task; return NULL; } StSocket::StSocket(){ sock_nfd = NULL; status = SocketInit; } StSocket::~StSocket(){ Close(); } st_netfd_t StSocket::GetStfd(){ return sock_nfd; } SocketStatus StSocket::Status(){ return status; } int StSocket::Connect(const char* ip, int port){ int ret = ERROR_SUCCESS; Close(); int sock = socket(AF_INET, SOCK_STREAM, 0); if(sock == -1){ ret = ERROR_SOCKET; Error("create socket error. ret=%d", ret); return ret; } int reuse_socket = 1; if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse_socket, sizeof(int)) == -1){ ret = ERROR_SOCKET; Error("setsockopt reuse-addr error. ret=%d", ret); return ret; } int keepalive_socket = 1; if(setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &keepalive_socket, sizeof(int)) == -1){ ret = ERROR_SOCKET; Error("setsockopt keep-alive error. ret=%d", ret); return ret; } sock_nfd = st_netfd_open_socket(sock); if(sock_nfd == NULL){ ret = ERROR_OPEN_SOCKET; Error("st_netfd_open_socket failed. ret=%d", ret); return ret; } Info("create socket(%d) success", sock); // connect to server sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = inet_addr(ip); if(st_connect(sock_nfd, (const struct sockaddr*)&addr, sizeof(sockaddr_in), ST_UTIME_NO_TIMEOUT) == -1){ ret = ERROR_CONNECT; Error("connect to server(%s:%d) error. ret=%d", ip, port, ret); return ret; } Info("connec to server %s at port %d success", ip, port); status = SocketConnected; return ret; } int StSocket::Read(const void* buf, size_t size, ssize_t* nread){ int ret = ERROR_SUCCESS; ssize_t got = st_read(sock_nfd, (void*)buf, size, ST_UTIME_NO_TIMEOUT); // On success a non-negative integer indicating the number of bytes actually read is returned // (a value of 0 means the network connection is closed or end of file is reached). if(got <= 0){ if(got == 0){ errno = ECONNRESET; } ret = ERROR_READ; status = SocketDisconnected; } if(got > 0){ statistic->OnRead(context->GetId(), got); } if (nread) { *nread = got; } return ret; } int StSocket::Readv(const iovec *iov, int iov_size, ssize_t* nread){ int ret = ERROR_SUCCESS; ssize_t got = st_readv(sock_nfd, iov, iov_size, ST_UTIME_NO_TIMEOUT); // On success a non-negative integer indicating the number of bytes actually read is returned // (a value of 0 means the network connection is closed or end of file is reached). if(got <= 0){ if(got == 0){ errno = ECONNRESET; } ret = ERROR_READ; status = SocketDisconnected; } if(got > 0){ statistic->OnRead(context->GetId(), got); } if (nread) { *nread = got; } return ret; } int StSocket::ReadFully(const void* buf, size_t size, ssize_t* nread){ int ret = ERROR_SUCCESS; ssize_t got = st_read_fully(sock_nfd, (void*)buf, size, ST_UTIME_NO_TIMEOUT); // On success a non-negative integer indicating the number of bytes actually read is returned // (a value less than nbyte means the network connection is closed or end of file is reached) if(got != (ssize_t)size){ if(got >= 0){ errno = ECONNRESET; } ret = ERROR_READ; status = SocketDisconnected; } if(got > 0){ statistic->OnRead(context->GetId(), got); } if (nread) { *nread = got; } return ret; } int StSocket::Write(const void* buf, size_t size, ssize_t* nwrite){ int ret = ERROR_SUCCESS; ssize_t writen = st_write(sock_nfd, (void*)buf, size, ST_UTIME_NO_TIMEOUT); if(writen <= 0){ ret = ERROR_SEND; status = SocketDisconnected; } if(writen > 0){ statistic->OnWrite(context->GetId(), writen); } if (nwrite) { *nwrite = writen; } return ret; } int StSocket::Writev(const iovec *iov, int iov_size, ssize_t* nwrite){ int ret = ERROR_SUCCESS; ssize_t writen = st_writev(sock_nfd, iov, iov_size, ST_UTIME_NO_TIMEOUT); if(writen <= 0){ ret = ERROR_SEND; status = SocketDisconnected; } if(writen > 0){ statistic->OnWrite(context->GetId(), writen); } if (nwrite) { *nwrite = writen; } return ret; } int StSocket::Close(){ int ret = ERROR_SUCCESS; if(sock_nfd == NULL){ return ret; } int fd = st_netfd_fileno(sock_nfd); if(st_netfd_close(sock_nfd) != 0){ ret = ERROR_CLOSE; } sock_nfd = NULL; status = SocketDisconnected; ::close(fd); return ret; } int64_t StUtility::GetCurrentTime(){ timeval now; int ret = gettimeofday(&now, NULL); if(ret == -1){ Warn("gettimeofday error, ret=%d", ret); } // we must convert the tv_sec/tv_usec to int64_t. return ((int64_t)now.tv_sec)*1000 + ((int64_t)now.tv_usec) / 1000; } void StUtility::InitRandom(){ timeval now; if(gettimeofday(&now, NULL) == -1){ srand(0); return; } srand(now.tv_sec * 1000000 + now.tv_usec); } st_utime_t StUtility::BuildRandomMTime(double sleep_seconds){ if(sleep_seconds <= 0){ return 0 * 1000; } // 80% consts value. // 40% random value. // to get more graceful random time to mocking HLS client. st_utime_t sleep_ms = (int)(sleep_seconds * 1000 * 0.7) + rand() % (int)(sleep_seconds * 1000 * 0.4); return sleep_ms; } int StUtility::DnsResolve(string host, string& ip){ int ret = ERROR_SUCCESS; if(inet_addr(host.c_str()) != INADDR_NONE){ ip = host; Info("dns resolve %s to %s", host.c_str(), ip.c_str()); return ret; } hostent* answer = gethostbyname(host.c_str()); if(answer == NULL){ ret = ERROR_DNS_RESOLVE; Error("dns resolve host %s error. ret=%d", host.c_str(), ret); return ret; } char ipv4[16]; memset(ipv4, 0, sizeof(ipv4)); for(int i = 0; i < answer->h_length; i++){ inet_ntop(AF_INET, answer->h_addr_list[i], ipv4, sizeof(ipv4)); Info("dns resolve host %s to %s.", host.c_str(), ipv4); break; } ip = ipv4; Info("dns resolve %s to %s", host.c_str(), ip.c_str()); return ret; } StLogContext::StLogContext(){ } StLogContext::~StLogContext(){ } void StLogContext::SetId(int id){ cache[st_thread_self()] = id; } int StLogContext::GetId(){ return cache[st_thread_self()]; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, 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 "config.h" #include "memcached.h" #include "runtime.h" #include <exception> Connection::Connection() : all_next(nullptr), all_prev(nullptr), sfd(INVALID_SOCKET), max_reqs_per_event(settings.default_reqs_per_event), nevents(0), sasl_conn(nullptr), state(conn_immediate_close), substate(bin_no_state), protocol(Protocol::Memcached), admin(false), registered_in_libevent(false), ev_flags(0), currentEvent(0), write_and_go(nullptr), write_and_free(nullptr), ritem(nullptr), rlbytes(0), item(nullptr), iov(nullptr), iovsize(0), iovused(0), msglist(nullptr), msgsize(0), msgused(0), msgcurr(0), msgbytes(0), request_addr_size(0), hdrsize(0), noreply(false), nodelay(false), refcount(0), supports_datatype(false), supports_mutation_extras(false), engine_storage(nullptr), start(0), cas(0), cmd(PROTOCOL_BINARY_CMD_INVALID), opaque(0), keylen(0), list_state(0), next(nullptr), thread(nullptr), aiostat(ENGINE_SUCCESS), ewouldblock(false), tap_iterator(nullptr), parent_port(0), dcp(0), cmd_context(nullptr), auth_context(nullptr), peername("unknown"), sockname("unknown") { MEMCACHED_CONN_CREATE(this); memset(&event, 0, sizeof(event)); memset(&request_addr, 0, sizeof(request_addr)); memset(&read, 0, sizeof(read)); memset(&write, 0, sizeof(write)); memset(&dynamic_buffer, 0, sizeof(dynamic_buffer)); memset(&ssl, 0, sizeof(ssl)); memset(&bucket, 0, sizeof(bucket)); memset(&binary_header, 0, sizeof(binary_header)); state = conn_immediate_close; sfd = INVALID_SOCKET; resetBufferSize(); } Connection::~Connection() { MEMCACHED_CONN_DESTROY(this); auth_destroy(auth_context); cbsasl_dispose(&sasl_conn); free(read.buf); free(write.buf); free(iov); free(msglist); cb_assert(reservedItems.empty()); for (auto *ptr : temp_alloc) { free(ptr); } } void Connection::resetBufferSize() { bool ret = true; if (iovsize != IOV_LIST_INITIAL) { void* mem = malloc(sizeof(struct iovec) * IOV_LIST_INITIAL); auto* ptr = reinterpret_cast<struct iovec*>(mem); if (ptr != NULL) { free(iov); iov = ptr; iovsize = IOV_LIST_INITIAL; } else { ret = false; } } if (msgsize != MSG_LIST_INITIAL) { void* mem = malloc(sizeof(struct msghdr) * MSG_LIST_INITIAL); auto* ptr = reinterpret_cast<struct msghdr*>(mem); if (ptr != NULL) { free(msglist); msglist = ptr; msgsize = MSG_LIST_INITIAL; } else { ret = false; } } if (!ret) { free(msglist); free(iov); std::bad_alloc ex; throw ex; } } /** * Convert a sockaddr_storage to a textual string (no name lookup). * * @param addr the sockaddr_storage received from getsockname or * getpeername * @param addr_len the current length used by the sockaddr_storage * @return a textual string representing the connection. or NULL * if an error occurs (caller takes ownership of the buffer and * must call free) */ static std::string sockaddr_to_string(const struct sockaddr_storage *addr, socklen_t addr_len) { char host[50]; char port[50]; int err = getnameinfo(reinterpret_cast<const struct sockaddr*>(addr), addr_len, host, sizeof(host), port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV); if (err != 0) { settings.extensions.logger->log(EXTENSION_LOG_WARNING, NULL, "getnameinfo failed with error %d", err); return NULL; } return std::string(host) + ":" + std::string(port); } void Connection::resolveConnectionName() { int err; struct sockaddr_storage peer; socklen_t peer_len = sizeof(peer); if ((err = getpeername(sfd, reinterpret_cast<struct sockaddr*>(&peer), &peer_len)) != 0) { settings.extensions.logger->log(EXTENSION_LOG_WARNING, NULL, "getpeername for socket %d with error %d", sfd, err); return; } struct sockaddr_storage sock; socklen_t sock_len = sizeof(sock); if ((err = getsockname(sfd, reinterpret_cast<struct sockaddr*>(&sock), &sock_len)) != 0) { settings.extensions.logger->log(EXTENSION_LOG_WARNING, NULL, "getsock for socket %d with error %d", sfd, err); return; } peername = sockaddr_to_string(&peer, peer_len); sockname = sockaddr_to_string(&sock, sock_len); } bool Connection::unregisterEvent() { cb_assert(registered_in_libevent); cb_assert(sfd != INVALID_SOCKET); if (event_del(&event) == -1) { log_system_error(EXTENSION_LOG_WARNING, NULL, "Failed to remove connection to libevent: %s"); return false; } registered_in_libevent = false; return true; } bool Connection::registerEvent() { cb_assert(!registered_in_libevent); cb_assert(sfd != INVALID_SOCKET); if (event_add(&event, NULL) == -1) { log_system_error(EXTENSION_LOG_WARNING, NULL, "Failed to add connection to libevent: %s"); return false; } registered_in_libevent = true; return true; } bool Connection::updateEvent(const int new_flags) { struct event_base *base = event.ev_base; if (ssl.isEnabled() && ssl.isConnected() && (new_flags & EV_READ)) { /* * If we want more data and we have SSL, that data might be inside * SSL's internal buffers rather than inside the socket buffer. In * that case signal an EV_READ event without actually polling the * socket. */ char dummy; /* SSL_pending() will not work here despite the name */ int rv = ssl.peek(&dummy, 1); if (rv > 0) { /* signal a call to the handler */ event_active(&event, EV_READ, 0); return true; } } if (ev_flags == new_flags) { // There is no change in the event flags! return true; } if (settings.verbose > 1) { settings.extensions.logger->log(EXTENSION_LOG_DEBUG, NULL, "Updated event for %d to read=%s, write=%s\n", sfd, (new_flags & EV_READ ? "yes" : "no"), (new_flags & EV_WRITE ? "yes" : "no")); } if (!unregisterEvent()) { settings.extensions.logger->log(EXTENSION_LOG_DEBUG, this, "Failed to remove connection from " "event notification library. Shutting " "down connection [%s - %s]", getPeername().c_str(), getSockname().c_str()); return false; } event_set(&event, sfd, new_flags, event_handler, reinterpret_cast<void*>(this)); event_base_set(base, &event); ev_flags = new_flags; if (!registerEvent()) { settings.extensions.logger->log(EXTENSION_LOG_DEBUG, this, "Failed to add connection to the " "event notification library. Shutting " "down connection [%s - %s]", getPeername().c_str(), getSockname().c_str()); return false; } return true; } bool Connection::initializeEvent(struct event_base *base) { int event_flags = (EV_READ | EV_PERSIST); event_set(&event, sfd, event_flags, event_handler, reinterpret_cast<void *>(this)); event_base_set(base, &event); ev_flags = event_flags; return registerEvent(); } SslContext::~SslContext() { if (enabled) { disable(); } } bool SslContext::enable(const std::string &cert, const std::string &pkey) { ctx = SSL_CTX_new(SSLv23_server_method()); /* MB-12359 - Disable SSLv2 & SSLv3 due to POODLE */ SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); /* @todo don't read files, but use in-memory-copies */ if (!SSL_CTX_use_certificate_chain_file(ctx, cert.c_str()) || !SSL_CTX_use_PrivateKey_file(ctx, pkey.c_str(), SSL_FILETYPE_PEM)) { return false; } set_ssl_ctx_cipher_list(ctx); enabled = true; error = false; client = NULL; try { in.buffer.resize(settings.bio_drain_buffer_sz); out.buffer.resize(settings.bio_drain_buffer_sz); } catch (std::bad_alloc) { return false; } BIO_new_bio_pair(&application, in.buffer.size(), &network, out.buffer.size()); client = SSL_new(ctx); SSL_set_bio(client, application, application); return true; } void SslContext::disable() { if (network != nullptr) { BIO_free_all(network); } if (client != nullptr) { SSL_free(client); } error = false; if (ctx != nullptr) { SSL_CTX_free(ctx); } enabled = false; } void SslContext::drainBioRecvPipe(SOCKET sfd) { int n; bool stop = false; do { if (in.current < in.total) { n = BIO_write(network, in.buffer.data() + in.current, in.total - in.current); if (n > 0) { in.current += n; if (in.current == in.total) { in.current = in.total = 0; } } else { /* Our input BIO is full, no need to grab more data from * the network at this time.. */ return ; } } if (in.total < in.buffer.size()) { n = recv(sfd, in.buffer.data() + in.total, in.buffer.size() - in.total, 0); if (n > 0) { in.total += n; } else { stop = true; if (n == 0) { error = true; /* read end shutdown */ } else { if (!is_blocking(GetLastNetworkError())) { error = true; } } } } } while (!stop); } void SslContext::drainBioSendPipe(SOCKET sfd) { int n; bool stop = false; do { if (out.current < out.total) { n = send(sfd, out.buffer.data() + out.current, out.total - out.current, 0); if (n > 0) { out.current += n; if (out.current == out.total) { out.current = out.total = 0; } } else { if (n == -1) { if (!is_blocking(GetLastNetworkError())) { error = true; } } return ; } } if (out.total == 0) { n = BIO_read(network, out.buffer.data(), out.buffer.size()); if (n > 0) { out.total = n; } else { stop = true; } } } while (!stop); } void SslContext::dumpCipherList(SOCKET sfd) { settings.extensions.logger->log(EXTENSION_LOG_DEBUG, NULL, "%d: Using SSL ciphers:", sfd); int ii = 0; const char *cipher; while ((cipher = SSL_get_cipher_list(client, ii++)) != NULL) { settings.extensions.logger->log(EXTENSION_LOG_DEBUG, NULL, "%d %s", sfd, cipher); } }<commit_msg>Put each initializer on a separate line<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, 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 "config.h" #include "memcached.h" #include "runtime.h" #include <exception> Connection::Connection() : all_next(nullptr), all_prev(nullptr), sfd(INVALID_SOCKET), max_reqs_per_event(settings.default_reqs_per_event), nevents(0), sasl_conn(nullptr), state(conn_immediate_close), substate(bin_no_state), protocol(Protocol::Memcached), admin(false), registered_in_libevent(false), ev_flags(0), currentEvent(0), write_and_go(nullptr), write_and_free(nullptr), ritem(nullptr), rlbytes(0), item(nullptr), iov(nullptr), iovsize(0), iovused(0), msglist(nullptr), msgsize(0), msgused(0), msgcurr(0), msgbytes(0), request_addr_size(0), hdrsize(0), noreply(false), nodelay(false), refcount(0), supports_datatype(false), supports_mutation_extras(false), engine_storage(nullptr), start(0), cas(0), cmd(PROTOCOL_BINARY_CMD_INVALID), opaque(0), keylen(0), list_state(0), next(nullptr), thread(nullptr), aiostat(ENGINE_SUCCESS), ewouldblock(false), tap_iterator(nullptr), parent_port(0), dcp(0), cmd_context(nullptr), auth_context(nullptr), peername("unknown"), sockname("unknown") { MEMCACHED_CONN_CREATE(this); memset(&event, 0, sizeof(event)); memset(&request_addr, 0, sizeof(request_addr)); memset(&read, 0, sizeof(read)); memset(&write, 0, sizeof(write)); memset(&dynamic_buffer, 0, sizeof(dynamic_buffer)); memset(&ssl, 0, sizeof(ssl)); memset(&bucket, 0, sizeof(bucket)); memset(&binary_header, 0, sizeof(binary_header)); state = conn_immediate_close; sfd = INVALID_SOCKET; resetBufferSize(); } Connection::~Connection() { MEMCACHED_CONN_DESTROY(this); auth_destroy(auth_context); cbsasl_dispose(&sasl_conn); free(read.buf); free(write.buf); free(iov); free(msglist); cb_assert(reservedItems.empty()); for (auto *ptr : temp_alloc) { free(ptr); } } void Connection::resetBufferSize() { bool ret = true; if (iovsize != IOV_LIST_INITIAL) { void* mem = malloc(sizeof(struct iovec) * IOV_LIST_INITIAL); auto* ptr = reinterpret_cast<struct iovec*>(mem); if (ptr != NULL) { free(iov); iov = ptr; iovsize = IOV_LIST_INITIAL; } else { ret = false; } } if (msgsize != MSG_LIST_INITIAL) { void* mem = malloc(sizeof(struct msghdr) * MSG_LIST_INITIAL); auto* ptr = reinterpret_cast<struct msghdr*>(mem); if (ptr != NULL) { free(msglist); msglist = ptr; msgsize = MSG_LIST_INITIAL; } else { ret = false; } } if (!ret) { free(msglist); free(iov); std::bad_alloc ex; throw ex; } } /** * Convert a sockaddr_storage to a textual string (no name lookup). * * @param addr the sockaddr_storage received from getsockname or * getpeername * @param addr_len the current length used by the sockaddr_storage * @return a textual string representing the connection. or NULL * if an error occurs (caller takes ownership of the buffer and * must call free) */ static std::string sockaddr_to_string(const struct sockaddr_storage *addr, socklen_t addr_len) { char host[50]; char port[50]; int err = getnameinfo(reinterpret_cast<const struct sockaddr*>(addr), addr_len, host, sizeof(host), port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV); if (err != 0) { settings.extensions.logger->log(EXTENSION_LOG_WARNING, NULL, "getnameinfo failed with error %d", err); return NULL; } return std::string(host) + ":" + std::string(port); } void Connection::resolveConnectionName() { int err; struct sockaddr_storage peer; socklen_t peer_len = sizeof(peer); if ((err = getpeername(sfd, reinterpret_cast<struct sockaddr*>(&peer), &peer_len)) != 0) { settings.extensions.logger->log(EXTENSION_LOG_WARNING, NULL, "getpeername for socket %d with error %d", sfd, err); return; } struct sockaddr_storage sock; socklen_t sock_len = sizeof(sock); if ((err = getsockname(sfd, reinterpret_cast<struct sockaddr*>(&sock), &sock_len)) != 0) { settings.extensions.logger->log(EXTENSION_LOG_WARNING, NULL, "getsock for socket %d with error %d", sfd, err); return; } peername = sockaddr_to_string(&peer, peer_len); sockname = sockaddr_to_string(&sock, sock_len); } bool Connection::unregisterEvent() { cb_assert(registered_in_libevent); cb_assert(sfd != INVALID_SOCKET); if (event_del(&event) == -1) { log_system_error(EXTENSION_LOG_WARNING, NULL, "Failed to remove connection to libevent: %s"); return false; } registered_in_libevent = false; return true; } bool Connection::registerEvent() { cb_assert(!registered_in_libevent); cb_assert(sfd != INVALID_SOCKET); if (event_add(&event, NULL) == -1) { log_system_error(EXTENSION_LOG_WARNING, NULL, "Failed to add connection to libevent: %s"); return false; } registered_in_libevent = true; return true; } bool Connection::updateEvent(const int new_flags) { struct event_base *base = event.ev_base; if (ssl.isEnabled() && ssl.isConnected() && (new_flags & EV_READ)) { /* * If we want more data and we have SSL, that data might be inside * SSL's internal buffers rather than inside the socket buffer. In * that case signal an EV_READ event without actually polling the * socket. */ char dummy; /* SSL_pending() will not work here despite the name */ int rv = ssl.peek(&dummy, 1); if (rv > 0) { /* signal a call to the handler */ event_active(&event, EV_READ, 0); return true; } } if (ev_flags == new_flags) { // There is no change in the event flags! return true; } if (settings.verbose > 1) { settings.extensions.logger->log(EXTENSION_LOG_DEBUG, NULL, "Updated event for %d to read=%s, write=%s\n", sfd, (new_flags & EV_READ ? "yes" : "no"), (new_flags & EV_WRITE ? "yes" : "no")); } if (!unregisterEvent()) { settings.extensions.logger->log(EXTENSION_LOG_DEBUG, this, "Failed to remove connection from " "event notification library. Shutting " "down connection [%s - %s]", getPeername().c_str(), getSockname().c_str()); return false; } event_set(&event, sfd, new_flags, event_handler, reinterpret_cast<void*>(this)); event_base_set(base, &event); ev_flags = new_flags; if (!registerEvent()) { settings.extensions.logger->log(EXTENSION_LOG_DEBUG, this, "Failed to add connection to the " "event notification library. Shutting " "down connection [%s - %s]", getPeername().c_str(), getSockname().c_str()); return false; } return true; } bool Connection::initializeEvent(struct event_base *base) { int event_flags = (EV_READ | EV_PERSIST); event_set(&event, sfd, event_flags, event_handler, reinterpret_cast<void *>(this)); event_base_set(base, &event); ev_flags = event_flags; return registerEvent(); } SslContext::~SslContext() { if (enabled) { disable(); } } bool SslContext::enable(const std::string &cert, const std::string &pkey) { ctx = SSL_CTX_new(SSLv23_server_method()); /* MB-12359 - Disable SSLv2 & SSLv3 due to POODLE */ SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); /* @todo don't read files, but use in-memory-copies */ if (!SSL_CTX_use_certificate_chain_file(ctx, cert.c_str()) || !SSL_CTX_use_PrivateKey_file(ctx, pkey.c_str(), SSL_FILETYPE_PEM)) { return false; } set_ssl_ctx_cipher_list(ctx); enabled = true; error = false; client = NULL; try { in.buffer.resize(settings.bio_drain_buffer_sz); out.buffer.resize(settings.bio_drain_buffer_sz); } catch (std::bad_alloc) { return false; } BIO_new_bio_pair(&application, in.buffer.size(), &network, out.buffer.size()); client = SSL_new(ctx); SSL_set_bio(client, application, application); return true; } void SslContext::disable() { if (network != nullptr) { BIO_free_all(network); } if (client != nullptr) { SSL_free(client); } error = false; if (ctx != nullptr) { SSL_CTX_free(ctx); } enabled = false; } void SslContext::drainBioRecvPipe(SOCKET sfd) { int n; bool stop = false; do { if (in.current < in.total) { n = BIO_write(network, in.buffer.data() + in.current, in.total - in.current); if (n > 0) { in.current += n; if (in.current == in.total) { in.current = in.total = 0; } } else { /* Our input BIO is full, no need to grab more data from * the network at this time.. */ return ; } } if (in.total < in.buffer.size()) { n = recv(sfd, in.buffer.data() + in.total, in.buffer.size() - in.total, 0); if (n > 0) { in.total += n; } else { stop = true; if (n == 0) { error = true; /* read end shutdown */ } else { if (!is_blocking(GetLastNetworkError())) { error = true; } } } } } while (!stop); } void SslContext::drainBioSendPipe(SOCKET sfd) { int n; bool stop = false; do { if (out.current < out.total) { n = send(sfd, out.buffer.data() + out.current, out.total - out.current, 0); if (n > 0) { out.current += n; if (out.current == out.total) { out.current = out.total = 0; } } else { if (n == -1) { if (!is_blocking(GetLastNetworkError())) { error = true; } } return ; } } if (out.total == 0) { n = BIO_read(network, out.buffer.data(), out.buffer.size()); if (n > 0) { out.total = n; } else { stop = true; } } } while (!stop); } void SslContext::dumpCipherList(SOCKET sfd) { settings.extensions.logger->log(EXTENSION_LOG_DEBUG, NULL, "%d: Using SSL ciphers:", sfd); int ii = 0; const char *cipher; while ((cipher = SSL_get_cipher_list(client, ii++)) != NULL) { settings.extensions.logger->log(EXTENSION_LOG_DEBUG, NULL, "%d %s", sfd, cipher); } }<|endoftext|>
<commit_before>//g++ genxmllicense.cpp -lcrypto++ -o genxmllicense #include <string> #include <vector> #include <fstream> #include <sstream> #include <stdexcept> using namespace std; #include <crypto++/rsa.h> #include <crypto++/osrng.h> #include <crypto++/base64.h> #include <crypto++/files.h> using namespace CryptoPP; string SignLicense(AutoSeededRandomPool &rng, string strContents) { //Read private key CryptoPP::ByteQueue bytes; FileSource file("secondary-privkey.txt", true, new Base64Decoder); file.TransferTo(bytes); bytes.MessageEnd(); RSA::PrivateKey privateKey; privateKey.Load(bytes); //Sign message RSASSA_PKCS1v15_SHA_Signer privkey(privateKey); SecByteBlock sbbSignature(privkey.SignatureLength()); privkey.SignMessage( rng, (byte const*) strContents.data(), strContents.size(), sbbSignature); //Save result string out; Base64Encoder enc(new StringSink(out)); enc.Put(sbbSignature, sbbSignature.size()); enc.MessageEnd(); return out; } string SerialiseKeyPairs(vector<vector<std::string> > &info) { string out; for(unsigned int pairNum = 0;pairNum < info.size();pairNum++) { out.append("<data k=\""); out.append(info[pairNum][0]); out.append("\" v=\""); out.append(info[pairNum][1]); out.append("\" />"); } return out; } string GetFileContent(string filename) { ifstream fi(filename.c_str()); if(!fi) { runtime_error("Could not open file"); } // get length of file: fi.seekg (0, fi.end); int length = fi.tellg(); fi.seekg (0, fi.beg); stringstream test; test << fi.rdbuf(); return test.str(); } int main() { vector<vector<std::string> > info; vector<string> pair; pair.push_back("licensee"); pair.push_back("John Doe, Big Institute, Belgium"); info.push_back(pair); pair.clear(); pair.push_back("functions"); pair.push_back("feature1, feature2"); info.push_back(pair); string serialisedInfo = SerialiseKeyPairs(info); AutoSeededRandomPool rng; string infoSig = SignLicense(rng, serialisedInfo); //Encode as xml string xml="<license>"; xml.append("<info>"); xml.append(serialisedInfo); xml.append("</info>"); xml.append("<infosig>"); xml.append(infoSig); xml.append("</infosig>"); xml.append("<key>"); xml.append(GetFileContent("secondary-pubkey.txt")); xml.append("</key>"); xml.append("<keysig>"); xml.append(GetFileContent("secondary-pubkey-sig.txt")); xml.append("</keysig>"); xml.append("</license>"); cout << xml << endl; } <commit_msg>Write result to file<commit_after>//g++ genxmllicense.cpp -lcrypto++ -o genxmllicense #include <string> #include <vector> #include <fstream> #include <sstream> #include <stdexcept> using namespace std; #include <crypto++/rsa.h> #include <crypto++/osrng.h> #include <crypto++/base64.h> #include <crypto++/files.h> using namespace CryptoPP; string SignLicense(AutoSeededRandomPool &rng, string strContents) { //Read private key CryptoPP::ByteQueue bytes; FileSource file("secondary-privkey.txt", true, new Base64Decoder); file.TransferTo(bytes); bytes.MessageEnd(); RSA::PrivateKey privateKey; privateKey.Load(bytes); //Sign message RSASSA_PKCS1v15_SHA_Signer privkey(privateKey); SecByteBlock sbbSignature(privkey.SignatureLength()); privkey.SignMessage( rng, (byte const*) strContents.data(), strContents.size(), sbbSignature); //Save result string out; Base64Encoder enc(new StringSink(out)); enc.Put(sbbSignature, sbbSignature.size()); enc.MessageEnd(); return out; } string SerialiseKeyPairs(vector<vector<std::string> > &info) { string out; for(unsigned int pairNum = 0;pairNum < info.size();pairNum++) { out.append("<data k=\""); out.append(info[pairNum][0]); out.append("\" v=\""); out.append(info[pairNum][1]); out.append("\" />"); } return out; } string GetFileContent(string filename) { ifstream fi(filename.c_str()); if(!fi) { runtime_error("Could not open file"); } // get length of file: fi.seekg (0, fi.end); int length = fi.tellg(); fi.seekg (0, fi.beg); stringstream test; test << fi.rdbuf(); return test.str(); } int main() { vector<vector<std::string> > info; vector<string> pair; pair.push_back("licensee"); pair.push_back("John Doe, Big Institute, Belgium"); info.push_back(pair); pair.clear(); pair.push_back("functions"); pair.push_back("feature1, feature2"); info.push_back(pair); string serialisedInfo = SerialiseKeyPairs(info); AutoSeededRandomPool rng; string infoSig = SignLicense(rng, serialisedInfo); //Encode as xml string xml="<license>"; xml.append("<info>"); xml.append(serialisedInfo); xml.append("</info>"); xml.append("<infosig>"); xml.append(infoSig); xml.append("</infosig>"); xml.append("<key>"); xml.append(GetFileContent("secondary-pubkey.txt")); xml.append("</key>"); xml.append("<keysig>"); xml.append(GetFileContent("secondary-pubkey-sig.txt")); xml.append("</keysig>"); xml.append("</license>"); //cout << xml << endl; ofstream out("xmllicense.xml"); out << xml; } <|endoftext|>
<commit_before>// NFA operates on bytes; it could only fail this if it tried to do signed // arithmetic on them, as UTF-8 continuations have most significant bit set. // NOTE: this file should be saved in UTF-8. // Those are perf. tests because `\p{x}` is horribly slow. GROUP_PERF_TEST_EX(5000, "(\\p{L}*)", ANCHOR_BOTH, "latin", 2); GROUP_PERF_TEST_EX(5000, "(\\p{L}*)", ANCHOR_BOTH, "кириллица", 2); GROUP_PERF_TEST_EX(5000, "(\\p{L}*)", ANCHOR_BOTH, "ελληνικά", 2); GROUP_PERF_TEST_EX(5000, "(\\p{L}*)", ANCHOR_BOTH, "繁體字", 2); GROUP_PERF_TEST_EX(5000, "(\\p{L}*)", ANCHOR_BOTH, "カタカナ", 2); GROUP_PERF_TEST_EX(9000, "(\\p{N}*)", ANCHOR_BOTH, "1234567890", 2); GROUP_PERF_TEST_EX(9000, "(\\p{N}*)", ANCHOR_BOTH, "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯ", 2); // These two don't match even though I copied these characters from a Wikipedia page // on numerals in Unicode. GROUP_PERF_TEST_EX(9000, "(\\p{N}*)", ANCHOR_BOTH, "ΠΔΗΧΜ", 2); GROUP_PERF_TEST_EX(9000, "(\\p{N}*)", ANCHOR_BOTH, ")𐅀𐅁𐅂𐅃𐅄𐅅𐅆𐅇𐅈𐅉𐅊𐅋𐅌𐅍𐅎𐅏", 2); <commit_msg>Add some Unicode tests for which the answer is "no".<commit_after>// NFA operates on bytes; it could only fail this if it tried to do signed // arithmetic on them, as UTF-8 continuations have most significant bit set. // NOTE: this file should be saved in UTF-8. // Those are perf. tests because `\p{x}` is horribly slow. GROUP_PERF_TEST_EX(5000, "(\\p{L}*)", ANCHOR_BOTH, "latin", 2); GROUP_PERF_TEST_EX(5000, "(\\p{L}*)", ANCHOR_BOTH, "кириллица", 2); GROUP_PERF_TEST_EX(5000, "(\\p{L}*)", ANCHOR_BOTH, "ελληνικά", 2); GROUP_PERF_TEST_EX(5000, "(\\p{L}*)", ANCHOR_BOTH, "繁體字", 2); GROUP_PERF_TEST_EX(5000, "(\\p{L}*)", ANCHOR_BOTH, "カタカナ", 2); GROUP_PERF_TEST_EX(5000, "(\\p{L}*)", ANCHOR_BOTH, "asdfg 1234567890 fail", 2); GROUP_PERF_TEST_EX(9000, "(\\p{N}*)", ANCHOR_BOTH, "1234567890", 2); GROUP_PERF_TEST_EX(9000, "(\\p{N}*)", ANCHOR_BOTH, "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯ", 2); // These two don't match even though I copied these characters from a Wikipedia page // on numerals in Unicode. GROUP_PERF_TEST_EX(9000, "(\\p{N}*)", ANCHOR_BOTH, "ΠΔΗΧΜ", 2); GROUP_PERF_TEST_EX(9000, "(\\p{N}*)", ANCHOR_BOTH, ")𐅀𐅁𐅂𐅃𐅄𐅅𐅆𐅇𐅈𐅉𐅊𐅋𐅌𐅍𐅎𐅏", 2); GROUP_PERF_TEST_EX(9000, "(\\p{N}*)", ANCHOR_BOTH, "12345 fail 67890", 2); <|endoftext|>
<commit_before>#include "ClientConnectToServerSystem.h" #include <boost/asio/ip/v6_only.hpp> #include <boost/asio/ip/address.hpp> #include "Control.h" #include <TcpClient.h> #include "InputBackendSystem.h" #include "LevelHandlerSystem.h" #include "GameState.h" #include "ClientStateSystem.h" #include <DebugUtil.h> ClientConnectToServerSystem::ClientConnectToServerSystem(TcpClient* p_tcpClient, bool p_connectDirectly/* =false */) : EntitySystem( SystemType::ClientConnectoToServerSystem ) { m_tcpClient = p_tcpClient; m_connectStraightAway = p_connectDirectly; m_isLookingForConnection = false; m_serverAddress = "127.0.0.1"; m_serverPort = "1337"; } ClientConnectToServerSystem::~ClientConnectToServerSystem() { } void ClientConnectToServerSystem::initialize() { if(m_connectStraightAway){ connectToNetworkAddress(); } } void ClientConnectToServerSystem::process() { if( m_tcpClient->hasActiveConnection() ) { m_isLookingForConnection = false; //m_world->getSystem(SystemType::ClientPacketHandlerSystem)->setEnabled(true); setEnabled(false); } } void ClientConnectToServerSystem::connectToNetworkAddress() { m_tcpClient->connectToServerAsync( m_serverAddress, m_serverPort); m_isLookingForConnection = true; } bool ClientConnectToServerSystem::setAddressAndConnect( const std::string& p_address, const std::string& p_port ) { if(setConnectionAddress(p_address,p_port)){ connectToNetworkAddress(); return true; } return false; } bool ClientConnectToServerSystem::setConnectionAddress( const std::string& p_address, const std::string& p_port ) { if(validateNetworkAddress(p_address, p_port)){ m_serverAddress = p_address; m_serverPort = p_port; return true; } return false; } bool ClientConnectToServerSystem::validateNetworkAddress( const std::string& p_address, const std::string& p_port ) { if(validateIPFormat(p_address) && validatePortFormat(p_port)){ return true; } return false; } bool ClientConnectToServerSystem::validateIPFormat(const std::string& p_address) { boost::asio::ip::address ipAddress; try{ ipAddress = boost::asio::ip::address::from_string(p_address); } catch(const std::exception& e){ DEBUGPRINT(("Invalid IP adress submited")); return false; } return true; } bool ClientConnectToServerSystem::validatePortFormat( const std::string& p_port ) { istringstream buffer(p_port); int portValue; buffer >> portValue; if(portValue < 1024 || portValue > 65535){ DEBUGPRINT(("Invalid Port range")); return false; } return true; } <commit_msg>Fixed so that port can now handle letters in the input.<commit_after>#include "ClientConnectToServerSystem.h" #include <boost/asio/ip/v6_only.hpp> #include <boost/asio/ip/address.hpp> #include "Control.h" #include <TcpClient.h> #include "InputBackendSystem.h" #include "LevelHandlerSystem.h" #include "GameState.h" #include "ClientStateSystem.h" #include <DebugUtil.h> ClientConnectToServerSystem::ClientConnectToServerSystem(TcpClient* p_tcpClient, bool p_connectDirectly/* =false */) : EntitySystem( SystemType::ClientConnectoToServerSystem ) { m_tcpClient = p_tcpClient; m_connectStraightAway = p_connectDirectly; m_isLookingForConnection = false; m_serverAddress = "127.0.0.1"; m_serverPort = "1337"; } ClientConnectToServerSystem::~ClientConnectToServerSystem() { } void ClientConnectToServerSystem::initialize() { if(m_connectStraightAway){ connectToNetworkAddress(); } } void ClientConnectToServerSystem::process() { if( m_tcpClient->hasActiveConnection() ) { m_isLookingForConnection = false; //m_world->getSystem(SystemType::ClientPacketHandlerSystem)->setEnabled(true); setEnabled(false); } } void ClientConnectToServerSystem::connectToNetworkAddress() { m_tcpClient->connectToServerAsync( m_serverAddress, m_serverPort); m_isLookingForConnection = true; } bool ClientConnectToServerSystem::setAddressAndConnect( const std::string& p_address, const std::string& p_port ) { if(setConnectionAddress(p_address,p_port)){ connectToNetworkAddress(); return true; } return false; } bool ClientConnectToServerSystem::setConnectionAddress( const std::string& p_address, const std::string& p_port ) { if(validateNetworkAddress(p_address, p_port)){ m_serverAddress = p_address; m_serverPort = p_port; return true; } return false; } bool ClientConnectToServerSystem::validateNetworkAddress( const std::string& p_address, const std::string& p_port ) { if(validateIPFormat(p_address) && validatePortFormat(p_port)){ return true; } return false; } bool ClientConnectToServerSystem::validateIPFormat(const std::string& p_address) { boost::asio::ip::address ipAddress; try{ ipAddress = boost::asio::ip::address::from_string(p_address); } catch(const std::exception& e){ DEBUGPRINT(("Invalid IP address submitted\n")); return false; } return true; } bool ClientConnectToServerSystem::validatePortFormat( const std::string& p_port ) { istringstream buffer(p_port); int portValue; try{ buffer >> portValue; } catch(exception& e){ DEBUGPRINT(("Invalid Port address submitted\n")); return false; } if(portValue < 1024 || portValue > 65535){ DEBUGPRINT(("Invalid Port range\n")); return false; } return true; } <|endoftext|>
<commit_before>/** * Copyright (c) 2016-2018 mvs developers * * This file is part of metaverse-explorer. * * metaverse-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/explorer/define.hpp> #include <metaverse/explorer/extensions/command_extension.hpp> #include <metaverse/explorer/extensions/command_extension_func.hpp> #include <metaverse/explorer/extensions/command_assistant.hpp> namespace libbitcoin { namespace explorer { namespace commands { /************************ transfercert *************************/ class transfercert : public command_extension { public: static const char* symbol(){ return "transfercert";} const char* name() override { return symbol();} bool category(int bs) override { return (ex_online & bs ) == bs; } const char* description() override { return "transfercert"; } arguments_metadata& load_arguments() override { return get_argument_metadata() .add("ACCOUNTNAME", 1) .add("ACCOUNTAUTH", 1) .add("TODID", 1) .add("SYMBOL", 1); } void load_fallbacks (std::istream& input, po::variables_map& variables) override { const auto raw = requires_raw_input(); load_input(auth_.name, "ACCOUNTNAME", variables, input, raw); load_input(auth_.auth, "ACCOUNTAUTH", variables, input, raw); load_input(argument_.to, "TODID", variables, input, raw); load_input(argument_.symbol, "SYMBOL", variables, input, raw); } options_metadata& load_options() override { using namespace po; options_description& options = get_option_metadata(); options.add_options() ( BX_HELP_VARIABLE ",h", value<bool>()->zero_tokens(), "Get a description and instructions for this command." ) ( "ACCOUNTNAME", value<std::string>(&auth_.name)->required(), BX_ACCOUNT_NAME ) ( "ACCOUNTAUTH", value<std::string>(&auth_.auth)->required(), BX_ACCOUNT_AUTH ) ( "TODID", value<std::string>(&argument_.to)->required(), "Target did" ) ( "SYMBOL", value<std::string>(&argument_.symbol)->required(), "Asset symbol" ) ( "cert,c", value<std::vector<std::string>>(&argument_.certs)->multitoken()->required(), "Asset cert type name, eg. ISSUE, DOMAIN, NAMING" ) ( "fee,f", value<uint64_t>(&argument_.fee)->default_value(10000), "Transaction fee. defaults to 10000 ETP bits" ); return options; } void set_defaults_from_config (po::variables_map& variables) override { } console_result invoke (Json::Value& jv_output, libbitcoin::server::server_node& node) override; struct argument { std::string to; std::string symbol; std::vector<std::string> certs; uint64_t fee; } argument_; struct option { } option_; }; } // namespace commands } // namespace explorer } // namespace libbitcoin <commit_msg>update help<commit_after>/** * Copyright (c) 2016-2018 mvs developers * * This file is part of metaverse-explorer. * * metaverse-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/explorer/define.hpp> #include <metaverse/explorer/extensions/command_extension.hpp> #include <metaverse/explorer/extensions/command_extension_func.hpp> #include <metaverse/explorer/extensions/command_assistant.hpp> namespace libbitcoin { namespace explorer { namespace commands { /************************ transfercert *************************/ class transfercert : public command_extension { public: static const char* symbol(){ return "transfercert";} const char* name() override { return symbol();} bool category(int bs) override { return (ex_online & bs ) == bs; } const char* description() override { return "transfercert"; } arguments_metadata& load_arguments() override { return get_argument_metadata() .add("ACCOUNTNAME", 1) .add("ACCOUNTAUTH", 1) .add("TODID", 1) .add("SYMBOL", 1); } void load_fallbacks (std::istream& input, po::variables_map& variables) override { const auto raw = requires_raw_input(); load_input(auth_.name, "ACCOUNTNAME", variables, input, raw); load_input(auth_.auth, "ACCOUNTAUTH", variables, input, raw); load_input(argument_.to, "TODID", variables, input, raw); load_input(argument_.symbol, "SYMBOL", variables, input, raw); } options_metadata& load_options() override { using namespace po; options_description& options = get_option_metadata(); options.add_options() ( BX_HELP_VARIABLE ",h", value<bool>()->zero_tokens(), "Get a description and instructions for this command." ) ( "ACCOUNTNAME", value<std::string>(&auth_.name)->required(), BX_ACCOUNT_NAME ) ( "ACCOUNTAUTH", value<std::string>(&auth_.auth)->required(), BX_ACCOUNT_AUTH ) ( "TODID", value<std::string>(&argument_.to)->required(), "Target did" ) ( "SYMBOL", value<std::string>(&argument_.symbol)->required(), "Asset cert symbol" ) ( "cert,c", value<std::vector<std::string>>(&argument_.certs)->multitoken()->required(), "Asset cert type name(s), multi names should be separeted by white-space, eg. ISSUE DOMAIN NAMING" ) ( "fee,f", value<uint64_t>(&argument_.fee)->default_value(10000), "Transaction fee. defaults to 10000 ETP bits" ); return options; } void set_defaults_from_config (po::variables_map& variables) override { } console_result invoke (Json::Value& jv_output, libbitcoin::server::server_node& node) override; struct argument { std::string to; std::string symbol; std::vector<std::string> certs; uint64_t fee; } argument_; struct option { } option_; }; } // namespace commands } // namespace explorer } // namespace libbitcoin <|endoftext|>
<commit_before><commit_msg>remove ability to use break() a block outside any loop<commit_after><|endoftext|>
<commit_before>/** * @file ParameterList.cpp * * @author <a href="mailto:[email protected]">Alexander Schulz</a> * @author <a href="mailto:[email protected]">Thomas Krause</a> * */ #include <string> #include <PlatformInterface/Platform.h> #include "Core/Cognition/CognitionDebugServer.h" #include <Tools/Debug/NaoTHAssert.h> #include "ParameterList.h" ParameterList::ParameterList(const std::string& parentClassName) { this->parentClassName = parentClassName; REGISTER_DEBUG_COMMAND(std::string(parentClassName).append(":set"), std::string("set the parameters for ").append(parentClassName), this); REGISTER_DEBUG_COMMAND(std::string(parentClassName).append(":list"), "get the list of available parameters", this); REGISTER_DEBUG_COMMAND(std::string(parentClassName).append(":store"), "store the configure file according to the path", this); }//end constructor ParameterList unsigned int& ParameterList::registerParameter(const std::string& name, unsigned int& parameter) { ASSERT(unsignedIntParameterReferences.find(name) == unsignedIntParameterReferences.end()); unsignedIntParameterReferences[name] = &parameter; return parameter; }//end registerParameter int& ParameterList::registerParameter(const std::string& name, int& parameter) { ASSERT(intParameterReferences.find(name) == intParameterReferences.end()); intParameterReferences[name] = &parameter; return parameter; }//end registerParameter double& ParameterList::registerParameter(const std::string& name, double& parameter) { ASSERT(doubleParameterReferences.find(name) == doubleParameterReferences.end()); doubleParameterReferences[name] = &parameter; return parameter; }//end registerParameter std::string& ParameterList::registerParameter(const std::string& name, std::string& parameter) { ASSERT(stringParameterReferences.find(name) == stringParameterReferences.end()); stringParameterReferences[name] = &parameter; return parameter; }//end registerParameter bool& ParameterList::registerParameter(const std::string& name, bool& parameter) { ASSERT(boolParameterReferences.find(name) == boolParameterReferences.end()); boolParameterReferences[name] = &parameter; return parameter; } void ParameterList::loadFromConfig() { naoth::Configuration& config = naoth::Platform::getInstance().theConfiguration; // unsigned int for (std::map<std::string, unsigned int*>::const_iterator iter = unsignedIntParameterReferences.begin(); iter != unsignedIntParameterReferences.end(); iter++) { if (config.hasKey(parentClassName, iter->first)) { *(iter->second) = config.getInt(parentClassName, iter->first); } }//end for // int for (std::map<std::string, int*>::const_iterator iter = intParameterReferences.begin(); iter != intParameterReferences.end(); iter++) { if (config.hasKey(parentClassName, iter->first)) { *(iter->second) = config.getInt(parentClassName, iter->first); } }//end for // double for (std::map<std::string, double*>::const_iterator iter = doubleParameterReferences.begin(); iter != doubleParameterReferences.end(); iter++) { if (config.hasKey(parentClassName, iter->first)) { *(iter->second) = config.getDouble(parentClassName, iter->first); } }//end for // string for (std::map<std::string, std::string*>::const_iterator iter = stringParameterReferences.begin(); iter != stringParameterReferences.end(); iter++) { if (config.hasKey(parentClassName, iter->first)) { *(iter->second) = config.getString(parentClassName, iter->first); } }//end for // bool for (std::map<std::string, bool*>::const_iterator iter = boolParameterReferences.begin(); iter != boolParameterReferences.end(); iter++) { if (config.hasKey(parentClassName, iter->first)) { *(iter->second) = config.getBool(parentClassName, iter->first); } }//end for } void ParameterList::saveToConfig() { } void ParameterList::executeDebugCommand( const std::string& command, const std::map<std::string, std::string>& arguments, std::stringstream &outstream) { if (command == std::string(parentClassName).append(":set")) { std::stringstream ss; for (std::map<std::string, std::string>::const_iterator iter = arguments.begin(); iter != arguments.end(); iter++) { ss << iter->first << " = " << iter->second << ";\n"; } // TODO } else if (command == std::string(parentClassName).append(":list")) { // TODO } else if (command == std::string(parentClassName).append(":store")) { // TODO } }//end executeDebugCommand <commit_msg>- setter functions for ParameterList<commit_after>/** * @file ParameterList.cpp * * @author <a href="mailto:[email protected]">Alexander Schulz</a> * @author <a href="mailto:[email protected]">Thomas Krause</a> * */ #include <string> #include <PlatformInterface/Platform.h> #include "Core/Cognition/CognitionDebugServer.h" #include <Tools/Debug/NaoTHAssert.h> #include "ParameterList.h" ParameterList::ParameterList(const std::string& parentClassName) { this->parentClassName = parentClassName; REGISTER_DEBUG_COMMAND(std::string(parentClassName).append(":set"), std::string("set the parameters for ").append(parentClassName), this); REGISTER_DEBUG_COMMAND(std::string(parentClassName).append(":list"), "get the list of available parameters", this); REGISTER_DEBUG_COMMAND(std::string(parentClassName).append(":store"), "store the configure file according to the path", this); }//end constructor ParameterList unsigned int& ParameterList::registerParameter(const std::string& name, unsigned int& parameter) { ASSERT(unsignedIntParameterReferences.find(name) == unsignedIntParameterReferences.end()); unsignedIntParameterReferences[name] = &parameter; return parameter; }//end registerParameter int& ParameterList::registerParameter(const std::string& name, int& parameter) { ASSERT(intParameterReferences.find(name) == intParameterReferences.end()); intParameterReferences[name] = &parameter; return parameter; }//end registerParameter double& ParameterList::registerParameter(const std::string& name, double& parameter) { ASSERT(doubleParameterReferences.find(name) == doubleParameterReferences.end()); doubleParameterReferences[name] = &parameter; return parameter; }//end registerParameter std::string& ParameterList::registerParameter(const std::string& name, std::string& parameter) { ASSERT(stringParameterReferences.find(name) == stringParameterReferences.end()); stringParameterReferences[name] = &parameter; return parameter; }//end registerParameter bool& ParameterList::registerParameter(const std::string& name, bool& parameter) { ASSERT(boolParameterReferences.find(name) == boolParameterReferences.end()); boolParameterReferences[name] = &parameter; return parameter; } void ParameterList::loadFromConfig() { naoth::Configuration& config = naoth::Platform::getInstance().theConfiguration; // unsigned int for (std::map<std::string, unsigned int*>::const_iterator iter = unsignedIntParameterReferences.begin(); iter != unsignedIntParameterReferences.end(); iter++) { if (config.hasKey(parentClassName, iter->first)) { *(iter->second) = config.getInt(parentClassName, iter->first); } }//end for // int for (std::map<std::string, int*>::const_iterator iter = intParameterReferences.begin(); iter != intParameterReferences.end(); iter++) { if (config.hasKey(parentClassName, iter->first)) { *(iter->second) = config.getInt(parentClassName, iter->first); } }//end for // double for (std::map<std::string, double*>::const_iterator iter = doubleParameterReferences.begin(); iter != doubleParameterReferences.end(); iter++) { if (config.hasKey(parentClassName, iter->first)) { *(iter->second) = config.getDouble(parentClassName, iter->first); } }//end for // string for (std::map<std::string, std::string*>::const_iterator iter = stringParameterReferences.begin(); iter != stringParameterReferences.end(); iter++) { if (config.hasKey(parentClassName, iter->first)) { *(iter->second) = config.getString(parentClassName, iter->first); } }//end for // bool for (std::map<std::string, bool*>::const_iterator iter = boolParameterReferences.begin(); iter != boolParameterReferences.end(); iter++) { if (config.hasKey(parentClassName, iter->first)) { *(iter->second) = config.getBool(parentClassName, iter->first); } }//end for } void ParameterList::saveToConfig() { naoth::Configuration& config = naoth::Platform::getInstance().theConfiguration; for(std::map<std::string, unsigned int*>::iterator iter = unsignedIntParameterReferences.begin(); iter != unsignedIntParameterReferences.end(); iter++) { config.setInt(parentClassName, iter->first, *(iter->second)); }//end for for(std::map<std::string, int*>::iterator iter = intParameterReferences.begin(); iter != intParameterReferences.end(); iter++) { config.setInt(parentClassName, iter->first, *(iter->second)); }//end for for(std::map<std::string, double*>::iterator iter = doubleParameterReferences.begin(); iter != doubleParameterReferences.end(); iter++) { config.setDouble(parentClassName, iter->first, *(iter->second)); }//end for for(std::map<std::string, std::string*>::iterator iter = stringParameterReferences.begin(); iter != stringParameterReferences.end(); iter++) { config.setString(parentClassName, iter->first, *(iter->second)); }//end for for(std::map<std::string, bool*>::iterator iter = boolParameterReferences.begin(); iter != boolParameterReferences.end(); iter++) { config.setBool(parentClassName, iter->first, *(iter->second)); }//end for } void ParameterList::executeDebugCommand( const std::string& command, const std::map<std::string, std::string>& arguments, std::stringstream &outstream) { if (command == std::string(parentClassName).append(":set")) { std::stringstream ss; for (std::map<std::string, std::string>::const_iterator iter = arguments.begin(); iter != arguments.end(); iter++) { ss << iter->first << " = " << iter->second << ";\n"; } // TODO } else if (command == std::string(parentClassName).append(":list")) { // TODO } else if (command == std::string(parentClassName).append(":store")) { // TODO } }//end executeDebugCommand <|endoftext|>
<commit_before>#include "gui.h" /** * @brief MainWindow::MainWindow : ventana principal para logearse, registrarse y ver competencias * * @param guiP : objeto gui que hace de mediador y sirve para pasar el control * una vez que se quiera ir a otra ventana * * @param parent : objeto tipo ventana padre que sirve como retorno, asi lo * implementa Qt */ MainWindow::MainWindow(GUI* guiP, QWidget *parent): QMainWindow(parent), gui(guiP), ui(new Ui::MainWindow) { ui->setupUi(this); QPixmap pix(":/images/Heros128.png"); ui->label_logo->setPixmap(pix); this->setWindowTitle("Sistema deportivo Pegaso"); // validador del email EmailValidator* emailValidator = new EmailValidator(this); ui->lineEdit->setValidator(emailValidator); // validador de la contraseña QRegExp password("[a-zA-Z0-9.-]*"); QValidator* passwordValidator = new QRegExpValidator(password,this); ui->lineEdit_2->setValidator(passwordValidator); // contraseña seteada para que no se vea al escribir ui->lineEdit_2->setEchoMode(QLineEdit::Password); ui->pushButton_3->hide(); ui->pushButton->hide(); // this->setGeometry(0,0,350,100); } /** * @brief GUI::GUI : Mediador que controla interacion de interfaz grafica * y gestores de la capa logica. * * @param gestorDBP * @param gestorCompetenciasP * @param gestorLugaresP * @param gestorPartidosP * @param gestorUsuariosP * @param deportesP * @param paisesP * @param estadosP * @param modalidadesP * */ GUI::GUI(GestorBaseDatos *gestorDBP, GestorCompetencias *gestorCompetenciasP, GestorLugares *gestorLugaresP, GestorPartidos *gestorPartidosP, GestorUsuarios *gestorUsuariosP, QVector<Deporte *> deportesP, QVector<Pais *> paisesP, QVector<Estado *> estadosP, QVector<TipoModalidad *> modalidadesP): gestorDB(gestorDBP), gestorCompetencias(gestorCompetenciasP), gestorLugares(gestorLugaresP), gestorPartidos(gestorPartidosP), gestorUsuarios(gestorUsuariosP), deportes(deportesP), paises(paisesP), estados(estadosP), modalidades(modalidadesP) {} MainWindow::~MainWindow() { delete ui; } /** * @brief MainWindow::on_pushButton_2_clicked * @details boton de login extrae toda la informacion de la ui, la verifica * y la envia al gestor correspondiente para luego efectuar el cambio de ventana o no */ void MainWindow::on_pushButton_2_clicked() { // La contraseña no puede ser menor a 6 caracteres // si no se cumple directamente no se verifica // no se avisa nada al respecto if(ui->lineEdit_2->text().size() > 0 && ui->lineEdit->text().size() > 0 && ui->lineEdit->hasAcceptableInput() ){ // se encripta la contraseña a penas se pide por seguridad QByteArray passwordHash = QCryptographicHash::hash(QByteArray::fromStdString(ui->lineEdit_2->text().toStdString()),QCryptographicHash::Sha256); // obtenemos el mail de la ui QString email = ui->lineEdit->text(); gui->handleMain(this,QString("pantallaUsuario"),email,passwordHash); } else{ QMessageBox* msg = new QMessageBox(this); msg->setText("Complete correctamente los campos por favor"); QPixmap icono(":/images/Heros-amarillo-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); } } /** * @brief MainWindow::on_pushButton_4_clicked * @details boton de cierre de la ventana principal */ void MainWindow::on_pushButton_4_clicked() { this->close(); } /** * @brief GUI::handleMain: * Handle para manejar los posibles eventos de la ventana principal * @param a : ventana padre a la posible ventana a instaciar * @param b : opcion para el handle * @param email : email para pedir el usuario * @param pass : contraseña encriptada para loggear usuario */ void GUI::handleMain(QMainWindow* a, QString b, QString email, QByteArray pass) { if (b == "pantallaUsuario") { if(gestorUsuarios->login(email,pass) != NULL){ pantalla_usuario* p = new pantalla_usuario(this,a); a->close(); p->show(); } else{ // mensaje de error QMessageBox* msg = new QMessageBox(a); msg->setText("Nombre o contraseña incorrecta"); QPixmap icono(":/images/Heros-rojo-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); } } else if (b == "registrarUsuario") { registrar_usuario * ru = new registrar_usuario(this,paises,a); ru->setModal(true); ru->show(); } } void GUI::handlePantallaUsuario(QDialog *a, QString b) { if (b == "listarCompetencias"){ listar_competencias* l = new listar_competencias(this,deportes,estados,modalidades,a); a->close(); l->show(); } } void GUI::handleListarCompetencias(QDialog *a, QString b, Competencia *comp) { if (b == "altaCompetencia") { Usuario* user = gestorUsuarios->getActual(); QVector<Lugar*> lugares = gestorLugares->getLugares(); QVector<TipoResultado*> resultados = gestorCompetencias->getTiposResultado(); alta_competencia * al = new alta_competencia(this,deportes,lugares,modalidades, resultados, a); al->setModal(true); al->show(); } else if (b == "verCompetencia") { Competencia * c = gestorCompetencias->getCompetenciaFull(comp->getId()); ver_competencia * v = new ver_competencia(this,c,a); v->setModal(true); v->show(); } } void GUI::handleAltaCompetencia(QDialog *a, QString b, QString nombreComp, Deporte* dep, QVector<Lugar *> lugs, QVector<int> disps, Modalidad* mod, QString reglamento) { if (b == "crearCompetencia") { bool op; QString error; Usuario* user = gestorUsuarios->getActual(); DtoCompetencia* dtoC = new DtoCompetencia(user,nombreComp,dep,lugs,disps,mod,reglamento); if(gestorCompetencias->crearCompetencia(dtoC,op,error) != NULL){ QMessageBox* msg = new QMessageBox(a); msg->setText("Competencia creada correctamente"); QPixmap icono(":/images/Heros-verde-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); } else{ // QMessageBox fracaso QMessageBox* msg = new QMessageBox(a); QString error1 = "Error al crear la competencia. \n" + error; msg->setText(error1); QPixmap icono(":/images/Heros-rojo-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); } a->close(); } } bool GUI::handleVerCompetencia(QDialog *a, QString b, QString error, Competencia* comp) { competenciaActual = comp; if (b == "modificarCompetencia") { /* code */ } else if (b == "generarFixture") { return gestorCompetencias->generarFixture(comp,error); competenciaActual = comp; } else if (b == "bajaCompetencia") { /* code */ } else if (b == "mostrarFixture") { comp = gestorCompetencias->getCompetenciaFull(comp->getId()); mostrar_fixture* mf = new mostrar_fixture(this,comp,a); mf->setModal(true); mf->show(); } else if (b == "mostrarTablasPosiciones") { tabla_posiciones* t = new tabla_posiciones(this,comp,a); t->setModal(true); t->show(); } else if (b == "listarParticipantes"){ participantes = comp->getParticipantes(); listar_participante * lp = new listar_participante(this,comp, a); lp->setModal(true); lp->show(); } return false; } void GUI::handleMostrarFixture(QDialog *a, QString b,Partido* partido) { if (b == "gestionarFixture") { gestionar_fixture* gf = new gestionar_fixture(competenciaActual,partido,this,a); gf->setModal(true); gf->show(); } } void GUI::handleGestionarFixture(QDialog *a, QString b, Partido *partP, Resultado *resP) { gestorCompetencias->nuevoResultado(competenciaActual,partP,resP); competenciaActual = gestorCompetencias->getCompetenciaFull(competenciaActual->getId()); QMessageBox* msg = new QMessageBox(a); msg->setText("Partido cargado correctamente"); QPixmap icono(":/images/Heros-verde-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); a->close(); } QVector<Competencia*> GUI::handleFiltrarCompetencias(QStringList data) { QString nombreComp, deporte, estado, tipoModalidad; Usuario* usuario = gestorUsuarios->getActual(); nombreComp = data[0]; deporte = data[1]; estado = data[2]; tipoModalidad = data[3]; Estado* e = this->buscarEstado(estado); Deporte* d = this->buscarDeporte(deporte); TipoModalidad* tm = this->buscarTipoModalidad(tipoModalidad); DtoGetCompetencia* datos = new DtoGetCompetencia(usuario,nombreComp,d,tm,e); return gestorCompetencias->getCompetenciasLazy(datos); } QString GUI::handleRegistrarUsuario(DtoUsuario *datos) { QString error; gestorUsuarios->altaUsuario(datos,error); return error; } QVector<Deporte *> GUI::getDeportes() const { return deportes; } void GUI::setDeportes(const QVector<Deporte *> &value) { deportes = value; } QVector<Provincia *> GUI::getProvincias(Pais *paisP) { return gestorUsuarios->getProvincias(paisP); } QVector<Localidad *> GUI::getLocalidades(Provincia *provinciaP) { return gestorUsuarios->getLocalidades(provinciaP); } QVector<Participante*> GUI::handleAltaParticipante(QDialog *a, QString nombre, QString email, QString ImgUrl) { DtoParticipante* datos = new DtoParticipante(nombre,email,ImgUrl); QString error; if(gestorCompetencias->altaParticipante(competenciaActual,datos,error)){ QMessageBox* msg = new QMessageBox(a); msg->setText(error); QPixmap icono(":/images/Heros-verde-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); return competenciaActual->getParticipantes(); } else{ QMessageBox* msg = new QMessageBox(a); msg->setText(error); QPixmap icono(":/images/Heros-rojo-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); QVector<Participante*> aux; return aux; } } Estado *GUI::buscarEstado(QString estado) { for (int i = 0; i < estados.size(); ++i) { if(estado.toLower() == estados[i]->getNombre().toLower()) return estados[i]; } return NULL; } Deporte *GUI::buscarDeporte(QString deporte) { for (int i = 0; i < deportes.size(); ++i) { if(deporte.toLower()==deportes[i]->getNombre().toLower()) return deportes[i]; } return NULL; } TipoModalidad *GUI::buscarTipoModalidad(QString tipoMod) { for (int i = 0; i < modalidades.size(); ++i) { if(tipoMod.toLower() == modalidades[i]->getNombre().toLower()) return modalidades[i]; } return NULL; } void GUI::show() { MainWindow * m = new MainWindow(this); m->show(); } void MainWindow::on_pushButton_clicked() { gui->handleMain(this,QString("registrarUsuario")); } EmailValidator::EmailValidator(QObject *parent) : QValidator(parent), m_validMailRegExp("[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}"), m_intermediateMailRegExp("[a-z0-9._%+-]*@?[a-z0-9.-]*\\.?[a-z]*"){} QValidator::State EmailValidator::validate(QString &text, int &pos) const { Q_UNUSED(pos) fixup(text); if (m_validMailRegExp.exactMatch(text)) return Acceptable; if (m_intermediateMailRegExp.exactMatch(text)) return Intermediate; return Invalid; } void EmailValidator::fixup(QString &text) const { text = text.trimmed().toLower(); } <commit_msg>Revertido cerrar en gui, listarCompetencias y pantallaUsuario no cerraban al presionar salir<commit_after>#include "gui.h" /** * @brief MainWindow::MainWindow : ventana principal para logearse, registrarse y ver competencias * * @param guiP : objeto gui que hace de mediador y sirve para pasar el control * una vez que se quiera ir a otra ventana * * @param parent : objeto tipo ventana padre que sirve como retorno, asi lo * implementa Qt */ MainWindow::MainWindow(GUI* guiP, QWidget *parent): QMainWindow(parent), gui(guiP), ui(new Ui::MainWindow) { ui->setupUi(this); QPixmap pix(":/images/Heros128.png"); ui->label_logo->setPixmap(pix); this->setWindowTitle("Sistema deportivo Pegaso"); // validador del email EmailValidator* emailValidator = new EmailValidator(this); ui->lineEdit->setValidator(emailValidator); // validador de la contraseña QRegExp password("[a-zA-Z0-9.-]*"); QValidator* passwordValidator = new QRegExpValidator(password,this); ui->lineEdit_2->setValidator(passwordValidator); // contraseña seteada para que no se vea al escribir ui->lineEdit_2->setEchoMode(QLineEdit::Password); ui->pushButton_3->hide(); ui->pushButton->hide(); // this->setGeometry(0,0,350,100); } /** * @brief GUI::GUI : Mediador que controla interacion de interfaz grafica * y gestores de la capa logica. * * @param gestorDBP * @param gestorCompetenciasP * @param gestorLugaresP * @param gestorPartidosP * @param gestorUsuariosP * @param deportesP * @param paisesP * @param estadosP * @param modalidadesP * */ GUI::GUI(GestorBaseDatos *gestorDBP, GestorCompetencias *gestorCompetenciasP, GestorLugares *gestorLugaresP, GestorPartidos *gestorPartidosP, GestorUsuarios *gestorUsuariosP, QVector<Deporte *> deportesP, QVector<Pais *> paisesP, QVector<Estado *> estadosP, QVector<TipoModalidad *> modalidadesP): gestorDB(gestorDBP), gestorCompetencias(gestorCompetenciasP), gestorLugares(gestorLugaresP), gestorPartidos(gestorPartidosP), gestorUsuarios(gestorUsuariosP), deportes(deportesP), paises(paisesP), estados(estadosP), modalidades(modalidadesP) {} MainWindow::~MainWindow() { delete ui; } /** * @brief MainWindow::on_pushButton_2_clicked * @details boton de login extrae toda la informacion de la ui, la verifica * y la envia al gestor correspondiente para luego efectuar el cambio de ventana o no */ void MainWindow::on_pushButton_2_clicked() { // La contraseña no puede ser menor a 6 caracteres // si no se cumple directamente no se verifica // no se avisa nada al respecto if(ui->lineEdit_2->text().size() > 0 && ui->lineEdit->text().size() > 0 && ui->lineEdit->hasAcceptableInput() ){ // se encripta la contraseña a penas se pide por seguridad QByteArray passwordHash = QCryptographicHash::hash(QByteArray::fromStdString(ui->lineEdit_2->text().toStdString()),QCryptographicHash::Sha256); // obtenemos el mail de la ui QString email = ui->lineEdit->text(); gui->handleMain(this,QString("pantallaUsuario"),email,passwordHash); } else{ QMessageBox* msg = new QMessageBox(this); msg->setText("Complete correctamente los campos por favor"); QPixmap icono(":/images/Heros-amarillo-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); } } /** * @brief MainWindow::on_pushButton_4_clicked * @details boton de cierre de la ventana principal */ void MainWindow::on_pushButton_4_clicked() { this->close(); } /** * @brief GUI::handleMain: * Handle para manejar los posibles eventos de la ventana principal * @param a : ventana padre a la posible ventana a instaciar * @param b : opcion para el handle * @param email : email para pedir el usuario * @param pass : contraseña encriptada para loggear usuario */ void GUI::handleMain(QMainWindow* a, QString b, QString email, QByteArray pass) { if (b == "pantallaUsuario") { if(gestorUsuarios->login(email,pass) != NULL){ pantalla_usuario* p = new pantalla_usuario(this,a); a->close(); p->show(); } else{ // mensaje de error QMessageBox* msg = new QMessageBox(a); msg->setText("Nombre o contraseña incorrecta"); QPixmap icono(":/images/Heros-rojo-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); } } else if (b == "registrarUsuario") { registrar_usuario * ru = new registrar_usuario(this,paises,a); ru->setModal(true); ru->show(); } } void GUI::handlePantallaUsuario(QDialog *a, QString b) { if (b == "listarCompetencias"){ listar_competencias* l = new listar_competencias(this,deportes,estados,modalidades,a); a->close(); l->show(); } else if(b == "cerrar") { MainWindow * m = new MainWindow(this); m->show(); a->close(); } } void GUI::handleListarCompetencias(QDialog *a, QString b, Competencia *comp) { if (b == "altaCompetencia") { Usuario* user = gestorUsuarios->getActual(); QVector<Lugar*> lugares = gestorLugares->getLugares(); QVector<TipoResultado*> resultados = gestorCompetencias->getTiposResultado(); alta_competencia * al = new alta_competencia(this,deportes,lugares,modalidades, resultados, a); al->setModal(true); al->show(); } else if (b == "verCompetencia") { Competencia * c = gestorCompetencias->getCompetenciaFull(comp->getId()); ver_competencia * v = new ver_competencia(this,c,a); v->setModal(true); v->show(); } else if(b == "cerrar") { pantalla_usuario* p = new pantalla_usuario(this); p->show(); a->close(); } } void GUI::handleAltaCompetencia(QDialog *a, QString b, QString nombreComp, Deporte* dep, QVector<Lugar *> lugs, QVector<int> disps, Modalidad* mod, QString reglamento) { if (b == "crearCompetencia") { bool op; QString error; Usuario* user = gestorUsuarios->getActual(); DtoCompetencia* dtoC = new DtoCompetencia(user,nombreComp,dep,lugs,disps,mod,reglamento); if(gestorCompetencias->crearCompetencia(dtoC,op,error) != NULL){ QMessageBox* msg = new QMessageBox(a); msg->setText("Competencia creada correctamente"); QPixmap icono(":/images/Heros-verde-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); } else{ // QMessageBox fracaso QMessageBox* msg = new QMessageBox(a); QString error1 = "Error al crear la competencia. \n" + error; msg->setText(error1); QPixmap icono(":/images/Heros-rojo-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); } a->close(); } } bool GUI::handleVerCompetencia(QDialog *a, QString b, QString error, Competencia* comp) { competenciaActual = comp; if (b == "modificarCompetencia") { /* code */ } else if (b == "generarFixture") { return gestorCompetencias->generarFixture(comp,error); competenciaActual = comp; } else if (b == "bajaCompetencia") { /* code */ } else if (b == "mostrarFixture") { comp = gestorCompetencias->getCompetenciaFull(comp->getId()); mostrar_fixture* mf = new mostrar_fixture(this,comp,a); mf->setModal(true); mf->show(); } else if (b == "mostrarTablasPosiciones") { tabla_posiciones* t = new tabla_posiciones(this,comp,a); t->setModal(true); t->show(); } else if (b == "listarParticipantes"){ participantes = comp->getParticipantes(); listar_participante * lp = new listar_participante(this,comp, a); lp->setModal(true); lp->show(); } return false; } void GUI::handleMostrarFixture(QDialog *a, QString b,Partido* partido) { if (b == "gestionarFixture") { gestionar_fixture* gf = new gestionar_fixture(competenciaActual,partido,this,a); gf->setModal(true); gf->show(); } } void GUI::handleGestionarFixture(QDialog *a, QString b, Partido *partP, Resultado *resP) { gestorCompetencias->nuevoResultado(competenciaActual,partP,resP); competenciaActual = gestorCompetencias->getCompetenciaFull(competenciaActual->getId()); QMessageBox* msg = new QMessageBox(a); msg->setText("Partido cargado correctamente"); QPixmap icono(":/images/Heros-verde-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); a->close(); } QVector<Competencia*> GUI::handleFiltrarCompetencias(QStringList data) { QString nombreComp, deporte, estado, tipoModalidad; Usuario* usuario = gestorUsuarios->getActual(); nombreComp = data[0]; deporte = data[1]; estado = data[2]; tipoModalidad = data[3]; Estado* e = this->buscarEstado(estado); Deporte* d = this->buscarDeporte(deporte); TipoModalidad* tm = this->buscarTipoModalidad(tipoModalidad); DtoGetCompetencia* datos = new DtoGetCompetencia(usuario,nombreComp,d,tm,e); return gestorCompetencias->getCompetenciasLazy(datos); } QString GUI::handleRegistrarUsuario(DtoUsuario *datos) { QString error; gestorUsuarios->altaUsuario(datos,error); return error; } QVector<Deporte *> GUI::getDeportes() const { return deportes; } void GUI::setDeportes(const QVector<Deporte *> &value) { deportes = value; } QVector<Provincia *> GUI::getProvincias(Pais *paisP) { return gestorUsuarios->getProvincias(paisP); } QVector<Localidad *> GUI::getLocalidades(Provincia *provinciaP) { return gestorUsuarios->getLocalidades(provinciaP); } QVector<Participante*> GUI::handleAltaParticipante(QDialog *a, QString nombre, QString email, QString ImgUrl) { DtoParticipante* datos = new DtoParticipante(nombre,email,ImgUrl); QString error; if(gestorCompetencias->altaParticipante(competenciaActual,datos,error)){ QMessageBox* msg = new QMessageBox(a); msg->setText(error); QPixmap icono(":/images/Heros-verde-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); return competenciaActual->getParticipantes(); } else{ QMessageBox* msg = new QMessageBox(a); msg->setText(error); QPixmap icono(":/images/Heros-rojo-64.png"); msg->setIconPixmap(icono); msg->setModal(true); msg->exec(); QVector<Participante*> aux; return aux; } } Estado *GUI::buscarEstado(QString estado) { for (int i = 0; i < estados.size(); ++i) { if(estado.toLower() == estados[i]->getNombre().toLower()) return estados[i]; } return NULL; } Deporte *GUI::buscarDeporte(QString deporte) { for (int i = 0; i < deportes.size(); ++i) { if(deporte.toLower()==deportes[i]->getNombre().toLower()) return deportes[i]; } return NULL; } TipoModalidad *GUI::buscarTipoModalidad(QString tipoMod) { for (int i = 0; i < modalidades.size(); ++i) { if(tipoMod.toLower() == modalidades[i]->getNombre().toLower()) return modalidades[i]; } return NULL; } void GUI::show() { MainWindow * m = new MainWindow(this); m->show(); } void MainWindow::on_pushButton_clicked() { gui->handleMain(this,QString("registrarUsuario")); } EmailValidator::EmailValidator(QObject *parent) : QValidator(parent), m_validMailRegExp("[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}"), m_intermediateMailRegExp("[a-z0-9._%+-]*@?[a-z0-9.-]*\\.?[a-z]*"){} QValidator::State EmailValidator::validate(QString &text, int &pos) const { Q_UNUSED(pos) fixup(text); if (m_validMailRegExp.exactMatch(text)) return Acceptable; if (m_intermediateMailRegExp.exactMatch(text)) return Intermediate; return Invalid; } void EmailValidator::fixup(QString &text) const { text = text.trimmed().toLower(); } <|endoftext|>
<commit_before>// GLEW #define GLEW_STATIC #include <GL/glew.h> // GL includes #include "Demos.h" #include "Window.h" gwindow::Window window; // The MAIN function, from here we start our application and run our Game loop int main() { window.create(WINDOW_NAME, SCREEN_WIDTH, SCREEN_HEIGHT); // Initialize GLEW to setup the OpenGL Function pointers glewExperimental = GL_TRUE; glewInit(); render_superbible_perpixelgloss(window.getWindow()); //render_superbible_cubemapenv(window.getWindow()); //render_superbible_equirectangular(window.getWindow()); //render_superbible_envmapsphere(window.getWindow()); //render_superbible_rimlight(window.getWindow()); //render_superbible_phonglighting(window.getWindow()); //render_superbible_csflocking(window.getWindow()); //render_superbible_shapedpoints(window.getWindow()); //render_superbible_hdrtonemap(window.getWindow()); //render_superbible_polygonsmooth(window.getWindow()); //render_superbible_linesmooth(window.getWindow()); //render_superbible_basicfbo(window.getWindow()); //render_superbible_depthclamp(window.getWindow()); //render_superbible_multiscissor(window.getWindow()); //render_superbible_noperspective(window.getWindow()); //render_superbible_multiviewport(window.getWindow()); //render_superbible_gsquads(window.getWindow()); //render_superbible_normalviewer(window.getWindow()); //render_superbible_gstessellate(window.getWindow()); //render_superbible_objectexploder(window.getWindow()); //render_superbible_gsculling(window.getWindow()); //render_superbible_cubicbezier(window.getWindow()); //render_superbible_dispmap(window.getWindow()); //render_superbible_tessmodes(window.getWindow()); //render_superbible_clipdistance(window.getWindow()); //render_superbible_multidrawindirect(window.getWindow()); //render_superbible_instancedattribs(window.getWindow()); //render_superbible_fragmentlist(window.getWindow()); //render_skybox_demo(window.getWindow()); //render_exploding_demo(window.getWindow()); //render_instancing_demo(window.getWindow()); return 0; }<commit_msg>Git configs<commit_after>// GLEW #define GLEW_STATIC #include <GL/glew.h> // GL includes #include "Demos.h" #include "Window.h" gwindow::Window window; // The MAIN function, from here we start our application and run our Game loop int main() { window.create(WINDOW_NAME, SCREEN_WIDTH, SCREEN_HEIGHT); // Initialize GLEW to setup the OpenGL Function pointers glewExperimental = GL_TRUE; glewInit(); //render_superbible_perpixelgloss(window.getWindow()); //render_superbible_cubemapenv(window.getWindow()); //render_superbible_equirectangular(window.getWindow()); //render_superbible_envmapsphere(window.getWindow()); //render_superbible_rimlight(window.getWindow()); //render_superbible_phonglighting(window.getWindow()); //render_superbible_csflocking(window.getWindow()); //render_superbible_shapedpoints(window.getWindow()); //render_superbible_hdrtonemap(window.getWindow()); //render_superbible_polygonsmooth(window.getWindow()); //render_superbible_linesmooth(window.getWindow()); //render_superbible_basicfbo(window.getWindow()); //render_superbible_depthclamp(window.getWindow()); //render_superbible_multiscissor(window.getWindow()); //render_superbible_noperspective(window.getWindow()); //render_superbible_multiviewport(window.getWindow()); //render_superbible_gsquads(window.getWindow()); //render_superbible_normalviewer(window.getWindow()); //render_superbible_gstessellate(window.getWindow()); //render_superbible_objectexploder(window.getWindow()); //render_superbible_gsculling(window.getWindow()); //render_superbible_cubicbezier(window.getWindow()); //render_superbible_dispmap(window.getWindow()); //render_superbible_tessmodes(window.getWindow()); //render_superbible_clipdistance(window.getWindow()); //render_superbible_multidrawindirect(window.getWindow()); //render_superbible_instancedattribs(window.getWindow()); //render_superbible_fragmentlist(window.getWindow()); //render_skybox_demo(window.getWindow()); render_exploding_demo(window.getWindow()); //render_instancing_demo(window.getWindow()); return 0; }<|endoftext|>
<commit_before>//--------------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2009 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <base/config.h> #if (DEAL_II_USE_MT == 1) && !defined(DEAL_II_CAN_USE_CXX0X) // of the C++ compiler doesn't completely support the C++0x standard (and // consequently we can't use std::thread, std::mutex, etc), then include all // the files that form BOOST's thread implementation so that we don't have to // build BOOST itself only to get at this small part of it. it also ensures // that we use the correct compiler and flags # define BOOST_THREAD_BUILD_LIB 1 # define DBOOST_ALL_NO_LIB 1 # ifdef DEAL_II_USE_MT_POSIX # define BOOST_THREAD_POSIX # include <boost/cstdint.hpp> # ifndef UINTMAX_C # define UINTMAX_C(x) x ## ULL # endif # include <../libs/thread/src/pthread/once.cpp> # include <../libs/thread/src/pthread/thread.cpp> # else # include <../libs/thread/src/win32/once.cpp> # include <../libs/thread/src/win32/thread.cpp> # endif #endif <commit_msg>Make sure we use the included boost library. This isn't going to work if someone tries to use an external boost version, but I can't see right now how that would work in the first place. At least we'd have to test this once or twice.<commit_after>//--------------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2009, 2010 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <base/config.h> #if (DEAL_II_USE_MT == 1) && !defined(DEAL_II_CAN_USE_CXX0X) // of the C++ compiler doesn't completely support the C++0x standard (and // consequently we can't use std::thread, std::mutex, etc), then include all // the files that form BOOST's thread implementation so that we don't have to // build BOOST itself only to get at this small part of it. it also ensures // that we use the correct compiler and flags # define BOOST_THREAD_BUILD_LIB 1 # define DBOOST_ALL_NO_LIB 1 # ifdef DEAL_II_USE_MT_POSIX # define BOOST_THREAD_POSIX # include <boost/cstdint.hpp> # ifndef UINTMAX_C # define UINTMAX_C(x) x ## ULL # endif # include "../contrib/boost/libs/thread/src/pthread/once.cpp" # include "../contrib/boost/libs/thread/src/pthread/thread.cpp" # else # include "../contrib/boost/libs/thread/src/win32/once.cpp" # include "../contrib/boost/libs/thread/src/win32/thread.cpp" # endif #endif <|endoftext|>
<commit_before>/******************************************************************************* * Project: libopencad * Purpose: OpenSource CAD formats support library * Author: Alexandr Borzykh, mush3d at gmail.com * Author: Dmitry Baryshnikov, [email protected] * Language: C++ ******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2016 Alexandr Borzykh * Copyright (c) 2016 NextGIS, <[email protected]> * * 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 "cadfilestreamio.h" CADFileStreamIO::CADFileStreamIO(const char* pszFilePath) : CADFileIO(pszFilePath) { } CADFileStreamIO::~CADFileStreamIO() { } const char* CADFileStreamIO::ReadLine() { // TODO: getline return nullptr; } bool CADFileStreamIO::Eof() { return m_oFileStream.eof(); } bool CADFileStreamIO::Open(int mode) { auto io_mode = std::ios_base::in; // as we use ifstream if(mode & OpenMode::binary) io_mode |= std::ios_base::binary; if(mode & OpenMode::write) //io_mode |= std::ios_base::out; return false; m_oFileStream = std::ifstream ( m_pszFilePath, io_mode); if(m_oFileStream.is_open()) m_bIsOpened = true; return m_bIsOpened; } bool CADFileStreamIO::Close() { m_oFileStream.close(); return CADFileIO::Close(); } int CADFileStreamIO::Seek(long offset, CADFileIO::SeekOrigin origin) { std::ios_base::seekdir direction; switch (origin) { case SeekOrigin::CUR: direction = std::ios_base::cur; break; case SeekOrigin::END: direction = std::ios_base::end; break; case SeekOrigin::BEG: direction = std::ios_base::beg; break; } return m_oFileStream.seekg(offset, direction).good() ? 0 : 1; } long CADFileStreamIO::Tell() { return m_oFileStream.tellg(); } size_t CADFileStreamIO::Read(void* ptr, size_t size) { return static_cast<size_t>(m_oFileStream.read( static_cast<char*>(ptr), static_cast<long>(size)).gcount()); } size_t CADFileStreamIO::Write(void* /*ptr*/, size_t /*size*/) { // unsupported return 0; } void CADFileStreamIO::Rewind() { m_oFileStream.seekg(0, std::ios_base::beg); } <commit_msg>Fix travis build (assigning ifstream error)<commit_after>/******************************************************************************* * Project: libopencad * Purpose: OpenSource CAD formats support library * Author: Alexandr Borzykh, mush3d at gmail.com * Author: Dmitry Baryshnikov, [email protected] * Language: C++ ******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2016 Alexandr Borzykh * Copyright (c) 2016 NextGIS, <[email protected]> * * 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 "cadfilestreamio.h" CADFileStreamIO::CADFileStreamIO(const char* pszFilePath) : CADFileIO(pszFilePath) { } CADFileStreamIO::~CADFileStreamIO() { } const char* CADFileStreamIO::ReadLine() { // TODO: getline return nullptr; } bool CADFileStreamIO::Eof() { return m_oFileStream.eof(); } bool CADFileStreamIO::Open(int mode) { auto io_mode = std::ios_base::in; // as we use ifstream if(mode & OpenMode::binary) io_mode |= std::ios_base::binary; if(mode & OpenMode::write) //io_mode |= std::ios_base::out; return false; m_oFileStream.open( m_pszFilePath, io_mode ); if(m_oFileStream.is_open()) m_bIsOpened = true; return m_bIsOpened; } bool CADFileStreamIO::Close() { m_oFileStream.close(); return CADFileIO::Close(); } int CADFileStreamIO::Seek(long offset, CADFileIO::SeekOrigin origin) { std::ios_base::seekdir direction; switch (origin) { case SeekOrigin::CUR: direction = std::ios_base::cur; break; case SeekOrigin::END: direction = std::ios_base::end; break; case SeekOrigin::BEG: direction = std::ios_base::beg; break; } return m_oFileStream.seekg(offset, direction).good() ? 0 : 1; } long CADFileStreamIO::Tell() { return m_oFileStream.tellg(); } size_t CADFileStreamIO::Read(void* ptr, size_t size) { return static_cast<size_t>(m_oFileStream.read( static_cast<char*>(ptr), static_cast<long>(size)).gcount()); } size_t CADFileStreamIO::Write(void* /*ptr*/, size_t /*size*/) { // unsupported return 0; } void CADFileStreamIO::Rewind() { m_oFileStream.seekg(0, std::ios_base::beg); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: adminpages.hxx,v $ * * $Revision: 1.21 $ * * last change: $Author: fs $ $Date: 2001-05-23 13:47:00 $ * * 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 EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DBAUI_ADMINPAGES_HXX_ #define _DBAUI_ADMINPAGES_HXX_ #ifndef _SFXTABDLG_HXX #include <sfx2/tabdlg.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _SV_EDIT_HXX #include <vcl/edit.hxx> #endif #ifndef _SV_BUTTON_HXX #include <vcl/imagebtn.hxx> #endif #ifndef _SV_GROUP_HXX #include <vcl/group.hxx> #endif #ifndef _SV_COMBOBOX_HXX #include <vcl/combobox.hxx> #endif #ifndef _DBAUI_DSNTYPES_HXX_ #include "dsntypes.hxx" #endif #ifndef _DBAUI_CHARSETS_HXX_ #include "charsets.hxx" #endif #ifndef _DBAUI_CURLEDIT_HXX_ #include "curledit.hxx" #endif #ifndef _DBAUI_TABLETREE_HXX_ #include "tabletree.hxx" #endif #ifndef _DBAUI_COMMON_TYPES_HXX_ #include "commontypes.hxx" #endif #ifndef _UCBHELPER_CONTENT_HXX #include <ucbhelper/content.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif //......................................................................... namespace dbaui { //......................................................................... //========================================================================= //= OPageSettings //========================================================================= struct OPageSettings { virtual ~OPageSettings(); }; //========================================================================= //= OGenericAdministrationPage //========================================================================= class ODbAdminDialog; class OGenericAdministrationPage : public SfxTabPage { protected: Link m_aModifiedHandler; /// to be called if something on the page has been modified public: OGenericAdministrationPage(Window* _pParent, const ResId& _rId, const SfxItemSet& _rAttrSet); /// set a handler which gets called every time something on the page has been modified void SetModifiedHandler(const Link& _rHandler) { m_aModifiedHandler = _rHandler; } /** create an instance of view settings for the page <p>The caller is responsible for destroying the object later on.</p> <p>The page may return <NULL/> if it does not support view settings.</p> */ virtual OPageSettings* createViewSettings(); /** get the pages current view settings, if any */ virtual void fillViewSettings(OPageSettings* _pSettings); /** called by the dialog after changes have been applied asnychronously <p>The page can use this method to restore it's (non-persistent, e.g. view-) settings to the state before the changes have been applied</p> <p>This method is necessary because during applying, the page may die and be re-created.</p> @param _pPageState the page state as given in <method>ODbAdminDialog::applyChangesAsync</method> @see ODbAdminDialog::applyChangesAsync */ virtual void restoreViewSettings(const OPageSettings* _pSettings); protected: /// default implementation: call FillItemSet, call checkItems, virtual int DeactivatePage(SfxItemSet* pSet); /// default implementation: call implInitControls with the given item set and _bSaveValue = sal_False virtual void Reset(const SfxItemSet& _rCoreAttrs); /// default implementation: call implInitControls with the given item set and _bSaveValue = sal_True virtual void ActivatePage(const SfxItemSet& _rSet); protected: void callModifiedHdl() const { if (m_aModifiedHandler.IsSet()) m_aModifiedHandler.Call((void*)this); } /// called from within DeactivatePage. The page is allowed to be deactivated if this method returns sal_True virtual sal_Bool checkItems() { return sal_True; } /** called from within Reset and ActivatePage, use to initialize the controls with the items from the given set @param _bSaveValue if set to sal_True, the implementation should call SaveValue on all relevant controls */ virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue) { } /// analyze the invalid and the readonly flag which may be present in the set void getFlags(const SfxItemSet& _rSet, sal_Bool& _rValid, sal_Bool& _rReadonly); /** prepares an action which requires a connection to work with. <p>It is checked if the current data source is modified. If in this case the dialog is appliable, and the user confirms the apply, an asyncApplyChanges (on the dialog) with the page settings given is executed. <p>If no async apply is necessary, the settings given (if not <NULL/> are deleted.</p> @return <TRUE/> if the action can be continued, <FALSE/> otherwise */ sal_Bool prepareConnectionAction( ODbAdminDialog* _pDialog, const String& _rActionDescription, OPageSettings** _pViewSettings = NULL ); protected: /** This link be used for controls where the tabpage does not need to take any special action when the control is modified. The implementation just calls callModifiedHdl. */ DECL_LINK(OnControlModified, Control*); /// may be used in SetXXXHdl calls to controls, is a link to <method>OnControlModified</method> Link getControlModifiedLink() { return LINK(this, OGenericAdministrationPage, OnControlModified); } }; //......................................................................... } // namespace dbaui //......................................................................... #endif // _DBAUI_ADMINPAGES_HXX_ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.20 2001/05/10 13:34:29 fs * #86223# +OPageSettings/createViewSettings/filleViewSettings/restoreViewSettings * * Revision 1.19 2001/01/26 16:12:12 fs * split up the file * * Revision 1.18 2001/01/26 06:59:12 fs * some basics for the query administration page - not enabled yet * * Revision 1.17 2001/01/04 11:21:45 fs * #81485# +OAdoDetailsPage * * Revision 1.16 2000/12/07 14:15:42 oj * #81131# check installed adabas dbs * * Revision 1.0 26.09.00 11:46:15 fs ************************************************************************/ <commit_msg>#86082# +OToolboxedPageViewSettings<commit_after>/************************************************************************* * * $RCSfile: adminpages.hxx,v $ * * $Revision: 1.22 $ * * last change: $Author: fs $ $Date: 2001-05-29 10:17:26 $ * * 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 EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DBAUI_ADMINPAGES_HXX_ #define _DBAUI_ADMINPAGES_HXX_ #ifndef _SFXTABDLG_HXX #include <sfx2/tabdlg.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _SV_EDIT_HXX #include <vcl/edit.hxx> #endif #ifndef _SV_BUTTON_HXX #include <vcl/imagebtn.hxx> #endif #ifndef _SV_GROUP_HXX #include <vcl/group.hxx> #endif #ifndef _SV_COMBOBOX_HXX #include <vcl/combobox.hxx> #endif #ifndef _DBAUI_DSNTYPES_HXX_ #include "dsntypes.hxx" #endif #ifndef _DBAUI_CHARSETS_HXX_ #include "charsets.hxx" #endif #ifndef _DBAUI_CURLEDIT_HXX_ #include "curledit.hxx" #endif #ifndef _DBAUI_TABLETREE_HXX_ #include "tabletree.hxx" #endif #ifndef _DBAUI_COMMON_TYPES_HXX_ #include "commontypes.hxx" #endif #ifndef _UCBHELPER_CONTENT_HXX #include <ucbhelper/content.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif //......................................................................... namespace dbaui { //......................................................................... //========================================================================= //= OPageSettings //========================================================================= struct OPageSettings { virtual ~OPageSettings(); }; //========================================================================= //= OToolboxedPageViewSettings //========================================================================= struct OToolboxedPageViewSettings : public OPageSettings { sal_uInt16 nDelayedToolboxAction; OToolboxedPageViewSettings() : nDelayedToolboxAction(0) { } }; //========================================================================= //= OGenericAdministrationPage //========================================================================= class ODbAdminDialog; class OGenericAdministrationPage : public SfxTabPage { protected: Link m_aModifiedHandler; /// to be called if something on the page has been modified public: OGenericAdministrationPage(Window* _pParent, const ResId& _rId, const SfxItemSet& _rAttrSet); /// set a handler which gets called every time something on the page has been modified void SetModifiedHandler(const Link& _rHandler) { m_aModifiedHandler = _rHandler; } /** create an instance of view settings for the page <p>The caller is responsible for destroying the object later on.</p> <p>The page may return <NULL/> if it does not support view settings.</p> */ virtual OPageSettings* createViewSettings(); /** get the pages current view settings, if any */ virtual void fillViewSettings(OPageSettings* _pSettings); /** called by the dialog after changes have been applied asnychronously <p>The page can use this method to restore it's (non-persistent, e.g. view-) settings to the state before the changes have been applied</p> <p>This method is necessary because during applying, the page may die and be re-created.</p> @param _pPageState the page state as given in <method>ODbAdminDialog::applyChangesAsync</method> @see ODbAdminDialog::applyChangesAsync */ virtual void restoreViewSettings(const OPageSettings* _pSettings); protected: /// default implementation: call FillItemSet, call checkItems, virtual int DeactivatePage(SfxItemSet* pSet); /// default implementation: call implInitControls with the given item set and _bSaveValue = sal_False virtual void Reset(const SfxItemSet& _rCoreAttrs); /// default implementation: call implInitControls with the given item set and _bSaveValue = sal_True virtual void ActivatePage(const SfxItemSet& _rSet); protected: void callModifiedHdl() const { if (m_aModifiedHandler.IsSet()) m_aModifiedHandler.Call((void*)this); } /// called from within DeactivatePage. The page is allowed to be deactivated if this method returns sal_True virtual sal_Bool checkItems() { return sal_True; } /** called from within Reset and ActivatePage, use to initialize the controls with the items from the given set @param _bSaveValue if set to sal_True, the implementation should call SaveValue on all relevant controls */ virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue) { } /// analyze the invalid and the readonly flag which may be present in the set void getFlags(const SfxItemSet& _rSet, sal_Bool& _rValid, sal_Bool& _rReadonly); /** prepares an action which requires a connection to work with. <p>It is checked if the current data source is modified. If in this case the dialog is appliable, and the user confirms the apply, an asyncApplyChanges (on the dialog) with the page settings given is executed. <p>If no async apply is necessary, the settings given (if not <NULL/> are deleted.</p> @return <TRUE/> if the action can be continued, <FALSE/> otherwise */ sal_Bool prepareConnectionAction( ODbAdminDialog* _pDialog, const String& _rActionDescription, OPageSettings** _pViewSettings = NULL ); protected: /** This link be used for controls where the tabpage does not need to take any special action when the control is modified. The implementation just calls callModifiedHdl. */ DECL_LINK(OnControlModified, Control*); /// may be used in SetXXXHdl calls to controls, is a link to <method>OnControlModified</method> Link getControlModifiedLink() { return LINK(this, OGenericAdministrationPage, OnControlModified); } }; //......................................................................... } // namespace dbaui //......................................................................... #endif // _DBAUI_ADMINPAGES_HXX_ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.21 2001/05/23 13:47:00 fs * #86444# +prepareConnectionAction * * Revision 1.20 2001/05/10 13:34:29 fs * #86223# +OPageSettings/createViewSettings/filleViewSettings/restoreViewSettings * * Revision 1.19 2001/01/26 16:12:12 fs * split up the file * * Revision 1.18 2001/01/26 06:59:12 fs * some basics for the query administration page - not enabled yet * * Revision 1.17 2001/01/04 11:21:45 fs * #81485# +OAdoDetailsPage * * Revision 1.16 2000/12/07 14:15:42 oj * #81131# check installed adabas dbs * * Revision 1.0 26.09.00 11:46:15 fs ************************************************************************/ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: odbcconfig.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2007-07-24 12:09:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _DBAUI_ODBC_CONFIG_HXX_ #define _DBAUI_ODBC_CONFIG_HXX_ #include "commontypes.hxx" #if defined(WIN) || defined(WNT) || defined (UNX) #define HAVE_ODBC_SUPPORT #endif #if ( defined(WIN) || defined(WNT) ) && defined(HAVE_ODBC_SUPPORT) #define HAVE_ODBC_ADMINISTRATION #endif #include <tools/link.hxx> #include <osl/module.h> #include <memory> //......................................................................... namespace dbaui { //......................................................................... //========================================================================= //= OOdbcLibWrapper //========================================================================= /** base for helper classes wrapping functionality from an ODBC library */ class OOdbcLibWrapper { oslModule m_pOdbcLib; // the library handle ::rtl::OUString m_sLibPath; // the path to the library public: #ifdef HAVE_ODBC_SUPPORT sal_Bool isLoaded() const { return NULL != m_pOdbcLib; } #else sal_Bool isLoaded() const { return sal_False; } #endif ::rtl::OUString getLibraryName() const { return m_sLibPath; } protected: #ifndef HAVE_ODBC_SUPPORT OOdbcLibWrapper() : m_pOdbcLib(NULL) { } #endif OOdbcLibWrapper(); ~OOdbcLibWrapper(); oslGenericFunction loadSymbol(const sal_Char* _pFunctionName); /// load the lib sal_Bool load(const sal_Char* _pLibPath); /// unload the lib void unload(); }; //========================================================================= //= OOdbcEnumeration //========================================================================= struct OdbcTypesImpl; class OOdbcEnumeration : public OOdbcLibWrapper { #ifdef HAVE_ODBC_SUPPORT // entry points for ODBC administration oslGenericFunction m_pAllocHandle; oslGenericFunction m_pFreeHandle; oslGenericFunction m_pSetEnvAttr; oslGenericFunction m_pDataSources; #endif OdbcTypesImpl* m_pImpl; // needed because we can't have a member of type SQLHANDLE: this would require us to include the respective // ODBC file, which would lead to a lot of conflicts with other includes public: OOdbcEnumeration(); ~OOdbcEnumeration(); void getDatasourceNames(StringBag& _rNames); protected: /// ensure that an ODBC environment is allocated sal_Bool allocEnv(); /// free any allocated ODBC environment void freeEnv(); }; //========================================================================= //= OOdbcManagement //========================================================================= #ifdef HAVE_ODBC_ADMINISTRATION class ProcessTerminationWait; class OOdbcManagement { ::std::auto_ptr< ProcessTerminationWait > m_pProcessWait; Link m_aAsyncFinishCallback; public: OOdbcManagement( const Link& _rAsyncFinishCallback ); ~OOdbcManagement(); bool manageDataSources_async(); bool isRunning() const; }; #endif //......................................................................... } // namespace dbaui //......................................................................... #endif // _DBAUI_ODBC_CONFIG_HXX_ <commit_msg>INTEGRATION: CWS os2port01 (1.6.106); FILE MERGED 2007/09/05 07:15:14 obr 1.6.106.2: RESYNC: (1.6-1.7); FILE MERGED 2006/12/28 14:54:08 ydario 1.6.106.1: OS/2 initial import.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: odbcconfig.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: vg $ $Date: 2007-09-20 14:58:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _DBAUI_ODBC_CONFIG_HXX_ #define _DBAUI_ODBC_CONFIG_HXX_ #include "commontypes.hxx" #if defined(WIN) || defined(WNT) || defined (UNX) #define HAVE_ODBC_SUPPORT #endif #if ( defined(WIN) || defined(WNT) ) && defined(HAVE_ODBC_SUPPORT) #define HAVE_ODBC_ADMINISTRATION #endif #include <tools/link.hxx> #include <osl/module.h> #include <memory> //......................................................................... namespace dbaui { //......................................................................... //========================================================================= //= OOdbcLibWrapper //========================================================================= /** base for helper classes wrapping functionality from an ODBC library */ class OOdbcLibWrapper { oslModule m_pOdbcLib; // the library handle ::rtl::OUString m_sLibPath; // the path to the library public: #ifdef HAVE_ODBC_SUPPORT sal_Bool isLoaded() const { return NULL != m_pOdbcLib; } #else sal_Bool isLoaded() const { return sal_False; } #endif ::rtl::OUString getLibraryName() const { return m_sLibPath; } protected: #ifndef HAVE_ODBC_SUPPORT OOdbcLibWrapper() : m_pOdbcLib(NULL) { } #else OOdbcLibWrapper(); #endif ~OOdbcLibWrapper(); oslGenericFunction loadSymbol(const sal_Char* _pFunctionName); /// load the lib sal_Bool load(const sal_Char* _pLibPath); /// unload the lib void unload(); }; //========================================================================= //= OOdbcEnumeration //========================================================================= struct OdbcTypesImpl; class OOdbcEnumeration : public OOdbcLibWrapper { #ifdef HAVE_ODBC_SUPPORT // entry points for ODBC administration oslGenericFunction m_pAllocHandle; oslGenericFunction m_pFreeHandle; oslGenericFunction m_pSetEnvAttr; oslGenericFunction m_pDataSources; #endif OdbcTypesImpl* m_pImpl; // needed because we can't have a member of type SQLHANDLE: this would require us to include the respective // ODBC file, which would lead to a lot of conflicts with other includes public: OOdbcEnumeration(); ~OOdbcEnumeration(); void getDatasourceNames(StringBag& _rNames); protected: /// ensure that an ODBC environment is allocated sal_Bool allocEnv(); /// free any allocated ODBC environment void freeEnv(); }; //========================================================================= //= OOdbcManagement //========================================================================= #ifdef HAVE_ODBC_ADMINISTRATION class ProcessTerminationWait; class OOdbcManagement { ::std::auto_ptr< ProcessTerminationWait > m_pProcessWait; Link m_aAsyncFinishCallback; public: OOdbcManagement( const Link& _rAsyncFinishCallback ); ~OOdbcManagement(); bool manageDataSources_async(); bool isRunning() const; }; #endif //......................................................................... } // namespace dbaui //......................................................................... #endif // _DBAUI_ODBC_CONFIG_HXX_ <|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS residcleanup (1.14.112); FILE MERGED 2007/02/28 20:46:11 pl 1.14.112.1: #i74635# no more ResMgr fallback<commit_after><|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <unordered_set> // UNSUPPORTED: c++98, c++03, c++11, c++14 // UNSUPPORTED: libcpp-no-deduction-guides // UNSUPPORTED: apple-clang-9.1 // template<class InputIterator, // class Hash = hash<iter-value-type<InputIterator>>, // class Pred = equal_to<iter-value-type<InputIterator>>, // class Allocator = allocator<iter-value-type<InputIterator>>> // unordered_set(InputIterator, InputIterator, typename see below::size_type = see below, // Hash = Hash(), Pred = Pred(), Allocator = Allocator()) // -> unordered_set<iter-value-type<InputIterator>, // Hash, Pred, Allocator>; // // template<class T, class Hash = hash<T>, // class Pred = equal_to<T>, class Allocator = allocator<T>> // unordered_set(initializer_list<T>, typename see below::size_type = see below, // Hash = Hash(), Pred = Pred(), Allocator = Allocator()) // -> unordered_set<T, Hash, Pred, Allocator>; // // template<class InputIterator, class Allocator> // unordered_set(InputIterator, InputIterator, typename see below::size_type, Allocator) // -> unordered_set<iter-value-type<InputIterator>, // hash<iter-value-type<InputIterator>>, // equal_to<iter-value-type<InputIterator>>, // Allocator>; // // template<class InputIterator, class Hash, class Allocator> // unordered_set(InputIterator, InputIterator, typename see below::size_type, // Hash, Allocator) // -> unordered_set<iter-value-type<InputIterator>, Hash, // equal_to<iter-value-type<InputIterator>>, // Allocator>; // // template<class T, class Allocator> // unordered_set(initializer_list<T>, typename see below::size_type, Allocator) // -> unordered_set<T, hash<T>, equal_to<T>, Allocator>; // // template<class T, class Hash, class Allocator> // unordered_set(initializer_list<T>, typename see below::size_type, Hash, Allocator) // -> unordered_set<T, Hash, equal_to<T>, Allocator>; //#include <algorithm> // is_permutation //#include <cassert> //#include <climits> // INT_MAX //#include <type_traits> //#include <unordered_set> // //#include "test_allocator.h" void main() { const int expected_s[] = {1, 2, 3, INT_MAX}; { const int arr[] = { 1, 2, 1, INT_MAX, 3 }; momo::stdish::unordered_set s(std::begin(arr), std::end(arr)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } { const int arr[] = { 1, 2, 1, INT_MAX, 3 }; momo::stdish::unordered_set s(std::begin(arr), std::end(arr), 42); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } { const int arr[] = { 1, 2, 1, INT_MAX, 3 }; momo::stdish::unordered_set s(std::begin(arr), std::end(arr), 42, std::hash<short>()); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } { const int arr[] = { 1, 2, 1, INT_MAX, 3 }; momo::stdish::unordered_set s(std::begin(arr), std::end(arr), 42, std::hash<short>(), test_allocator<int>(0, 40)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<int>, test_allocator<int>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); assert(s.get_allocator().get_id() == 40); } { momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<>, test_allocator<int>> source; momo::stdish::unordered_set s(source); ASSERT_SAME_TYPE(decltype(s), decltype(source)); assert(s.size() == 0); } { momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<>, test_allocator<int>> source; momo::stdish::unordered_set s{source}; // braces instead of parens ASSERT_SAME_TYPE(decltype(s), decltype(source)); assert(s.size() == 0); } { momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<>, test_allocator<int>> source; momo::stdish::unordered_set s(source, test_allocator<int>(0, 41)); ASSERT_SAME_TYPE(decltype(s), decltype(source)); assert(s.size() == 0); assert(s.get_allocator().get_id() == 41); } { momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<>, test_allocator<int>> source; momo::stdish::unordered_set s{source, test_allocator<int>(0, 42)}; // braces instead of parens ASSERT_SAME_TYPE(decltype(s), decltype(source)); assert(s.size() == 0); assert(s.get_allocator().get_id() == 42); } { momo::stdish::unordered_set s{ 1, 2, 1, INT_MAX, 3 }; ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } { momo::stdish::unordered_set s({ 1, 2, 1, INT_MAX, 3 }, 42); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } { momo::stdish::unordered_set s({ 1, 2, 1, INT_MAX, 3 }, 42, std::hash<short>()); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } { momo::stdish::unordered_set s({ 1, 2, 1, INT_MAX, 3 }, 42, std::hash<short>(), std::equal_to<>()); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } { momo::stdish::unordered_set s({ 1, 2, 1, INT_MAX, 3 }, 42, std::hash<short>(), std::equal_to<>(), test_allocator<int>(0, 43)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<>, test_allocator<int>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); assert(s.get_allocator().get_id() == 43); } { const int arr[] = { 1, 2, 1, INT_MAX, 3 }; momo::stdish::unordered_set s(std::begin(arr), std::end(arr), 42, test_allocator<int>(0, 44)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<int>, std::equal_to<int>, test_allocator<int>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); assert(s.get_allocator().get_id() == 44); } { const int arr[] = { 1, 2, 1, INT_MAX, 3 }; momo::stdish::unordered_set s(std::begin(arr), std::end(arr), 42, std::hash<short>(), test_allocator<int>(0, 44)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<int>, test_allocator<int>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); assert(s.get_allocator().get_id() == 44); } { momo::stdish::unordered_set s({ 1, 2, 1, INT_MAX, 3 }, 42, test_allocator<int>(0, 43)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<int>, std::equal_to<int>, test_allocator<int>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); assert(s.get_allocator().get_id() == 43); } { momo::stdish::unordered_set s({ 1, 2, 1, INT_MAX, 3 }, 42, std::hash<short>(), test_allocator<int>(0, 42)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<int>, test_allocator<int>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); assert(s.get_allocator().get_id() == 42); } } <commit_msg>Deduction: unordered_set<commit_after>//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <unordered_set> // UNSUPPORTED: c++98, c++03, c++11, c++14 // UNSUPPORTED: libcpp-no-deduction-guides // UNSUPPORTED: apple-clang-9.1 // template<class InputIterator, // class Hash = hash<iter-value-type<InputIterator>>, // class Pred = equal_to<iter-value-type<InputIterator>>, // class Allocator = allocator<iter-value-type<InputIterator>>> // unordered_set(InputIterator, InputIterator, typename see below::size_type = see below, // Hash = Hash(), Pred = Pred(), Allocator = Allocator()) // -> unordered_set<iter-value-type<InputIterator>, // Hash, Pred, Allocator>; // // template<class T, class Hash = hash<T>, // class Pred = equal_to<T>, class Allocator = allocator<T>> // unordered_set(initializer_list<T>, typename see below::size_type = see below, // Hash = Hash(), Pred = Pred(), Allocator = Allocator()) // -> unordered_set<T, Hash, Pred, Allocator>; // // template<class InputIterator, class Allocator> // unordered_set(InputIterator, InputIterator, typename see below::size_type, Allocator) // -> unordered_set<iter-value-type<InputIterator>, // hash<iter-value-type<InputIterator>>, // equal_to<iter-value-type<InputIterator>>, // Allocator>; // // template<class InputIterator, class Hash, class Allocator> // unordered_set(InputIterator, InputIterator, typename see below::size_type, // Hash, Allocator) // -> unordered_set<iter-value-type<InputIterator>, Hash, // equal_to<iter-value-type<InputIterator>>, // Allocator>; // // template<class T, class Allocator> // unordered_set(initializer_list<T>, typename see below::size_type, Allocator) // -> unordered_set<T, hash<T>, equal_to<T>, Allocator>; // // template<class T, class Hash, class Allocator> // unordered_set(initializer_list<T>, typename see below::size_type, Hash, Allocator) // -> unordered_set<T, Hash, equal_to<T>, Allocator>; //#include <algorithm> // is_permutation //#include <cassert> //#include <climits> // INT_MAX //#include <type_traits> //#include <unordered_set> // //#include "test_allocator.h" void main() { const int expected_s[] = {1, 2, 3, INT_MAX}; { const int arr[] = { 1, 2, 1, INT_MAX, 3 }; momo::stdish::unordered_set s(std::begin(arr), std::end(arr)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } { const int arr[] = { 1, 2, 1, INT_MAX, 3 }; momo::stdish::unordered_set s(std::begin(arr), std::end(arr), 42); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } { const int arr[] = { 1, 2, 1, INT_MAX, 3 }; momo::stdish::unordered_set s(std::begin(arr), std::end(arr), 42, std::hash<short>()); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } { const int arr[] = { 1, 2, 1, INT_MAX, 3 }; momo::stdish::unordered_set s(std::begin(arr), std::end(arr), 42, std::hash<short>(), test_allocator<int>(0, 40)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<int>, test_allocator<int>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); assert(s.get_allocator().get_id() == 40); } { momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<>, test_allocator<int>> source; momo::stdish::unordered_set s(source); ASSERT_SAME_TYPE(decltype(s), decltype(source)); assert(s.size() == 0); } { momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<>, test_allocator<int>> source; momo::stdish::unordered_set s{source}; // braces instead of parens ASSERT_SAME_TYPE(decltype(s), decltype(source)); assert(s.size() == 0); } { momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<>, test_allocator<int>> source; momo::stdish::unordered_set s(source, test_allocator<int>(0, 41)); ASSERT_SAME_TYPE(decltype(s), decltype(source)); assert(s.size() == 0); assert(s.get_allocator().get_id() == 41); } { momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<>, test_allocator<int>> source; momo::stdish::unordered_set s{source, test_allocator<int>(0, 42)}; // braces instead of parens ASSERT_SAME_TYPE(decltype(s), decltype(source)); assert(s.size() == 0); assert(s.get_allocator().get_id() == 42); } { momo::stdish::unordered_set s{ 1, 2, 1, INT_MAX, 3 }; ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } { momo::stdish::unordered_set s({ 1, 2, 1, INT_MAX, 3 }, 42); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } { momo::stdish::unordered_set s({ 1, 2, 1, INT_MAX, 3 }, 42, std::hash<short>()); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } #ifdef LIBCPP_HAS_BAD_NEWS_FOR_MOMO { momo::stdish::unordered_set s({ 1, 2, 1, INT_MAX, 3 }, 42, std::hash<short>(), std::equal_to<>()); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); } #endif { momo::stdish::unordered_set s({ 1, 2, 1, INT_MAX, 3 }, 42, std::hash<short>(), std::equal_to<>(), test_allocator<int>(0, 43)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<>, test_allocator<int>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); assert(s.get_allocator().get_id() == 43); } { const int arr[] = { 1, 2, 1, INT_MAX, 3 }; momo::stdish::unordered_set s(std::begin(arr), std::end(arr), 42, test_allocator<int>(0, 44)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, momo::HashCoder<int>, std::equal_to<int>, test_allocator<int>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); assert(s.get_allocator().get_id() == 44); } { const int arr[] = { 1, 2, 1, INT_MAX, 3 }; momo::stdish::unordered_set s(std::begin(arr), std::end(arr), 42, std::hash<short>(), test_allocator<int>(0, 44)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<int>, test_allocator<int>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); assert(s.get_allocator().get_id() == 44); } { momo::stdish::unordered_set s({ 1, 2, 1, INT_MAX, 3 }, 42, test_allocator<int>(0, 43)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, momo::HashCoder<int>, std::equal_to<int>, test_allocator<int>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); assert(s.get_allocator().get_id() == 43); } { momo::stdish::unordered_set s({ 1, 2, 1, INT_MAX, 3 }, 42, std::hash<short>(), test_allocator<int>(0, 42)); ASSERT_SAME_TYPE(decltype(s), momo::stdish::unordered_set<int, std::hash<short>, std::equal_to<int>, test_allocator<int>>); assert(std::is_permutation(s.begin(), s.end(), std::begin(expected_s), std::end(expected_s))); assert(s.get_allocator().get_id() == 42); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xlocx.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: obo $ $Date: 2007-01-22 13:22:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_XLOCX_HXX #define SC_XLOCX_HXX #ifndef _MSOCXIMEX_HXX #include <svx/msocximex.hxx> #endif #ifndef SC_XIROOT_HXX #include "xiroot.hxx" #endif #ifndef SC_XEROOT_HXX #include "xeroot.hxx" #endif // 0 = Export TBX form controls, 1 = Export OCX form controls. #define EXC_EXP_OCX_CTRL 0 // OCX controls =============================================================== /** Converter base class for import and export of OXC controls. @descr The purpose of this class is to manage all the draw pages occuring in a spreadsheet document. Derived classes implement import or export of the controls. */ class XclOcxConverter : protected SvxMSConvertOCXControls { protected: explicit XclOcxConverter( const XclRoot& rRoot ); virtual ~XclOcxConverter(); /** Sets the sheet index of the currently processed object. GetDrawPage() needs this. */ void SetScTab( SCTAB nScTab ); /** Calls SetScTab() with the passed sheet index and updates the xDrawPage base class member. */ void SetDrawPage( SCTAB nScTab ); private: /** Returns the current draw page. */ virtual const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& GetDrawPage(); private: const XclRoot& mrRoot; /// Root data. SCTAB mnCurrScTab; /// Stores sheet index of an object for GetDrawPage(). SCTAB mnCachedScTab; /// Sheet index of cached draw page. }; // ---------------------------------------------------------------------------- class Rectangle; class SdrObject; class XclImpOleObj; class XclImpTbxControlObj; class XclImpControlObjHelper; /** Converter for import of OXC controls. */ class XclImpOcxConverter : public XclOcxConverter, protected XclImpRoot { public: explicit XclImpOcxConverter( const XclImpRoot& rRoot ); /** Reads the control formatting data for the passed object and creates the SdrUnoObj. */ SdrObject* CreateSdrObject( XclImpOleObj& rOcxCtrlObj, const Rectangle& rAnchorRect ); /** Creates the SdrUnoObj for the passed TBX form control object. */ SdrObject* CreateSdrObject( XclImpTbxControlObj& rTbxCtrlObj, const Rectangle& rAnchorRect ); private: /** Inserts the passed control rxFComp into the form. */ virtual sal_Bool InsertControl( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent >& rxFComp, const ::com::sun::star::awt::Size& rSize, ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >* pxShape, BOOL bFloatingCtrl ); /** Returns the SdrObject from the passed shape. Sets the passed anchor rectangle. */ SdrObject* FinalizeSdrObject( XclImpControlObjHelper& rCtrlObj, ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape, const Rectangle& rAnchorRect ) const; /** Tries to register a Basic macro for the control. */ void RegisterTbxMacro( const XclImpTbxControlObj& rTbxCtrlObj ); private: SotStorageStreamRef mxStrm; /// The 'Ctls' stream in the Excel file. sal_Int32 mnLastIndex; /// Last insertion index of a control. }; // ---------------------------------------------------------------------------- class SdrObject; #if EXC_EXP_OCX_CTRL class XclExpOcxControlObj; #else class XclExpTbxControlObj; #endif class XclExpCtrlLinkHelper; /** Converter for export of OXC controls. */ class XclExpOcxConverter : public XclOcxConverter, protected XclExpRoot { public: explicit XclExpOcxConverter( const XclExpRoot& rRoot ); #if EXC_EXP_OCX_CTRL /** Creates an OCX form control OBJ record from the passed form control. @descr Writes the form control data to the 'Ctls' stream. */ XclExpOcxControlObj* CreateCtrlObj( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ); private: SotStorageStreamRef mxStrm; /// The 'Ctls' stream. #else /** Creates a TBX form control OBJ record from the passed form control. */ XclExpTbxControlObj* CreateCtrlObj( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ); private: /** Tries to get the name of a Basic macro from a control. */ void ConvertTbxMacro( XclExpTbxControlObj& rTbxCtrlObj, ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > xCtrlModel ); #endif }; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS changefileheader (1.14.342); FILE MERGED 2008/04/01 15:30:20 thb 1.14.342.3: #i85898# Stripping all external header guards 2008/04/01 12:36:24 thb 1.14.342.2: #i85898# Stripping all external header guards 2008/03/31 17:14:48 rt 1.14.342.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xlocx.hxx,v $ * $Revision: 1.15 $ * * 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. * ************************************************************************/ #ifndef SC_XLOCX_HXX #define SC_XLOCX_HXX #include <svx/msocximex.hxx> #include "xiroot.hxx" #include "xeroot.hxx" // 0 = Export TBX form controls, 1 = Export OCX form controls. #define EXC_EXP_OCX_CTRL 0 // OCX controls =============================================================== /** Converter base class for import and export of OXC controls. @descr The purpose of this class is to manage all the draw pages occuring in a spreadsheet document. Derived classes implement import or export of the controls. */ class XclOcxConverter : protected SvxMSConvertOCXControls { protected: explicit XclOcxConverter( const XclRoot& rRoot ); virtual ~XclOcxConverter(); /** Sets the sheet index of the currently processed object. GetDrawPage() needs this. */ void SetScTab( SCTAB nScTab ); /** Calls SetScTab() with the passed sheet index and updates the xDrawPage base class member. */ void SetDrawPage( SCTAB nScTab ); private: /** Returns the current draw page. */ virtual const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& GetDrawPage(); private: const XclRoot& mrRoot; /// Root data. SCTAB mnCurrScTab; /// Stores sheet index of an object for GetDrawPage(). SCTAB mnCachedScTab; /// Sheet index of cached draw page. }; // ---------------------------------------------------------------------------- class Rectangle; class SdrObject; class XclImpOleObj; class XclImpTbxControlObj; class XclImpControlObjHelper; /** Converter for import of OXC controls. */ class XclImpOcxConverter : public XclOcxConverter, protected XclImpRoot { public: explicit XclImpOcxConverter( const XclImpRoot& rRoot ); /** Reads the control formatting data for the passed object and creates the SdrUnoObj. */ SdrObject* CreateSdrObject( XclImpOleObj& rOcxCtrlObj, const Rectangle& rAnchorRect ); /** Creates the SdrUnoObj for the passed TBX form control object. */ SdrObject* CreateSdrObject( XclImpTbxControlObj& rTbxCtrlObj, const Rectangle& rAnchorRect ); private: /** Inserts the passed control rxFComp into the form. */ virtual sal_Bool InsertControl( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent >& rxFComp, const ::com::sun::star::awt::Size& rSize, ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >* pxShape, BOOL bFloatingCtrl ); /** Returns the SdrObject from the passed shape. Sets the passed anchor rectangle. */ SdrObject* FinalizeSdrObject( XclImpControlObjHelper& rCtrlObj, ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape, const Rectangle& rAnchorRect ) const; /** Tries to register a Basic macro for the control. */ void RegisterTbxMacro( const XclImpTbxControlObj& rTbxCtrlObj ); private: SotStorageStreamRef mxStrm; /// The 'Ctls' stream in the Excel file. sal_Int32 mnLastIndex; /// Last insertion index of a control. }; // ---------------------------------------------------------------------------- class SdrObject; #if EXC_EXP_OCX_CTRL class XclExpOcxControlObj; #else class XclExpTbxControlObj; #endif class XclExpCtrlLinkHelper; /** Converter for export of OXC controls. */ class XclExpOcxConverter : public XclOcxConverter, protected XclExpRoot { public: explicit XclExpOcxConverter( const XclExpRoot& rRoot ); #if EXC_EXP_OCX_CTRL /** Creates an OCX form control OBJ record from the passed form control. @descr Writes the form control data to the 'Ctls' stream. */ XclExpOcxControlObj* CreateCtrlObj( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ); private: SotStorageStreamRef mxStrm; /// The 'Ctls' stream. #else /** Creates a TBX form control OBJ record from the passed form control. */ XclExpTbxControlObj* CreateCtrlObj( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape ); private: /** Tries to get the name of a Basic macro from a control. */ void ConvertTbxMacro( XclExpTbxControlObj& rTbxCtrlObj, ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > xCtrlModel ); #endif }; // ============================================================================ #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE --------------------------------------------------------------- #include <vcl/outdev.hxx> #include "drawutil.hxx" #include "document.hxx" #include "global.hxx" #include "viewdata.hxx" // STATIC DATA ----------------------------------------------------------- // ----------------------------------------------------------------------- inline Fraction MakeFraction( long nA, long nB ) { return ( nA && nB ) ? Fraction(nA,nB) : Fraction(1,1); } void ScDrawUtil::CalcScale( ScDocument* pDoc, SCTAB nTab, SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow, OutputDevice* pDev, const Fraction& rZoomX, const Fraction& rZoomY, double nPPTX, double nPPTY, Fraction& rScaleX, Fraction& rScaleY ) { long nPixelX = 0; long nTwipsX = 0; long nPixelY = 0; long nTwipsY = 0; for (SCCOL i=nStartCol; i<nEndCol; i++) { sal_uInt16 nWidth = pDoc->GetColWidth(i,nTab); nTwipsX += (long) nWidth; nPixelX += ScViewData::ToPixel( nWidth, nPPTX ); } for (SCROW nRow = nStartRow; nRow <= nEndRow-1; ++nRow) { SCROW nLastRow = nRow; if (pDoc->RowHidden(nRow, nTab, NULL, &nLastRow)) { nRow = nLastRow; continue; } sal_uInt16 nHeight = pDoc->GetRowHeight(nRow, nTab); nTwipsY += static_cast<long>(nHeight); nPixelY += ScViewData::ToPixel(nHeight, nPPTY); } MapMode aHMMMode( MAP_100TH_MM, Point(), rZoomX, rZoomY ); Point aPixelLog = pDev->PixelToLogic( Point( nPixelX,nPixelY ), aHMMMode ); // Fraction(double) ctor can be used here (and avoid overflows of PixelLog * Zoom) // because ReduceInaccurate is called later anyway. if ( aPixelLog.X() && nTwipsX ) rScaleX = Fraction( ((double)aPixelLog.X()) * ((double)rZoomX.GetNumerator()) / ((double)nTwipsX) / ((double)HMM_PER_TWIPS) / ((double)rZoomX.GetDenominator()) ); else rScaleX = Fraction( 1, 1 ); if ( aPixelLog.Y() && nTwipsY ) rScaleY = Fraction( ((double)aPixelLog.Y()) * ((double)rZoomY.GetNumerator()) / ((double)nTwipsY) / ((double)HMM_PER_TWIPS) / ((double)rZoomY.GetDenominator()) ); else rScaleY = Fraction( 1, 1 ); // 25 bits of accuracy are needed to always hit the right part of // cells in the last rows (was 17 before 1M rows). rScaleX.ReduceInaccurate( 25 ); rScaleY.ReduceInaccurate( 25 ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>calc69: #i118068# handle all-hidden case in ScDrawUtil::CalcScale<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE --------------------------------------------------------------- #include <vcl/outdev.hxx> #include "drawutil.hxx" #include "document.hxx" #include "global.hxx" #include "viewdata.hxx" // STATIC DATA ----------------------------------------------------------- // ----------------------------------------------------------------------- inline Fraction MakeFraction( long nA, long nB ) { return ( nA && nB ) ? Fraction(nA,nB) : Fraction(1,1); } void ScDrawUtil::CalcScale( ScDocument* pDoc, SCTAB nTab, SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow, OutputDevice* pDev, const Fraction& rZoomX, const Fraction& rZoomY, double nPPTX, double nPPTY, Fraction& rScaleX, Fraction& rScaleY ) { long nPixelX = 0; long nTwipsX = 0; long nPixelY = 0; long nTwipsY = 0; for (SCCOL i=nStartCol; i<nEndCol; i++) { sal_uInt16 nWidth = pDoc->GetColWidth(i,nTab); nTwipsX += (long) nWidth; nPixelX += ScViewData::ToPixel( nWidth, nPPTX ); } for (SCROW nRow = nStartRow; nRow <= nEndRow-1; ++nRow) { SCROW nLastRow = nRow; if (pDoc->RowHidden(nRow, nTab, NULL, &nLastRow)) { nRow = nLastRow; continue; } sal_uInt16 nHeight = pDoc->GetRowHeight(nRow, nTab); nTwipsY += static_cast<long>(nHeight); nPixelY += ScViewData::ToPixel(nHeight, nPPTY); } // #i116848# To get a large-enough number for PixelToLogic, multiply the integer values // instead of using a larger number of rows if ( nTwipsY ) { long nMultiply = 2000000 / nTwipsY; if ( nMultiply > 1 ) { nTwipsY *= nMultiply; nPixelY *= nMultiply; } } MapMode aHMMMode( MAP_100TH_MM, Point(), rZoomX, rZoomY ); Point aPixelLog = pDev->PixelToLogic( Point( nPixelX,nPixelY ), aHMMMode ); // Fraction(double) ctor can be used here (and avoid overflows of PixelLog * Zoom) // because ReduceInaccurate is called later anyway. if ( aPixelLog.X() && nTwipsX ) rScaleX = Fraction( ((double)aPixelLog.X()) * ((double)rZoomX.GetNumerator()) / ((double)nTwipsX) / ((double)HMM_PER_TWIPS) / ((double)rZoomX.GetDenominator()) ); else rScaleX = Fraction( 1, 1 ); if ( aPixelLog.Y() && nTwipsY ) rScaleY = Fraction( ((double)aPixelLog.Y()) * ((double)rZoomY.GetNumerator()) / ((double)nTwipsY) / ((double)HMM_PER_TWIPS) / ((double)rZoomY.GetDenominator()) ); else rScaleY = Fraction( 1, 1 ); // 25 bits of accuracy are needed to always hit the right part of // cells in the last rows (was 17 before 1M rows). rScaleX.ReduceInaccurate( 25 ); rScaleY.ReduceInaccurate( 25 ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// @(#)root/test:$Name: $:$Id: MainEvent.cxx,v 1.24 2002/08/17 21:39:33 brun Exp $ // Author: Rene Brun 19/01/97 //////////////////////////////////////////////////////////////////////// // // A simple example with a ROOT tree // ================================= // // This program creates : // - a ROOT file // - a tree // Additional arguments can be passed to the program to control the flow // of execution. (see comments describing the arguments in the code). // Event nevent comp split fill // All arguments are optional. Default is: // Event 400 1 1 1 // // In this example, the tree consists of one single "super branch" // The statement ***tree->Branch("event", event, 64000,split);*** below // will parse the structure described in Event.h and will make // a new branch for each data member of the class if split is set to 1. // - 9 branches corresponding to the basic types fType, fNtrack,fNseg, // fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance. // - 3 branches corresponding to the members of the subobject EventHeader. // - one branch for each data member of the class Track of TClonesArray. // - one branch for the TRefArray of high Pt tracks // - one branch for the TRefArray of muon tracks // - one branch for the reference pointer to the last track // - one branch for the object fH (histogram of class TH1F). // // if split = 0 only one single branch is created and the complete event // is serialized in one single buffer. // if split = -2 the event is split using the old TBranchObject mechanism // if split = -1 the event is streamed using the old TBranchObject mechanism // if split > 0 the event is split using the new TBranchElement mechanism. // // if comp = 0 no compression at all. // if comp = 1 event is compressed. // if comp = 2 same as 1. In addition branches with floats in the TClonesArray // are also compressed. // The 4th argument fill can be set to 0 if one wants to time // the percentage of time spent in creating the event structure and // not write the event in the file. // In this example, one loops over nevent events. // The branch "event" is created at the first event. // The branch address is set for all other events. // For each event, the event header is filled and ntrack tracks // are generated and added to the TClonesArray list. // For each event the event histogram is saved as well as the list // of all tracks. // // The two TRefArray contain only references to the original tracks owned by // the TClonesArray fTracks. // // The number of events can be given as the first argument to the program. // By default 400 events are generated. // The compression option can be activated/deactivated via the second argument. // // ---Running/Linking instructions---- // This program consists of the following files and procedures. // - Event.h event class description // - Event.C event class implementation // - MainEvent.C the main program to demo this class might be used (this file) // - EventCint.C the CINT dictionary for the event and Track classes // this file is automatically generated by rootcint (see Makefile), // when the class definition in Event.h is modified. // // ---Analyzing the Event.root file with the interactive root // example of a simple session // Root > TFile f("Event.root") // Root > T.Draw("fNtrack") //histogram the number of tracks per event // Root > T.Draw("fPx") //histogram fPx for all tracks in all events // Root > T.Draw("fXfirst:fYfirst","fNtrack>600") // //scatter-plot for x versus y of first point of each track // Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram // // Look also in the same directory at the following macros: // - eventa.C an example how to read the tree // - eventb.C how to read events conditionally // //////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "Riostream.h" #include "TROOT.h" #include "TFile.h" #include "TNetFile.h" #include "TRandom.h" #include "TTree.h" #include "TBranch.h" #include "TClonesArray.h" #include "TStopwatch.h" #include "Event.h" //______________________________________________________________________________ int main(int argc, char **argv) { Int_t nevent = 400; // by default create 400 events Int_t comp = 1; // by default file is compressed Int_t split = 1; // by default, split Event in sub branches Int_t write = 1; // by default the tree is filled Int_t hfill = 0; // by default histograms are not filled Int_t read = 0; Int_t arg4 = 1; Int_t arg5 = 600; //default number of tracks per event Int_t netf = 0; if (argc > 1) nevent = atoi(argv[1]); if (argc > 2) comp = atoi(argv[2]); if (argc > 3) split = atoi(argv[3]); if (argc > 4) arg4 = atoi(argv[4]); if (argc > 5) arg5 = atoi(argv[5]); if (arg4 == 0) { write = 0; hfill = 0; read = 1;} if (arg4 == 1) { write = 1; hfill = 0;} if (arg4 == 2) { write = 0; hfill = 0;} if (arg4 == 10) { write = 0; hfill = 1;} if (arg4 == 11) { write = 1; hfill = 1;} if (arg4 == 20) { write = 0; read = 1;} //read sequential if (arg4 == 25) { write = 0; read = 2;} //read random if (arg4 >= 30) { netf = 1; } //use TNetFile if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential if (arg4 == 35) { write = 0; read = 2;} //netfile + read random if (arg4 == 36) { write = 1; } //netfile + write sequential Int_t branchStyle = 1; //new style by default if (split < 0) {branchStyle = 0; split = -1-split;} TFile *hfile; TTree *tree; Event *event = 0; // Fill event, header and tracks with some random numbers // Create a timer object to benchmark this loop TStopwatch timer; timer.Start(); Int_t nb = 0; Int_t ev; Int_t bufsize; Double_t told = 0; Double_t tnew = 0; Int_t printev = 100; if (arg5 < 100) printev = 1000; if (arg5 < 10) printev = 10000; //In this new version of mainEvent, one cannot activate the next statement //because tracks are referenced //Track::Class()->IgnoreTObjectStreamer(); // Read case if (read) { if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root"); hfile->UseCache(10); } else hfile = new TFile("Event.root"); tree = (TTree*)hfile->Get("T"); TBranch *branch = tree->GetBranch("event"); branch->SetAddress(&event); Int_t nentries = (Int_t)tree->GetEntries(); nevent = TMath::Max(nevent,nentries); if (read == 1) { //read sequential for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); told=tnew; timer.Continue(); } nb += tree->GetEntry(ev); //read complete event in memory } } else { //read random Int_t evrandom; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) cout<<"event="<<ev<<endl; evrandom = Int_t(nevent*gRandom->Rndm(1)); nb += tree->GetEntry(evrandom); //read complete event in memory } } } else { // Write case // Create a new ROOT binary machine independent file. // Note that this file may contain any kind of ROOT objects, histograms, // pictures, graphics objects, detector geometries, tracks, events, etc.. // This file is now becoming the current directory. if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file"); hfile->UseCache(10); } else hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file"); hfile->SetCompressionLevel(comp); // Create histogram to show write_time in function of time Float_t curtime = -0.5; Int_t ntime = nevent/printev; TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime); HistogramManager *hm = 0; if (hfill) { TDirectory *hdir = new TDirectory("histograms", "all histograms"); hm = new HistogramManager(hdir); } // Create a ROOT Tree and one superbranch TTree *tree = new TTree("T","An example of a ROOT tree"); tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written bufsize = 64000; if (split) bufsize /= 4; event = new Event(); TTree::SetBranchStyle(branchStyle); TBranch *branch = tree->Branch("event", "Event", &event, bufsize,split); branch->SetAutoDelete(kFALSE); Float_t ptmin = 1; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); htime->Fill(curtime,tnew-told); curtime += 1; told=tnew; timer.Continue(); } event->Build(ev, arg5, ptmin); if (write) nb += tree->Fill(); //fill the tree if (hm) hm->Hfill(event); //fill histograms } if (write) { hfile = tree->GetCurrentFile(); //just in case we switched to a new file hfile->Write(); tree->Print(); } } // Stop timer and print results timer.Stop(); Float_t mbytes = 0.000001*nb; Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); printf("\n%d events and %d bytes processed.\n",nevent,nb); printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime); if (read) { printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime); } else { printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4); printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime); //printf("file compression factor = %f\n",hfile.GetCompressionFactor()); } hfile->Close(); return 0; } <commit_msg>Add a call to TTree::SetMaxTreeSize to give the possibility to create a Tree as big as 2 Terabytes (if the system can do it). For example try the following: Event 100000 0 7 1 This should create a Tree of size 7.6 Gigabytes<commit_after>// @(#)root/test:$Name: $:$Id: MainEvent.cxx,v 1.25 2002/11/13 17:35:50 rdm Exp $ // Author: Rene Brun 19/01/97 //////////////////////////////////////////////////////////////////////// // // A simple example with a ROOT tree // ================================= // // This program creates : // - a ROOT file // - a tree // Additional arguments can be passed to the program to control the flow // of execution. (see comments describing the arguments in the code). // Event nevent comp split fill // All arguments are optional. Default is: // Event 400 1 1 1 // // In this example, the tree consists of one single "super branch" // The statement ***tree->Branch("event", event, 64000,split);*** below // will parse the structure described in Event.h and will make // a new branch for each data member of the class if split is set to 1. // - 9 branches corresponding to the basic types fType, fNtrack,fNseg, // fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance. // - 3 branches corresponding to the members of the subobject EventHeader. // - one branch for each data member of the class Track of TClonesArray. // - one branch for the TRefArray of high Pt tracks // - one branch for the TRefArray of muon tracks // - one branch for the reference pointer to the last track // - one branch for the object fH (histogram of class TH1F). // // if split = 0 only one single branch is created and the complete event // is serialized in one single buffer. // if split = -2 the event is split using the old TBranchObject mechanism // if split = -1 the event is streamed using the old TBranchObject mechanism // if split > 0 the event is split using the new TBranchElement mechanism. // // if comp = 0 no compression at all. // if comp = 1 event is compressed. // if comp = 2 same as 1. In addition branches with floats in the TClonesArray // are also compressed. // The 4th argument fill can be set to 0 if one wants to time // the percentage of time spent in creating the event structure and // not write the event in the file. // In this example, one loops over nevent events. // The branch "event" is created at the first event. // The branch address is set for all other events. // For each event, the event header is filled and ntrack tracks // are generated and added to the TClonesArray list. // For each event the event histogram is saved as well as the list // of all tracks. // // The two TRefArray contain only references to the original tracks owned by // the TClonesArray fTracks. // // The number of events can be given as the first argument to the program. // By default 400 events are generated. // The compression option can be activated/deactivated via the second argument. // // ---Running/Linking instructions---- // This program consists of the following files and procedures. // - Event.h event class description // - Event.C event class implementation // - MainEvent.C the main program to demo this class might be used (this file) // - EventCint.C the CINT dictionary for the event and Track classes // this file is automatically generated by rootcint (see Makefile), // when the class definition in Event.h is modified. // // ---Analyzing the Event.root file with the interactive root // example of a simple session // Root > TFile f("Event.root") // Root > T.Draw("fNtrack") //histogram the number of tracks per event // Root > T.Draw("fPx") //histogram fPx for all tracks in all events // Root > T.Draw("fXfirst:fYfirst","fNtrack>600") // //scatter-plot for x versus y of first point of each track // Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram // // Look also in the same directory at the following macros: // - eventa.C an example how to read the tree // - eventb.C how to read events conditionally // //////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "Riostream.h" #include "TROOT.h" #include "TFile.h" #include "TNetFile.h" #include "TRandom.h" #include "TTree.h" #include "TBranch.h" #include "TClonesArray.h" #include "TStopwatch.h" #include "Event.h" //______________________________________________________________________________ int main(int argc, char **argv) { Int_t nevent = 400; // by default create 400 events Int_t comp = 1; // by default file is compressed Int_t split = 1; // by default, split Event in sub branches Int_t write = 1; // by default the tree is filled Int_t hfill = 0; // by default histograms are not filled Int_t read = 0; Int_t arg4 = 1; Int_t arg5 = 600; //default number of tracks per event Int_t netf = 0; if (argc > 1) nevent = atoi(argv[1]); if (argc > 2) comp = atoi(argv[2]); if (argc > 3) split = atoi(argv[3]); if (argc > 4) arg4 = atoi(argv[4]); if (argc > 5) arg5 = atoi(argv[5]); if (arg4 == 0) { write = 0; hfill = 0; read = 1;} if (arg4 == 1) { write = 1; hfill = 0;} if (arg4 == 2) { write = 0; hfill = 0;} if (arg4 == 10) { write = 0; hfill = 1;} if (arg4 == 11) { write = 1; hfill = 1;} if (arg4 == 20) { write = 0; read = 1;} //read sequential if (arg4 == 25) { write = 0; read = 2;} //read random if (arg4 >= 30) { netf = 1; } //use TNetFile if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential if (arg4 == 35) { write = 0; read = 2;} //netfile + read random if (arg4 == 36) { write = 1; } //netfile + write sequential Int_t branchStyle = 1; //new style by default if (split < 0) {branchStyle = 0; split = -1-split;} TFile *hfile; TTree *tree; Event *event = 0; // Fill event, header and tracks with some random numbers // Create a timer object to benchmark this loop TStopwatch timer; timer.Start(); Int_t nb = 0; Int_t ev; Int_t bufsize; Double_t told = 0; Double_t tnew = 0; Int_t printev = 100; if (arg5 < 100) printev = 1000; if (arg5 < 10) printev = 10000; //Authorize Trees up to 2 Terabytes (if the system can do it) TTree::SetMaxTreeSize(1000*Long64_t(2000000000)); // Read case if (read) { if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root"); hfile->UseCache(10); } else hfile = new TFile("Event.root"); tree = (TTree*)hfile->Get("T"); TBranch *branch = tree->GetBranch("event"); branch->SetAddress(&event); Int_t nentries = (Int_t)tree->GetEntries(); nevent = TMath::Max(nevent,nentries); if (read == 1) { //read sequential for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); told=tnew; timer.Continue(); } nb += tree->GetEntry(ev); //read complete event in memory } } else { //read random Int_t evrandom; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) cout<<"event="<<ev<<endl; evrandom = Int_t(nevent*gRandom->Rndm(1)); nb += tree->GetEntry(evrandom); //read complete event in memory } } } else { // Write case // Create a new ROOT binary machine independent file. // Note that this file may contain any kind of ROOT objects, histograms, // pictures, graphics objects, detector geometries, tracks, events, etc.. // This file is now becoming the current directory. if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file"); hfile->UseCache(10); } else hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file"); hfile->SetCompressionLevel(comp); // Create histogram to show write_time in function of time Float_t curtime = -0.5; Int_t ntime = nevent/printev; TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime); HistogramManager *hm = 0; if (hfill) { TDirectory *hdir = new TDirectory("histograms", "all histograms"); hm = new HistogramManager(hdir); } // Create a ROOT Tree and one superbranch TTree *tree = new TTree("T","An example of a ROOT tree"); tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written bufsize = 64000; if (split) bufsize /= 4; event = new Event(); TTree::SetBranchStyle(branchStyle); TBranch *branch = tree->Branch("event", "Event", &event, bufsize,split); branch->SetAutoDelete(kFALSE); Float_t ptmin = 1; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); htime->Fill(curtime,tnew-told); curtime += 1; told=tnew; timer.Continue(); } event->Build(ev, arg5, ptmin); if (write) nb += tree->Fill(); //fill the tree if (hm) hm->Hfill(event); //fill histograms } if (write) { hfile = tree->GetCurrentFile(); //just in case we switched to a new file hfile->Write(); tree->Print(); } } // Stop timer and print results timer.Stop(); Float_t mbytes = 0.000001*nb; Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); printf("\n%d events and %d bytes processed.\n",nevent,nb); printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime); if (read) { printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime); } else { printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4); printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime); //printf("file compression factor = %f\n",hfile.GetCompressionFactor()); } hfile->Close(); return 0; } <|endoftext|>
<commit_before>//===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass is responsible for finalizing the functions frame layout, saving // callee saved registers, and for emitting prolog & epilog code for the // function. // // This pass must be run after register allocation. After this pass is // executed, it is illegal to construct MO_FrameIndex operands. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/MRegisterInfo.h" #include "llvm/Target/TargetFrameInfo.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Support/Compiler.h" using namespace llvm; namespace { struct VISIBILITY_HIDDEN PEI : public MachineFunctionPass { const char *getPassName() const { return "Prolog/Epilog Insertion & Frame Finalization"; } /// runOnMachineFunction - Insert prolog/epilog code and replace abstract /// frame indexes with appropriate references. /// bool runOnMachineFunction(MachineFunction &Fn) { // Get MachineDebugInfo so that we can track the construction of the // frame. if (MachineDebugInfo *DI = getAnalysisToUpdate<MachineDebugInfo>()) { Fn.getFrameInfo()->setMachineDebugInfo(DI); } // Scan the function for modified callee saved registers and insert spill // code for any callee saved registers that are modified. Also calculate // the MaxCallFrameSize and HasCalls variables for the function's frame // information and eliminates call frame pseudo instructions. calculateCalleeSavedRegisters(Fn); // Add the code to save and restore the caller saved registers saveCallerSavedRegisters(Fn); // Allow the target machine to make final modifications to the function // before the frame layout is finalized. Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn); // Calculate actual frame offsets for all of the abstract stack objects... calculateFrameObjectOffsets(Fn); // Add prolog and epilog code to the function. This function is required // to align the stack frame as necessary for any stack variables or // called functions. Because of this, calculateCalleeSavedRegisters // must be called before this function in order to set the HasCalls // and MaxCallFrameSize variables. insertPrologEpilogCode(Fn); // Replace all MO_FrameIndex operands with physical register references // and actual offsets. // replaceFrameIndices(Fn); return true; } private: void calculateCalleeSavedRegisters(MachineFunction &Fn); void saveCallerSavedRegisters(MachineFunction &Fn); void calculateFrameObjectOffsets(MachineFunction &Fn); void replaceFrameIndices(MachineFunction &Fn); void insertPrologEpilogCode(MachineFunction &Fn); }; } /// createPrologEpilogCodeInserter - This function returns a pass that inserts /// prolog and epilog code, and eliminates abstract frame references. /// FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); } /// calculateCalleeSavedRegisters - Scan the function for modified caller saved /// registers. Also calculate the MaxCallFrameSize and HasCalls variables for /// the function's frame information and eliminates call frame pseudo /// instructions. /// void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) { const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo(); const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo(); // Get the callee saved register list... const unsigned *CSRegs = RegInfo->getCalleeSaveRegs(); // Get the function call frame set-up and tear-down instruction opcode int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode(); int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode(); // Early exit for targets which have no callee saved registers and no call // frame setup/destroy pseudo instructions. if ((CSRegs == 0 || CSRegs[0] == 0) && FrameSetupOpcode == -1 && FrameDestroyOpcode == -1) return; unsigned MaxCallFrameSize = 0; bool HasCalls = false; for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) if (I->getOpcode() == FrameSetupOpcode || I->getOpcode() == FrameDestroyOpcode) { assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo" " instructions should have a single immediate argument!"); unsigned Size = I->getOperand(0).getImmedValue(); if (Size > MaxCallFrameSize) MaxCallFrameSize = Size; HasCalls = true; RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++); } else { ++I; } MachineFrameInfo *FFI = Fn.getFrameInfo(); FFI->setHasCalls(HasCalls); FFI->setMaxCallFrameSize(MaxCallFrameSize); // Now figure out which *callee saved* registers are modified by the current // function, thus needing to be saved and restored in the prolog/epilog. // const bool *PhysRegsUsed = Fn.getUsedPhysregs(); const TargetRegisterClass* const *CSRegClasses = RegInfo->getCalleeSaveRegClasses(); std::vector<CalleeSavedInfo> CSI; for (unsigned i = 0; CSRegs[i]; ++i) { unsigned Reg = CSRegs[i]; if (PhysRegsUsed[Reg]) { // If the reg is modified, save it! CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i])); } else { for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg); *AliasSet; ++AliasSet) { // Check alias registers too. if (PhysRegsUsed[*AliasSet]) { CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i])); break; } } } } if (CSI.empty()) return; // Early exit if no caller saved registers are modified! unsigned NumFixedSpillSlots; const std::pair<unsigned,int> *FixedSpillSlots = TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots); // Now that we know which registers need to be saved and restored, allocate // stack slots for them. for (unsigned i = 0, e = CSI.size(); i != e; ++i) { unsigned Reg = CSI[i].getReg(); const TargetRegisterClass *RC = CSI[i].getRegClass(); // Check to see if this physreg must be spilled to a particular stack slot // on this target. const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots; while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots && FixedSlot->first != Reg) ++FixedSlot; int FrameIdx; if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) { // Nope, just spill it anywhere convenient. FrameIdx = FFI->CreateStackObject(RC->getSize(), RC->getAlignment()); } else { // Spill it to the stack where we must. FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second); } CSI[i].setFrameIdx(FrameIdx); } FFI->setCalleeSavedInfo(CSI); } /// saveCallerSavedRegisters - Insert spill code for any caller saved registers /// that are modified in the function. /// void PEI::saveCallerSavedRegisters(MachineFunction &Fn) { // Get callee saved register information. MachineFrameInfo *FFI = Fn.getFrameInfo(); const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo(); // Early exit if no caller saved registers are modified! if (CSI.empty()) return; const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo(); // Now that we have a stack slot for each register to be saved, insert spill // code into the entry block. MachineBasicBlock *MBB = Fn.begin(); MachineBasicBlock::iterator I = MBB->begin(); for (unsigned i = 0, e = CSI.size(); i != e; ++i) { // Insert the spill to the stack frame. RegInfo->storeRegToStackSlot(*MBB, I, CSI[i].getReg(), CSI[i].getFrameIdx(), CSI[i].getRegClass()); } // Add code to restore the callee-save registers in each exiting block. const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo(); for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) // If last instruction is a return instruction, add an epilogue. if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) { MBB = FI; I = MBB->end(); --I; // Skip over all terminator instructions, which are part of the return // sequence. MachineBasicBlock::iterator I2 = I; while (I2 != MBB->begin() && TII.isTerminatorInstr((--I2)->getOpcode())) I = I2; bool AtStart = I == MBB->begin(); MachineBasicBlock::iterator BeforeI = I; if (!AtStart) --BeforeI; // Restore all registers immediately before the return and any terminators // that preceed it. for (unsigned i = 0, e = CSI.size(); i != e; ++i) { RegInfo->loadRegFromStackSlot(*MBB, I, CSI[i].getReg(), CSI[i].getFrameIdx(), CSI[i].getRegClass()); assert(I != MBB->begin() && "loadRegFromStackSlot didn't insert any code!"); // Insert in reverse order. loadRegFromStackSlot can insert multiple // instructions. if (AtStart) I = MBB->begin(); else { I = BeforeI; ++I; } } } } /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the /// abstract stack objects. /// void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) { const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo(); bool StackGrowsDown = TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown; // Loop over all of the stack objects, assigning sequential addresses... MachineFrameInfo *FFI = Fn.getFrameInfo(); unsigned StackAlignment = TFI.getStackAlignment(); unsigned MaxAlign = 0; // Start at the beginning of the local area. // The Offset is the distance from the stack top in the direction // of stack growth -- so it's always positive. int Offset = TFI.getOffsetOfLocalArea(); if (StackGrowsDown) Offset = -Offset; assert(Offset >= 0 && "Local area offset should be in direction of stack growth"); // If there are fixed sized objects that are preallocated in the local area, // non-fixed objects can't be allocated right at the start of local area. // We currently don't support filling in holes in between fixed sized objects, // so we adjust 'Offset' to point to the end of last fixed sized // preallocated object. for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) { int FixedOff; if (StackGrowsDown) { // The maximum distance from the stack pointer is at lower address of // the object -- which is given by offset. For down growing stack // the offset is negative, so we negate the offset to get the distance. FixedOff = -FFI->getObjectOffset(i); } else { // The maximum distance from the start pointer is at the upper // address of the object. FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i); } if (FixedOff > Offset) Offset = FixedOff; } for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) { // If stack grows down, we need to add size of find the lowest // address of the object. if (StackGrowsDown) Offset += FFI->getObjectSize(i); unsigned Align = FFI->getObjectAlignment(i); // If the alignment of this object is greater than that of the stack, then // increase the stack alignment to match. MaxAlign = std::max(MaxAlign, Align); // Adjust to alignment boundary Offset = (Offset+Align-1)/Align*Align; if (StackGrowsDown) { FFI->setObjectOffset(i, -Offset); // Set the computed offset } else { FFI->setObjectOffset(i, Offset); Offset += FFI->getObjectSize(i); } } // Align the final stack pointer offset, but only if there are calls in the // function. This ensures that any calls to subroutines have their stack // frames suitable aligned. if (FFI->hasCalls()) Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment; // Set the final value of the stack pointer... FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea()); // Remember the required stack alignment in case targets need it to perform // dynamic stack alignment. assert(FFI->getMaxAlignment() == MaxAlign && "Stack alignment calculation broken!"); } /// insertPrologEpilogCode - Scan the function for modified caller saved /// registers, insert spill code for these caller saved registers, then add /// prolog and epilog code to the function. /// void PEI::insertPrologEpilogCode(MachineFunction &Fn) { // Add prologue to the function... Fn.getTarget().getRegisterInfo()->emitPrologue(Fn); // Add epilogue to restore the callee-save registers in each exiting block const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo(); for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) { // If last instruction is a return instruction, add an epilogue if (!I->empty() && TII.isReturn(I->back().getOpcode())) Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I); } } /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical /// register references and actual offsets. /// void PEI::replaceFrameIndices(MachineFunction &Fn) { if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do? const TargetMachine &TM = Fn.getTarget(); assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!"); const MRegisterInfo &MRI = *TM.getRegisterInfo(); for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) if (I->getOperand(i).isFrameIndex()) { // If this instruction has a FrameIndex operand, we need to use that // target machine register info object to eliminate it. MRI.eliminateFrameIndex(I); break; } } <commit_msg>PEI now place callee save spills closest to the address pointed to by the incoming stack. This allows X86 backend to use push / pop in epilogue / prologue.<commit_after>//===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass is responsible for finalizing the functions frame layout, saving // callee saved registers, and for emitting prolog & epilog code for the // function. // // This pass must be run after register allocation. After this pass is // executed, it is illegal to construct MO_FrameIndex operands. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/MRegisterInfo.h" #include "llvm/Target/TargetFrameInfo.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Support/Compiler.h" #include <climits> using namespace llvm; namespace { struct VISIBILITY_HIDDEN PEI : public MachineFunctionPass { const char *getPassName() const { return "Prolog/Epilog Insertion & Frame Finalization"; } /// runOnMachineFunction - Insert prolog/epilog code and replace abstract /// frame indexes with appropriate references. /// bool runOnMachineFunction(MachineFunction &Fn) { // Get MachineDebugInfo so that we can track the construction of the // frame. if (MachineDebugInfo *DI = getAnalysisToUpdate<MachineDebugInfo>()) { Fn.getFrameInfo()->setMachineDebugInfo(DI); } // Allow the target machine to make some adjustments to the function // e.g. UsedPhysRegs before calculateCalleeSavedRegisters. Fn.getTarget().getRegisterInfo()->processFunctionBeforeCalleeSaveScan(Fn); // Scan the function for modified callee saved registers and insert spill // code for any callee saved registers that are modified. Also calculate // the MaxCallFrameSize and HasCalls variables for the function's frame // information and eliminates call frame pseudo instructions. calculateCalleeSavedRegisters(Fn); // Add the code to save and restore the callee saved registers saveCalleeSavedRegisters(Fn); // Allow the target machine to make final modifications to the function // before the frame layout is finalized. Fn.getTarget().getRegisterInfo()->processFunctionBeforeFrameFinalized(Fn); // Calculate actual frame offsets for all of the abstract stack objects... calculateFrameObjectOffsets(Fn); // Add prolog and epilog code to the function. This function is required // to align the stack frame as necessary for any stack variables or // called functions. Because of this, calculateCalleeSavedRegisters // must be called before this function in order to set the HasCalls // and MaxCallFrameSize variables. insertPrologEpilogCode(Fn); // Replace all MO_FrameIndex operands with physical register references // and actual offsets. // replaceFrameIndices(Fn); return true; } private: // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee save // stack frame indexes. unsigned MinCSFrameIndex, MaxCSFrameIndex; void calculateCalleeSavedRegisters(MachineFunction &Fn); void saveCalleeSavedRegisters(MachineFunction &Fn); void calculateFrameObjectOffsets(MachineFunction &Fn); void replaceFrameIndices(MachineFunction &Fn); void insertPrologEpilogCode(MachineFunction &Fn); }; } /// createPrologEpilogCodeInserter - This function returns a pass that inserts /// prolog and epilog code, and eliminates abstract frame references. /// FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); } /// calculateCalleeSavedRegisters - Scan the function for modified callee saved /// registers. Also calculate the MaxCallFrameSize and HasCalls variables for /// the function's frame information and eliminates call frame pseudo /// instructions. /// void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) { const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo(); const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo(); // Get the callee saved register list... const unsigned *CSRegs = RegInfo->getCalleeSaveRegs(); // Get the function call frame set-up and tear-down instruction opcode int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode(); int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode(); // Early exit for targets which have no callee saved registers and no call // frame setup/destroy pseudo instructions. if ((CSRegs == 0 || CSRegs[0] == 0) && FrameSetupOpcode == -1 && FrameDestroyOpcode == -1) return; unsigned MaxCallFrameSize = 0; bool HasCalls = false; for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) if (I->getOpcode() == FrameSetupOpcode || I->getOpcode() == FrameDestroyOpcode) { assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo" " instructions should have a single immediate argument!"); unsigned Size = I->getOperand(0).getImmedValue(); if (Size > MaxCallFrameSize) MaxCallFrameSize = Size; HasCalls = true; RegInfo->eliminateCallFramePseudoInstr(Fn, *BB, I++); } else { ++I; } MachineFrameInfo *FFI = Fn.getFrameInfo(); FFI->setHasCalls(HasCalls); FFI->setMaxCallFrameSize(MaxCallFrameSize); // Now figure out which *callee saved* registers are modified by the current // function, thus needing to be saved and restored in the prolog/epilog. // const bool *PhysRegsUsed = Fn.getUsedPhysregs(); const TargetRegisterClass* const *CSRegClasses = RegInfo->getCalleeSaveRegClasses(); std::vector<CalleeSavedInfo> CSI; for (unsigned i = 0; CSRegs[i]; ++i) { unsigned Reg = CSRegs[i]; if (PhysRegsUsed[Reg]) { // If the reg is modified, save it! CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i])); } else { for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg); *AliasSet; ++AliasSet) { // Check alias registers too. if (PhysRegsUsed[*AliasSet]) { CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i])); break; } } } } if (CSI.empty()) return; // Early exit if no callee saved registers are modified! unsigned NumFixedSpillSlots; const std::pair<unsigned,int> *FixedSpillSlots = TFI->getCalleeSaveSpillSlots(NumFixedSpillSlots); // Now that we know which registers need to be saved and restored, allocate // stack slots for them. MinCSFrameIndex = INT_MAX; MaxCSFrameIndex = 0; for (unsigned i = 0, e = CSI.size(); i != e; ++i) { unsigned Reg = CSI[i].getReg(); const TargetRegisterClass *RC = CSI[i].getRegClass(); // Check to see if this physreg must be spilled to a particular stack slot // on this target. const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots; while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots && FixedSlot->first != Reg) ++FixedSlot; int FrameIdx; if (FixedSlot == FixedSpillSlots+NumFixedSpillSlots) { // Nope, just spill it anywhere convenient. FrameIdx = FFI->CreateStackObject(RC->getSize(), RC->getAlignment()); if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx; if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx; } else { // Spill it to the stack where we must. FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second); } CSI[i].setFrameIdx(FrameIdx); } FFI->setCalleeSavedInfo(CSI); } /// saveCalleeSavedRegisters - Insert spill code for any callee saved registers /// that are modified in the function. /// void PEI::saveCalleeSavedRegisters(MachineFunction &Fn) { // Get callee saved register information. MachineFrameInfo *FFI = Fn.getFrameInfo(); const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo(); // Early exit if no callee saved registers are modified! if (CSI.empty()) return; const MRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo(); // Now that we have a stack slot for each register to be saved, insert spill // code into the entry block. MachineBasicBlock *MBB = Fn.begin(); MachineBasicBlock::iterator I = MBB->begin(); for (unsigned i = 0, e = CSI.size(); i != e; ++i) { // Insert the spill to the stack frame. RegInfo->storeRegToStackSlot(*MBB, I, CSI[i].getReg(), CSI[i].getFrameIdx(), CSI[i].getRegClass()); } // Add code to restore the callee-save registers in each exiting block. const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo(); for (MachineFunction::iterator FI = Fn.begin(), E = Fn.end(); FI != E; ++FI) // If last instruction is a return instruction, add an epilogue. if (!FI->empty() && TII.isReturn(FI->back().getOpcode())) { MBB = FI; I = MBB->end(); --I; // Skip over all terminator instructions, which are part of the return // sequence. MachineBasicBlock::iterator I2 = I; while (I2 != MBB->begin() && TII.isTerminatorInstr((--I2)->getOpcode())) I = I2; bool AtStart = I == MBB->begin(); MachineBasicBlock::iterator BeforeI = I; if (!AtStart) --BeforeI; // Restore all registers immediately before the return and any terminators // that preceed it. for (unsigned i = 0, e = CSI.size(); i != e; ++i) { RegInfo->loadRegFromStackSlot(*MBB, I, CSI[i].getReg(), CSI[i].getFrameIdx(), CSI[i].getRegClass()); assert(I != MBB->begin() && "loadRegFromStackSlot didn't insert any code!"); // Insert in reverse order. loadRegFromStackSlot can insert multiple // instructions. if (AtStart) I = MBB->begin(); else { I = BeforeI; ++I; } } } } /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the /// abstract stack objects. /// void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) { const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo(); bool StackGrowsDown = TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown; // Loop over all of the stack objects, assigning sequential addresses... MachineFrameInfo *FFI = Fn.getFrameInfo(); unsigned StackAlignment = TFI.getStackAlignment(); unsigned MaxAlign = 0; // Start at the beginning of the local area. // The Offset is the distance from the stack top in the direction // of stack growth -- so it's always positive. int Offset = TFI.getOffsetOfLocalArea(); if (StackGrowsDown) Offset = -Offset; assert(Offset >= 0 && "Local area offset should be in direction of stack growth"); // If there are fixed sized objects that are preallocated in the local area, // non-fixed objects can't be allocated right at the start of local area. // We currently don't support filling in holes in between fixed sized objects, // so we adjust 'Offset' to point to the end of last fixed sized // preallocated object. for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) { int FixedOff; if (StackGrowsDown) { // The maximum distance from the stack pointer is at lower address of // the object -- which is given by offset. For down growing stack // the offset is negative, so we negate the offset to get the distance. FixedOff = -FFI->getObjectOffset(i); } else { // The maximum distance from the start pointer is at the upper // address of the object. FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i); } if (FixedOff > Offset) Offset = FixedOff; } // First assign frame offsets to stack objects that are used to spill // callee save registers. if (StackGrowsDown) { for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) { if (i < MinCSFrameIndex || i > MaxCSFrameIndex) continue; // If stack grows down, we need to add size of find the lowest // address of the object. Offset += FFI->getObjectSize(i); unsigned Align = FFI->getObjectAlignment(i); // If the alignment of this object is greater than that of the stack, then // increase the stack alignment to match. MaxAlign = std::max(MaxAlign, Align); // Adjust to alignment boundary Offset = (Offset+Align-1)/Align*Align; FFI->setObjectOffset(i, -Offset); // Set the computed offset } } else { for (int i = FFI->getObjectIndexEnd()-1; i >= 0; --i) { if ((unsigned)i < MinCSFrameIndex || (unsigned)i > MaxCSFrameIndex) continue; unsigned Align = FFI->getObjectAlignment(i); // If the alignment of this object is greater than that of the stack, then // increase the stack alignment to match. MaxAlign = std::max(MaxAlign, Align); // Adjust to alignment boundary Offset = (Offset+Align-1)/Align*Align; FFI->setObjectOffset(i, Offset); Offset += FFI->getObjectSize(i); } } // Then assign frame offsets to stack objects that are not used to spill // callee save registers. for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) { if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) continue; // If stack grows down, we need to add size of find the lowest // address of the object. if (StackGrowsDown) Offset += FFI->getObjectSize(i); unsigned Align = FFI->getObjectAlignment(i); // If the alignment of this object is greater than that of the stack, then // increase the stack alignment to match. MaxAlign = std::max(MaxAlign, Align); // Adjust to alignment boundary Offset = (Offset+Align-1)/Align*Align; if (StackGrowsDown) { FFI->setObjectOffset(i, -Offset); // Set the computed offset } else { FFI->setObjectOffset(i, Offset); Offset += FFI->getObjectSize(i); } } // Align the final stack pointer offset, but only if there are calls in the // function. This ensures that any calls to subroutines have their stack // frames suitable aligned. if (FFI->hasCalls()) Offset = (Offset+StackAlignment-1)/StackAlignment*StackAlignment; // Set the final value of the stack pointer... FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea()); // Remember the required stack alignment in case targets need it to perform // dynamic stack alignment. assert(FFI->getMaxAlignment() == MaxAlign && "Stack alignment calculation broken!"); } /// insertPrologEpilogCode - Scan the function for modified callee saved /// registers, insert spill code for these callee saved registers, then add /// prolog and epilog code to the function. /// void PEI::insertPrologEpilogCode(MachineFunction &Fn) { // Add prologue to the function... Fn.getTarget().getRegisterInfo()->emitPrologue(Fn); // Add epilogue to restore the callee-save registers in each exiting block const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo(); for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) { // If last instruction is a return instruction, add an epilogue if (!I->empty() && TII.isReturn(I->back().getOpcode())) Fn.getTarget().getRegisterInfo()->emitEpilogue(Fn, *I); } } /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical /// register references and actual offsets. /// void PEI::replaceFrameIndices(MachineFunction &Fn) { if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do? const TargetMachine &TM = Fn.getTarget(); assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!"); const MRegisterInfo &MRI = *TM.getRegisterInfo(); for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) if (I->getOperand(i).isFrameIndex()) { // If this instruction has a FrameIndex operand, we need to use that // target machine register info object to eliminate it. MRI.eliminateFrameIndex(I); break; } } <|endoftext|>
<commit_before>//===--- LSLocationPrinter.cpp - Dump all memory locations in program -----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This pass tests type expansion, memlocation expansion and memlocation // reduction. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-memlocation-dumper" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/SIL/Projection.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILValue.h" #include "swift/SIL/SILValueProjection.h" #include "swift/SILOptimizer/Analysis/Analysis.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" using namespace swift; //===----------------------------------------------------------------------===// // Top Level Driver //===----------------------------------------------------------------------===// namespace { enum class MLKind : unsigned { OnlyExpansion = 0, OnlyReduction = 1, OnlyTypeExpansion = 2, All = 3, }; } // end anonymous namespace static llvm::cl::opt<MLKind> LSLocationKinds( "ml", llvm::cl::desc("LSLocation Kinds:"), llvm::cl::init(MLKind::All), llvm::cl::values( clEnumValN(MLKind::OnlyExpansion, "only-expansion", "only-expansion"), clEnumValN(MLKind::OnlyReduction, "only-reduction", "only-reduction"), clEnumValN(MLKind::OnlyTypeExpansion, "only-type-expansion", "only-type-expansion"), clEnumValN(MLKind::All, "all", "all"), clEnumValEnd)); static llvm::cl::opt<bool> UseNewProjection("lslocation-dump-use-new-projection", llvm::cl::init(false)); namespace { class LSLocationPrinter : public SILModuleTransform { /// Type expansion analysis. TypeExpansionAnalysis *TE; public: /// Dumps the expansions of SILType accessed in the function. /// This tests the expandTypeIntoLeafProjectionPaths function, which is /// a function used extensively in expand and reduce functions. /// /// We test it to catch any suspicious things in the earliest point. /// void printTypeExpansion(SILFunction &Fn) { SILModule *M = &Fn.getModule(); ProjectionPathList PPList; unsigned Counter = 0; for (auto &BB : Fn) { for (auto &II : BB) { if (auto *LI = dyn_cast<LoadInst>(&II)) { SILValue V = LI->getOperand(); // This is an address type, take it object type. SILType Ty = V->getType().getObjectType(); ProjectionPath::expandTypeIntoLeafProjectionPaths(Ty, M, PPList); } else if (auto *SI = dyn_cast<StoreInst>(&II)) { SILValue V = SI->getDest(); // This is an address type, take it object type. SILType Ty = V->getType().getObjectType(); ProjectionPath::expandTypeIntoLeafProjectionPaths(Ty, M, PPList); } else { // Not interested in these instructions yet. continue; } llvm::outs() << "#" << Counter++ << II; for (auto &T : PPList) { llvm::outs() << T.getValue(); } PPList.clear(); } } llvm::outs() << "\n"; } void printTypeExpansionWithNewProjection(SILFunction &Fn) { SILModule *M = &Fn.getModule(); llvm::SmallVector<Optional<NewProjectionPath>, 8> PPList; unsigned Counter = 0; for (auto &BB : Fn) { for (auto &II : BB) { SILValue V; SILType Ty; if (auto *LI = dyn_cast<LoadInst>(&II)) { V = LI->getOperand(); // This is an address type, take it object type. Ty = V->getType().getObjectType(); NewProjectionPath::expandTypeIntoLeafProjectionPaths(Ty, M, PPList); } else if (auto *SI = dyn_cast<StoreInst>(&II)) { V = SI->getDest(); // This is an address type, take it object type. Ty = V->getType().getObjectType(); NewProjectionPath::expandTypeIntoLeafProjectionPaths(Ty, M, PPList); } else { // Not interested in these instructions yet. continue; } llvm::outs() << "#" << Counter++ << II; for (auto &T : PPList) { T.getValue().print(llvm::outs(), *M); } PPList.clear(); } } llvm::outs() << "\n"; } /// Dumps the expansions of memory locations accessed in the function. /// This tests the expand function in LSLocation class. /// /// We test it to catch any suspicious things when memory location is /// expanded, i.e. base is traced back and aggregate is expanded /// properly. void printMemExpansion(SILFunction &Fn) { LSLocation L; LSLocationList Locs; unsigned Counter = 0; for (auto &BB : Fn) { for (auto &II : BB) { if (auto *LI = dyn_cast<LoadInst>(&II)) { SILValue Mem = LI->getOperand(); SILValue UO = getUnderlyingObject(Mem); L.init(UO, NewProjectionPath::getProjectionPath(UO, Mem)); if (!L.isValid()) continue; LSLocation::expand(L, &Fn.getModule(), Locs, TE); } else if (auto *SI = dyn_cast<StoreInst>(&II)) { SILValue Mem = SI->getDest(); SILValue UO = getUnderlyingObject(Mem); L.init(UO, NewProjectionPath::getProjectionPath(UO, Mem)); if (!L.isValid()) continue; LSLocation::expand(L, &Fn.getModule(), Locs, TE); } else { // Not interested in these instructions yet. continue; } llvm::outs() << "#" << Counter++ << II; for (auto &Loc : Locs) { Loc.print(&Fn.getModule()); } Locs.clear(); } } llvm::outs() << "\n"; } /// Dumps the reductions of set of memory locations. /// /// This function first calls expand on a memory location. It then calls /// reduce, in hope to get the original memory location back. /// void printMemReduction(SILFunction &Fn) { LSLocation L; LSLocationList Locs; llvm::DenseSet<LSLocation> SLocs; unsigned Counter = 0; for (auto &BB : Fn) { for (auto &II : BB) { // Expand it first. // if (auto *LI = dyn_cast<LoadInst>(&II)) { SILValue Mem = LI->getOperand(); SILValue UO = getUnderlyingObject(Mem); L.init(UO, NewProjectionPath::getProjectionPath(UO, Mem)); if (!L.isValid()) continue; LSLocation::expand(L, &Fn.getModule(), Locs, TE); } else if (auto *SI = dyn_cast<StoreInst>(&II)) { SILValue Mem = SI->getDest(); SILValue UO = getUnderlyingObject(Mem); L.init(UO, NewProjectionPath::getProjectionPath(UO, Mem)); if (!L.isValid()) continue; LSLocation::expand(L, &Fn.getModule(), Locs, TE); } else { // Not interested in these instructions yet. continue; } // Try to reduce it. // // Reduction should not care about the order of the memory locations in // the set. for (auto I = Locs.begin(); I != Locs.end(); ++I) { SLocs.insert(*I); } // This should get the original (unexpanded) location back. LSLocation::reduce(L, &Fn.getModule(), SLocs, TE); llvm::outs() << "#" << Counter++ << II; for (auto &Loc : SLocs) { Loc.print(&Fn.getModule()); } L.reset(); Locs.clear(); SLocs.clear(); } } llvm::outs() << "\n"; } void run() override { for (auto &Fn : *getModule()) { if (Fn.isExternalDeclaration()) continue; // Initialize the type expansion analysis. TE = PM->getAnalysis<TypeExpansionAnalysis>(); llvm::outs() << "@" << Fn.getName() << "\n"; switch (LSLocationKinds) { case MLKind::OnlyTypeExpansion: printTypeExpansionWithNewProjection(Fn); break; case MLKind::OnlyExpansion: printMemExpansion(Fn); break; case MLKind::OnlyReduction: printMemReduction(Fn); break; default: break; } } } StringRef getName() override { return "Mem Location Dumper"; } }; } // end anonymous namespace SILTransform *swift::createLSLocationPrinter() { return new LSLocationPrinter(); } <commit_msg>Migrate LSLocation printer pass to new projection. This should be NFC<commit_after>//===--- LSLocationPrinter.cpp - Dump all memory locations in program -----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This pass tests type expansion, memlocation expansion and memlocation // reduction. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-memlocation-dumper" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/SIL/Projection.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILValue.h" #include "swift/SIL/SILValueProjection.h" #include "swift/SILOptimizer/Analysis/Analysis.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" using namespace swift; //===----------------------------------------------------------------------===// // Top Level Driver //===----------------------------------------------------------------------===// namespace { enum class MLKind : unsigned { OnlyExpansion = 0, OnlyReduction = 1, OnlyTypeExpansion = 2, All = 3, }; } // end anonymous namespace static llvm::cl::opt<MLKind> LSLocationKinds( "ml", llvm::cl::desc("LSLocation Kinds:"), llvm::cl::init(MLKind::All), llvm::cl::values( clEnumValN(MLKind::OnlyExpansion, "only-expansion", "only-expansion"), clEnumValN(MLKind::OnlyReduction, "only-reduction", "only-reduction"), clEnumValN(MLKind::OnlyTypeExpansion, "only-type-expansion", "only-type-expansion"), clEnumValN(MLKind::All, "all", "all"), clEnumValEnd)); static llvm::cl::opt<bool> UseNewProjection("lslocation-dump-use-new-projection", llvm::cl::init(false)); namespace { class LSLocationPrinter : public SILModuleTransform { /// Type expansion analysis. TypeExpansionAnalysis *TE; public: /// Dumps the expansions of SILType accessed in the function. /// This tests the expandTypeIntoLeafProjectionPaths function, which is /// a function used extensively in expand and reduce functions. /// /// We test it to catch any suspicious things in the earliest point. /// void printTypeExpansion(SILFunction &Fn) { SILModule *M = &Fn.getModule(); NewProjectionPathList PPList; unsigned Counter = 0; for (auto &BB : Fn) { for (auto &II : BB) { if (auto *LI = dyn_cast<LoadInst>(&II)) { SILValue V = LI->getOperand(); // This is an address type, take it object type. SILType Ty = V->getType().getObjectType(); NewProjectionPath::expandTypeIntoLeafProjectionPaths(Ty, M, PPList); } else if (auto *SI = dyn_cast<StoreInst>(&II)) { SILValue V = SI->getDest(); // This is an address type, take it object type. SILType Ty = V->getType().getObjectType(); NewProjectionPath::expandTypeIntoLeafProjectionPaths(Ty, M, PPList); } else { // Not interested in these instructions yet. continue; } llvm::outs() << "#" << Counter++ << II; for (auto &T : PPList) { T.getValue().print(llvm::outs(), *M); } PPList.clear(); } } llvm::outs() << "\n"; } void printTypeExpansionWithNewProjection(SILFunction &Fn) { SILModule *M = &Fn.getModule(); llvm::SmallVector<Optional<NewProjectionPath>, 8> PPList; unsigned Counter = 0; for (auto &BB : Fn) { for (auto &II : BB) { SILValue V; SILType Ty; if (auto *LI = dyn_cast<LoadInst>(&II)) { V = LI->getOperand(); // This is an address type, take it object type. Ty = V->getType().getObjectType(); NewProjectionPath::expandTypeIntoLeafProjectionPaths(Ty, M, PPList); } else if (auto *SI = dyn_cast<StoreInst>(&II)) { V = SI->getDest(); // This is an address type, take it object type. Ty = V->getType().getObjectType(); NewProjectionPath::expandTypeIntoLeafProjectionPaths(Ty, M, PPList); } else { // Not interested in these instructions yet. continue; } llvm::outs() << "#" << Counter++ << II; for (auto &T : PPList) { T.getValue().print(llvm::outs(), *M); } PPList.clear(); } } llvm::outs() << "\n"; } /// Dumps the expansions of memory locations accessed in the function. /// This tests the expand function in LSLocation class. /// /// We test it to catch any suspicious things when memory location is /// expanded, i.e. base is traced back and aggregate is expanded /// properly. void printMemExpansion(SILFunction &Fn) { LSLocation L; LSLocationList Locs; unsigned Counter = 0; for (auto &BB : Fn) { for (auto &II : BB) { if (auto *LI = dyn_cast<LoadInst>(&II)) { SILValue Mem = LI->getOperand(); SILValue UO = getUnderlyingObject(Mem); L.init(UO, NewProjectionPath::getProjectionPath(UO, Mem)); if (!L.isValid()) continue; LSLocation::expand(L, &Fn.getModule(), Locs, TE); } else if (auto *SI = dyn_cast<StoreInst>(&II)) { SILValue Mem = SI->getDest(); SILValue UO = getUnderlyingObject(Mem); L.init(UO, NewProjectionPath::getProjectionPath(UO, Mem)); if (!L.isValid()) continue; LSLocation::expand(L, &Fn.getModule(), Locs, TE); } else { // Not interested in these instructions yet. continue; } llvm::outs() << "#" << Counter++ << II; for (auto &Loc : Locs) { Loc.print(&Fn.getModule()); } Locs.clear(); } } llvm::outs() << "\n"; } /// Dumps the reductions of set of memory locations. /// /// This function first calls expand on a memory location. It then calls /// reduce, in hope to get the original memory location back. /// void printMemReduction(SILFunction &Fn) { LSLocation L; LSLocationList Locs; llvm::DenseSet<LSLocation> SLocs; unsigned Counter = 0; for (auto &BB : Fn) { for (auto &II : BB) { // Expand it first. // if (auto *LI = dyn_cast<LoadInst>(&II)) { SILValue Mem = LI->getOperand(); SILValue UO = getUnderlyingObject(Mem); L.init(UO, NewProjectionPath::getProjectionPath(UO, Mem)); if (!L.isValid()) continue; LSLocation::expand(L, &Fn.getModule(), Locs, TE); } else if (auto *SI = dyn_cast<StoreInst>(&II)) { SILValue Mem = SI->getDest(); SILValue UO = getUnderlyingObject(Mem); L.init(UO, NewProjectionPath::getProjectionPath(UO, Mem)); if (!L.isValid()) continue; LSLocation::expand(L, &Fn.getModule(), Locs, TE); } else { // Not interested in these instructions yet. continue; } // Try to reduce it. // // Reduction should not care about the order of the memory locations in // the set. for (auto I = Locs.begin(); I != Locs.end(); ++I) { SLocs.insert(*I); } // This should get the original (unexpanded) location back. LSLocation::reduce(L, &Fn.getModule(), SLocs, TE); llvm::outs() << "#" << Counter++ << II; for (auto &Loc : SLocs) { Loc.print(&Fn.getModule()); } L.reset(); Locs.clear(); SLocs.clear(); } } llvm::outs() << "\n"; } void run() override { for (auto &Fn : *getModule()) { if (Fn.isExternalDeclaration()) continue; // Initialize the type expansion analysis. TE = PM->getAnalysis<TypeExpansionAnalysis>(); llvm::outs() << "@" << Fn.getName() << "\n"; switch (LSLocationKinds) { case MLKind::OnlyTypeExpansion: printTypeExpansionWithNewProjection(Fn); break; case MLKind::OnlyExpansion: printMemExpansion(Fn); break; case MLKind::OnlyReduction: printMemReduction(Fn); break; default: break; } } } StringRef getName() override { return "Mem Location Dumper"; } }; } // end anonymous namespace SILTransform *swift::createLSLocationPrinter() { return new LSLocationPrinter(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 "QUECTEL_BG96.h" #include "QUECTEL_BG96_CellularNetwork.h" #include "QUECTEL_BG96_CellularStack.h" #include "QUECTEL_BG96_CellularInformation.h" #include "QUECTEL_BG96_CellularContext.h" #include "CellularLog.h" using namespace mbed; using namespace events; #define CONNECT_DELIM "\r\n" #define CONNECT_BUFFER_SIZE (1280 + 80 + 80) // AT response + sscanf format #define CONNECT_TIMEOUT 8000 #define DEVICE_READY_URC "CPIN:" static const intptr_t cellular_properties[AT_CellularBase::PROPERTY_MAX] = { AT_CellularNetwork::RegistrationModeLAC, // C_EREG AT_CellularNetwork::RegistrationModeLAC, // C_GREG AT_CellularNetwork::RegistrationModeLAC, // C_REG 0, // AT_CGSN_WITH_TYPE 0, // AT_CGDATA 1, // AT_CGAUTH 1, // AT_CNMI 1, // AT_CSMP 1, // AT_CMGF 1, // AT_CSDH 1, // PROPERTY_IPV4_STACK 0, // PROPERTY_IPV6_STACK 0, // PROPERTY_IPV4V6_STACK 1, // PROPERTY_NON_IP_PDP_TYPE 1, // PROPERTY_AT_CGEREP }; QUECTEL_BG96::QUECTEL_BG96(FileHandle *fh) : AT_CellularDevice(fh) { AT_CellularBase::set_cellular_properties(cellular_properties); } AT_CellularNetwork *QUECTEL_BG96::open_network_impl(ATHandler &at) { return new QUECTEL_BG96_CellularNetwork(at); } AT_CellularContext *QUECTEL_BG96::create_context_impl(ATHandler &at, const char *apn, bool cp_req, bool nonip_req) { return new QUECTEL_BG96_CellularContext(at, this, apn, cp_req, nonip_req); } AT_CellularInformation *QUECTEL_BG96::open_information_impl(ATHandler &at) { return new QUECTEL_BG96_CellularInformation(at); } void QUECTEL_BG96::set_ready_cb(Callback<void()> callback) { _at->set_urc_handler(DEVICE_READY_URC, callback); } #if MBED_CONF_QUECTEL_BG96_PROVIDE_DEFAULT #include "UARTSerial.h" CellularDevice *CellularDevice::get_default_instance() { static UARTSerial serial(MBED_CONF_QUECTEL_BG96_TX, MBED_CONF_QUECTEL_BG96_RX, MBED_CONF_QUECTEL_BG96_BAUDRATE); #if defined (MBED_CONF_QUECTEL_BG96_RTS) && defined(MBED_CONF_QUECTEL_BG96_CTS) tr_debug("QUECTEL_BG96 flow control: RTS %d CTS %d", MBED_CONF_QUECTEL_BG96_RTS, MBED_CONF_QUECTEL_BG96_CTS); serial.set_flow_control(SerialBase::RTSCTS, MBED_CONF_QUECTEL_BG96_RTS, MBED_CONF_QUECTEL_BG96_CTS); #endif static QUECTEL_BG96 device(&serial); return &device; } #endif <commit_msg>Cellular: Added IPV6 and IPV4V6 as supported properties for BG96<commit_after>/* * Copyright (c) 2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 "QUECTEL_BG96.h" #include "QUECTEL_BG96_CellularNetwork.h" #include "QUECTEL_BG96_CellularStack.h" #include "QUECTEL_BG96_CellularInformation.h" #include "QUECTEL_BG96_CellularContext.h" #include "CellularLog.h" using namespace mbed; using namespace events; #define CONNECT_DELIM "\r\n" #define CONNECT_BUFFER_SIZE (1280 + 80 + 80) // AT response + sscanf format #define CONNECT_TIMEOUT 8000 #define DEVICE_READY_URC "CPIN:" static const intptr_t cellular_properties[AT_CellularBase::PROPERTY_MAX] = { AT_CellularNetwork::RegistrationModeLAC, // C_EREG AT_CellularNetwork::RegistrationModeLAC, // C_GREG AT_CellularNetwork::RegistrationModeLAC, // C_REG 0, // AT_CGSN_WITH_TYPE 0, // AT_CGDATA 1, // AT_CGAUTH 1, // AT_CNMI 1, // AT_CSMP 1, // AT_CMGF 1, // AT_CSDH 1, // PROPERTY_IPV4_STACK 1, // PROPERTY_IPV6_STACK 1, // PROPERTY_IPV4V6_STACK 1, // PROPERTY_NON_IP_PDP_TYPE 1, // PROPERTY_AT_CGEREP }; QUECTEL_BG96::QUECTEL_BG96(FileHandle *fh) : AT_CellularDevice(fh) { AT_CellularBase::set_cellular_properties(cellular_properties); } AT_CellularNetwork *QUECTEL_BG96::open_network_impl(ATHandler &at) { return new QUECTEL_BG96_CellularNetwork(at); } AT_CellularContext *QUECTEL_BG96::create_context_impl(ATHandler &at, const char *apn, bool cp_req, bool nonip_req) { return new QUECTEL_BG96_CellularContext(at, this, apn, cp_req, nonip_req); } AT_CellularInformation *QUECTEL_BG96::open_information_impl(ATHandler &at) { return new QUECTEL_BG96_CellularInformation(at); } void QUECTEL_BG96::set_ready_cb(Callback<void()> callback) { _at->set_urc_handler(DEVICE_READY_URC, callback); } #if MBED_CONF_QUECTEL_BG96_PROVIDE_DEFAULT #include "UARTSerial.h" CellularDevice *CellularDevice::get_default_instance() { static UARTSerial serial(MBED_CONF_QUECTEL_BG96_TX, MBED_CONF_QUECTEL_BG96_RX, MBED_CONF_QUECTEL_BG96_BAUDRATE); #if defined (MBED_CONF_QUECTEL_BG96_RTS) && defined(MBED_CONF_QUECTEL_BG96_CTS) tr_debug("QUECTEL_BG96 flow control: RTS %d CTS %d", MBED_CONF_QUECTEL_BG96_RTS, MBED_CONF_QUECTEL_BG96_CTS); serial.set_flow_control(SerialBase::RTSCTS, MBED_CONF_QUECTEL_BG96_RTS, MBED_CONF_QUECTEL_BG96_CTS); #endif static QUECTEL_BG96 device(&serial); return &device; } #endif <|endoftext|>
<commit_before><commit_msg>#92803# Copy/Paste: Use Clipboard, not Selection!<commit_after><|endoftext|>
<commit_before>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifdef ENABLE_MPI # undef ENABLE_MPI #endif #define ENABLE_MPI 0 #ifdef ENABLE_PARMETIS # undef ENABLE_PARMETIS #endif #define ENABLE_PARMETIS 0 #include "config.h" #if !(HAVE_ALUGRID || HAVE_DUNE_ALUGRID) # error Missing ALUGrid! #endif #include <dune/grid/alugrid.hh> #include "generic.hh" using namespace Dune; int main(int /*argc*/, char** /*argv*/) { try { typedef GenericLinearellipticExample< ALUGrid< 3, 3, simplex, nonconforming >, GDT::ChooseSpaceBackend::fem, Stuff::LA::ChooseBackend::istl_sparse > ExampleType; auto logger_cfg = ExampleType::logger_options(); logger_cfg["info"] = "99"; logger_cfg["info_color"] = "blue"; Stuff::Common::Configuration battery_geometry; battery_geometry["lower_left"] = "[0 0 0]"; battery_geometry["upper_right"] = "[0.0184 0.008 0.008]"; battery_geometry["num_elements"] = "[46 20 20]"; battery_geometry["separator"] = "[0.0084 0.01; 0 0.008; 0 0.008]"; battery_geometry["filename"] = "geometry__46x20x20_h4e-6m"; auto grid_cfg = ExampleType::grid_options("grid.multiscale.provider.cube"); grid_cfg.add(battery_geometry, "", true); Stuff::Common::Configuration boundary_cfg; boundary_cfg["type"] = "stuff.grid.boundaryinfo.normalbased"; boundary_cfg["default"] = "neumann"; boundary_cfg["dirichlet.0"] = "[-1 0 0]"; boundary_cfg["dirichlet.1"] = "[1 0 0]"; auto problem_cfg = ExampleType::problem_options("hdd.linearelliptic.problem.battery"); problem_cfg.add(battery_geometry, "diffusion_factor", true); problem_cfg["dirichlet.expression"] = "0"; problem_cfg["neumann.expression"] = "0"; problem_cfg["force.value"] = "1000"; auto solver_options = ExampleType::solver_options("bicgstab.amg.ilu0"); ExampleType example(logger_cfg, grid_cfg, boundary_cfg, problem_cfg); auto& disc = example.discretization(); auto U = disc.create_vector(); disc.solve(solver_options, U, Pymor::Parameter("ELECTROLYTE", 1.)); disc.visualize(U, "solution", "solution"); // if we came that far we can as well be happy about it return EXIT_SUCCESS; } catch (Dune::Exception& e) { std::cerr << "\n" << e.what() << std::endl; } catch (std::exception& e) { std::cerr << "\n" << e.what() << std::endl; } catch (...) { std::cerr << "Unknown exception thrown!" << std::endl; } // try return EXIT_FAILURE; } // ... main(...) <commit_msg>[examples...generic] add finalizing output (for timings)<commit_after>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifdef ENABLE_MPI # undef ENABLE_MPI #endif #define ENABLE_MPI 0 #ifdef ENABLE_PARMETIS # undef ENABLE_PARMETIS #endif #define ENABLE_PARMETIS 0 #include "config.h" #if !(HAVE_ALUGRID || HAVE_DUNE_ALUGRID) # error Missing ALUGrid! #endif #include <dune/grid/alugrid.hh> #include "generic.hh" using namespace Dune; int main(int /*argc*/, char** /*argv*/) { try { typedef GenericLinearellipticExample< ALUGrid< 3, 3, simplex, nonconforming >, GDT::ChooseSpaceBackend::fem, Stuff::LA::ChooseBackend::istl_sparse > ExampleType; auto logger_cfg = ExampleType::logger_options(); logger_cfg["info"] = "99"; logger_cfg["info_color"] = "blue"; Stuff::Common::Configuration battery_geometry; battery_geometry["lower_left"] = "[0 0 0]"; battery_geometry["upper_right"] = "[0.0184 0.008 0.008]"; battery_geometry["num_elements"] = "[46 20 20]"; battery_geometry["separator"] = "[0.0084 0.01; 0 0.008; 0 0.008]"; battery_geometry["filename"] = "geometry__46x20x20_h4e-6m"; auto grid_cfg = ExampleType::grid_options("grid.multiscale.provider.cube"); grid_cfg.add(battery_geometry, "", true); Stuff::Common::Configuration boundary_cfg; boundary_cfg["type"] = "stuff.grid.boundaryinfo.normalbased"; boundary_cfg["default"] = "neumann"; boundary_cfg["dirichlet.0"] = "[-1 0 0]"; boundary_cfg["dirichlet.1"] = "[1 0 0]"; auto problem_cfg = ExampleType::problem_options("hdd.linearelliptic.problem.battery"); problem_cfg.add(battery_geometry, "diffusion_factor", true); problem_cfg["dirichlet.expression"] = "0"; problem_cfg["neumann.expression"] = "0"; problem_cfg["force.value"] = "1000"; auto solver_options = ExampleType::solver_options("bicgstab.amg.ilu0"); ExampleType example(logger_cfg, grid_cfg, boundary_cfg, problem_cfg); auto& disc = example.discretization(); auto U = disc.create_vector(); disc.solve(solver_options, U, Pymor::Parameter("ELECTROLYTE", 0.6)); disc.visualize(U, "solution", "solution"); DSC::TimedLogger().get("main").info() << "finished!" << std::endl; // if we came that far we can as well be happy about it return EXIT_SUCCESS; } catch (Dune::Exception& e) { std::cerr << "\n" << e.what() << std::endl; } catch (std::exception& e) { std::cerr << "\n" << e.what() << std::endl; } catch (...) { std::cerr << "Unknown exception thrown!" << std::endl; } // try return EXIT_FAILURE; } // ... main(...) <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: convertsinglebytetobmpunicode.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-20 04:37:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "context.h" #include "converter.h" #include "convertsinglebytetobmpunicode.hxx" #include "unichars.h" #include "osl/diagnose.h" #include "rtl/textcvt.h" #include "sal/types.h" #include <cstddef> sal_Size rtl_textenc_convertSingleByteToBmpUnicode( ImplTextConverterData const * data, void *, sal_Char const * srcBuf, sal_Size srcBytes, sal_Unicode * destBuf, sal_Size destChars, sal_uInt32 flags, sal_uInt32 * info, sal_Size * srcCvtBytes) { sal_Unicode const * map = static_cast< rtl::textenc::BmpUnicodeToSingleByteConverterData const * >( data)->byteToUnicode; sal_uInt32 infoFlags = 0; sal_Size converted = 0; sal_Unicode * destBufPtr = destBuf; sal_Unicode * destBufEnd = destBuf + destChars; for (; converted < srcBytes; ++converted) { bool undefined = true; sal_Char b = *srcBuf++; sal_Unicode c = map[static_cast< sal_uInt8 >(b)]; if (c == 0xFFFF) { goto bad_input; } if (destBufEnd - destBufPtr < 1) { goto no_output; } *destBufPtr++ = c; continue; bad_input: switch (ImplHandleBadInputTextToUnicodeConversion( undefined, false, b, flags, &destBufPtr, destBufEnd, &infoFlags)) { case IMPL_BAD_INPUT_STOP: break; case IMPL_BAD_INPUT_CONTINUE: continue; case IMPL_BAD_INPUT_NO_OUTPUT: goto no_output; } break; no_output: --srcBuf; infoFlags |= RTL_TEXTTOUNICODE_INFO_DESTBUFFERTOSMALL; break; } if (info != 0) { *info = infoFlags; } if (srcCvtBytes != 0) { *srcCvtBytes = converted; } return destBufPtr - destBuf; } sal_Size rtl_textenc_convertBmpUnicodeToSingleByte( ImplTextConverterData const * data, void * context, sal_Unicode const * srcBuf, sal_Size srcChars, sal_Char * destBuf, sal_Size destBytes, sal_uInt32 flags, sal_uInt32 * info, sal_Size * srcCvtChars) { std::size_t entries = static_cast< rtl::textenc::BmpUnicodeToSingleByteConverterData const * >( data)->unicodeToByteEntries; rtl::textenc::BmpUnicodeToSingleByteRange const * ranges = static_cast< rtl::textenc::BmpUnicodeToSingleByteConverterData const * >( data)->unicodeToByte; sal_Unicode highSurrogate = 0; sal_uInt32 infoFlags = 0; sal_Size converted = 0; sal_Char * destBufPtr = destBuf; sal_Char * destBufEnd = destBuf + destBytes; if (context != 0) { highSurrogate = static_cast< ImplUnicodeToTextContext * >(context)-> m_nHighSurrogate; } for (; converted < srcChars; ++converted) { bool undefined = true; sal_uInt32 c = *srcBuf++; if (highSurrogate == 0) { if (ImplIsHighSurrogate(c)) { highSurrogate = static_cast< sal_Unicode >(c); continue; } } else if (ImplIsLowSurrogate(c)) { c = ImplCombineSurrogates(highSurrogate, c); } else { undefined = false; goto bad_input; } if (ImplIsLowSurrogate(c) || ImplIsNoncharacter(c)) { undefined = false; goto bad_input; } // Linearly searching through the ranges if probably fastest, assuming // that most converted characters belong to the ASCII subset: for (std::size_t i = 0; i < entries; ++i) { if (c < ranges[i].unicode) { break; } else if (c <= sal::static_int_cast< sal_uInt32 >( ranges[i].unicode + ranges[i].range)) { if (destBufEnd - destBufPtr < 1) { goto no_output; } *destBufPtr++ = static_cast< sal_Char >( ranges[i].byte + (c - ranges[i].unicode)); goto done; } } goto bad_input; done: highSurrogate = 0; continue; bad_input: switch (ImplHandleBadInputUnicodeToTextConversion( undefined, c, flags, &destBufPtr, destBufEnd, &infoFlags, 0, 0, 0)) { case IMPL_BAD_INPUT_STOP: highSurrogate = 0; break; case IMPL_BAD_INPUT_CONTINUE: highSurrogate = 0; continue; case IMPL_BAD_INPUT_NO_OUTPUT: goto no_output; } break; no_output: --srcBuf; infoFlags |= RTL_UNICODETOTEXT_INFO_DESTBUFFERTOSMALL; break; } if (highSurrogate != 0 && ((infoFlags & (RTL_UNICODETOTEXT_INFO_ERROR | RTL_UNICODETOTEXT_INFO_DESTBUFFERTOSMALL)) == 0)) { if ((flags & RTL_UNICODETOTEXT_FLAGS_FLUSH) != 0) { infoFlags |= RTL_UNICODETOTEXT_INFO_SRCBUFFERTOSMALL; } else { switch (ImplHandleBadInputUnicodeToTextConversion( false, 0, flags, &destBufPtr, destBufEnd, &infoFlags, 0, 0, 0)) { case IMPL_BAD_INPUT_STOP: case IMPL_BAD_INPUT_CONTINUE: highSurrogate = 0; break; case IMPL_BAD_INPUT_NO_OUTPUT: infoFlags |= RTL_UNICODETOTEXT_INFO_DESTBUFFERTOSMALL; break; } } } if (context != 0) { static_cast< ImplUnicodeToTextContext * >(context)->m_nHighSurrogate = highSurrogate; } if (info != 0) { *info = infoFlags; } if (srcCvtChars != 0) { *srcCvtChars = converted; } return destBufPtr - destBuf; } <commit_msg>INTEGRATION: CWS pchfix02 (1.4.30); FILE MERGED 2006/09/01 17:34:21 kaib 1.4.30.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: convertsinglebytetobmpunicode.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 09:08:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sal.hxx" #include "context.h" #include "converter.h" #include "convertsinglebytetobmpunicode.hxx" #include "unichars.h" #include "osl/diagnose.h" #include "rtl/textcvt.h" #include "sal/types.h" #include <cstddef> sal_Size rtl_textenc_convertSingleByteToBmpUnicode( ImplTextConverterData const * data, void *, sal_Char const * srcBuf, sal_Size srcBytes, sal_Unicode * destBuf, sal_Size destChars, sal_uInt32 flags, sal_uInt32 * info, sal_Size * srcCvtBytes) { sal_Unicode const * map = static_cast< rtl::textenc::BmpUnicodeToSingleByteConverterData const * >( data)->byteToUnicode; sal_uInt32 infoFlags = 0; sal_Size converted = 0; sal_Unicode * destBufPtr = destBuf; sal_Unicode * destBufEnd = destBuf + destChars; for (; converted < srcBytes; ++converted) { bool undefined = true; sal_Char b = *srcBuf++; sal_Unicode c = map[static_cast< sal_uInt8 >(b)]; if (c == 0xFFFF) { goto bad_input; } if (destBufEnd - destBufPtr < 1) { goto no_output; } *destBufPtr++ = c; continue; bad_input: switch (ImplHandleBadInputTextToUnicodeConversion( undefined, false, b, flags, &destBufPtr, destBufEnd, &infoFlags)) { case IMPL_BAD_INPUT_STOP: break; case IMPL_BAD_INPUT_CONTINUE: continue; case IMPL_BAD_INPUT_NO_OUTPUT: goto no_output; } break; no_output: --srcBuf; infoFlags |= RTL_TEXTTOUNICODE_INFO_DESTBUFFERTOSMALL; break; } if (info != 0) { *info = infoFlags; } if (srcCvtBytes != 0) { *srcCvtBytes = converted; } return destBufPtr - destBuf; } sal_Size rtl_textenc_convertBmpUnicodeToSingleByte( ImplTextConverterData const * data, void * context, sal_Unicode const * srcBuf, sal_Size srcChars, sal_Char * destBuf, sal_Size destBytes, sal_uInt32 flags, sal_uInt32 * info, sal_Size * srcCvtChars) { std::size_t entries = static_cast< rtl::textenc::BmpUnicodeToSingleByteConverterData const * >( data)->unicodeToByteEntries; rtl::textenc::BmpUnicodeToSingleByteRange const * ranges = static_cast< rtl::textenc::BmpUnicodeToSingleByteConverterData const * >( data)->unicodeToByte; sal_Unicode highSurrogate = 0; sal_uInt32 infoFlags = 0; sal_Size converted = 0; sal_Char * destBufPtr = destBuf; sal_Char * destBufEnd = destBuf + destBytes; if (context != 0) { highSurrogate = static_cast< ImplUnicodeToTextContext * >(context)-> m_nHighSurrogate; } for (; converted < srcChars; ++converted) { bool undefined = true; sal_uInt32 c = *srcBuf++; if (highSurrogate == 0) { if (ImplIsHighSurrogate(c)) { highSurrogate = static_cast< sal_Unicode >(c); continue; } } else if (ImplIsLowSurrogate(c)) { c = ImplCombineSurrogates(highSurrogate, c); } else { undefined = false; goto bad_input; } if (ImplIsLowSurrogate(c) || ImplIsNoncharacter(c)) { undefined = false; goto bad_input; } // Linearly searching through the ranges if probably fastest, assuming // that most converted characters belong to the ASCII subset: for (std::size_t i = 0; i < entries; ++i) { if (c < ranges[i].unicode) { break; } else if (c <= sal::static_int_cast< sal_uInt32 >( ranges[i].unicode + ranges[i].range)) { if (destBufEnd - destBufPtr < 1) { goto no_output; } *destBufPtr++ = static_cast< sal_Char >( ranges[i].byte + (c - ranges[i].unicode)); goto done; } } goto bad_input; done: highSurrogate = 0; continue; bad_input: switch (ImplHandleBadInputUnicodeToTextConversion( undefined, c, flags, &destBufPtr, destBufEnd, &infoFlags, 0, 0, 0)) { case IMPL_BAD_INPUT_STOP: highSurrogate = 0; break; case IMPL_BAD_INPUT_CONTINUE: highSurrogate = 0; continue; case IMPL_BAD_INPUT_NO_OUTPUT: goto no_output; } break; no_output: --srcBuf; infoFlags |= RTL_UNICODETOTEXT_INFO_DESTBUFFERTOSMALL; break; } if (highSurrogate != 0 && ((infoFlags & (RTL_UNICODETOTEXT_INFO_ERROR | RTL_UNICODETOTEXT_INFO_DESTBUFFERTOSMALL)) == 0)) { if ((flags & RTL_UNICODETOTEXT_FLAGS_FLUSH) != 0) { infoFlags |= RTL_UNICODETOTEXT_INFO_SRCBUFFERTOSMALL; } else { switch (ImplHandleBadInputUnicodeToTextConversion( false, 0, flags, &destBufPtr, destBufEnd, &infoFlags, 0, 0, 0)) { case IMPL_BAD_INPUT_STOP: case IMPL_BAD_INPUT_CONTINUE: highSurrogate = 0; break; case IMPL_BAD_INPUT_NO_OUTPUT: infoFlags |= RTL_UNICODETOTEXT_INFO_DESTBUFFERTOSMALL; break; } } } if (context != 0) { static_cast< ImplUnicodeToTextContext * >(context)->m_nHighSurrogate = highSurrogate; } if (info != 0) { *info = infoFlags; } if (srcCvtChars != 0) { *srcCvtChars = converted; } return destBufPtr - destBuf; } <|endoftext|>
<commit_before>/* This program will add histograms (see note) and Trees from a list of root files and write them to a target root file. The target file is newly created and must not be identical to one of the source files. Syntax: hadd targetfile source1 source2 ... or hadd -f targetfile source1 source2 ... (targetfile is overwritten if it exists) When -the -f option is specified, one can also specify the compression level of the target file. By default the compression level is 1, but if "-f0" is specified, the target file will not be compressed. if "-f6" is specified, the compression level 6 will be used. For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn f1 with h1 h2 h3 T1 f2 with h1 h4 T1 T2 f3 with h5 the result of hadd -f x.root f1.root f2.root f3.root will be a file x.root with h1 h2 h3 h4 h5 T1 T2 where h1 will be the sum of the 2 histograms in f1 and f2 T1 will be the merge of the Trees in f1 and f2 The files may contain sub-directories. if the source files contains histograms and Trees, one can skip the Trees with hadd -T targetfile source1 source2 ... Wildcarding and indirect files are also supported hadd result.root myfil*.root will merge all files in myfil*.root hadd result.root file1.root @list.txt file2. root myfil*.root will merge file1. root, file2. root, all files in myfil*.root and all files in the indirect text file list.txt ("@" as the first character of the file indicates an indirect file. An indirect file is a text file containing a list of other files, including other indirect files, one line per file). If the sources and and target compression levels are identical (default), the program uses the TChain::Merge function with option "fast", ie the merge will be done without unzipping or unstreaming the baskets (i.e. direct copy of the raw byte on disk). The "fast" mode is typically 5 times faster than the mode unzipping and unstreaming the baskets. NOTE1: By default histograms are added. However hadd does not support the case where histograms have their bit TH1::kIsAverage set. NOTE2: hadd returns a status code: 0 if OK, -1 otherwise Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, [email protected] : rewritten from scratch by Rene Brun (30 November 2005) to support files with nested directories. Toby Burnett implemented the possibility to use indirect files. */ #include "RConfig.h" #include <string> #include "TFile.h" #include "THashList.h" #include "TKey.h" #include "TObjString.h" #include "Riostream.h" #include "TClass.h" #include "TSystem.h" #include <stdlib.h> #include "TFileMerger.h" //___________________________________________________________________________ int main( int argc, char **argv ) { if ( argc < 3 || "-h" == string(argv[1]) || "--help" == string(argv[1]) ) { cout << "Usage: " << argv[0] << " [-f[0-9]] [-k] [-T] [-O] [-n maxopenedfiles] targetfile source1 [source2 source3 ...]" << endl; cout << "This program will add histograms from a list of root files and write them" << endl; cout << "to a target root file. The target file is newly created and must not " << endl; cout << "exist, or if -f (\"force\") is given, must not be one of the source files." << endl; cout << "Supply at least two source files for this to make sense... ;-)" << endl; cout << "If the option -k is used, hadd will not exit on corrupt or non-existant input files but skip the offending files instead." << endl; cout << "If the option -T is used, Trees are not merged" <<endl; cout << "If the option -O is used, when merging TTree, the basket size is re-optimized" <<endl; cout << "If the option -n is used, hadd will open at most 'maxopenedfiles' at once, use 0 to request to use the system maximum." << endl; cout << "When -the -f option is specified, one can also specify the compression" <<endl; cout << "level of the target file. By default the compression level is 1, but" <<endl; cout << "if \"-f0\" is specified, the target file will not be compressed." <<endl; cout << "if \"-f6\" is specified, the compression level 6 will be used." <<endl; cout << "if Target and source files have different compression levels"<<endl; cout << " a slower method is used"<<endl; return 1; } Bool_t force = kFALSE; Bool_t skip_errors = kFALSE; Bool_t reoptimize = kFALSE; Bool_t noTrees = kFALSE; Int_t maxopenedfiles = 0; int ffirst = 2; Int_t newcomp = 1; for( int a = 1; a < argc; ++a ) { if ( strcmp(argv[a],"-T") == 0 ) { noTrees = kTRUE; ++ffirst; } else if ( strcmp(argv[a],"-f") == 0 ) { force = kTRUE; ++ffirst; } else if ( strcmp(argv[a],"-k") == 0 ) { skip_errors = kTRUE; ++ffirst; } else if ( strcmp(argv[a],"-O") == 0 ) { reoptimize = kTRUE; ++ffirst; } else if ( strcmp(argv[a],"-n") == 0 ) { if (a+1 >= argc) { cerr << "Error: no maximum number of opened was provided after -n.\n"; } else { long request = strtol(argv[a+1], 0, 10); if (request < kMaxLong && request >= 0) { maxopenedfiles = (Int_t)request; ++a; ++ffirst; } else { cerr << "Error: could not parse the max number of opened file passed after -n: " << argv[a+1] << ". We will use the system maximum.\n"; } } ++ffirst; } else if ( argv[a][0] == '-' ) { char ft[4]; for( int j=0; j<=9; ++j ) { snprintf(ft,4,"-f%d",j); if (!strcmp(argv[a],ft)) { force = kTRUE; newcomp = j; ++ffirst; break; } } if (!force) { // Bad argument cerr << "Error: option " << argv[a] << " is not a supported option.\n"; ++ffirst; } } } gSystem->Load("libTreePlayer"); cout << "Target file: " << argv[ffirst-1] << endl; TFileMerger merger(kFALSE,kFALSE); merger.SetPrintLevel(99); if (maxopenedfiles > 0) { merger.SetMaxOpenedFiles(maxopenedfiles); } if (!merger.OutputFile(argv[ffirst-1],force,newcomp) ) { cerr << "Error opening target file (does " << argv[ffirst-1] << " exist?)." << endl; cerr << "Pass \"-f\" argument to force re-creation of output file." << endl; exit(1); } for ( int i = ffirst; i < argc; i++ ) { if (argv[i] && argv[i][0]=='@') { std::ifstream indirect_file(argv[i]+1); if( ! indirect_file.is_open() ) { std::cerr<< "Could not open indirect file " << (argv[i]+1) << std::endl; return 1; } while( indirect_file ){ std::string line; std::getline(indirect_file, line); if( !merger.AddFile(line.c_str()) ) { return 1; } } } else if( ! merger.AddFile(argv[i]) ) { if ( skip_errors ) { cerr << "Skipping file with error: " << argv[i] << endl; } else { cerr << "Exiting due to error in " << argv[i] << endl; return 1; } } } if (reoptimize) { merger.SetFastMethod(kFALSE); } else { if (merger.HasCompressionChange()) { // Don't warn if the user any request re-optimization. cout <<"Sources and Target have different compression levels"<<endl; cout <<"Merging will be slower"<<endl; } } merger.SetNotrees(noTrees); Bool_t status = merger.Merge(); if (status) { return 0; } else { return 1; } } <commit_msg>Update argument parsing in hadd to support the often typed:<commit_after>/* This program will add histograms (see note) and Trees from a list of root files and write them to a target root file. The target file is newly created and must not be identical to one of the source files. Syntax: hadd targetfile source1 source2 ... or hadd -f targetfile source1 source2 ... (targetfile is overwritten if it exists) When -the -f option is specified, one can also specify the compression level of the target file. By default the compression level is 1, but if "-f0" is specified, the target file will not be compressed. if "-f6" is specified, the compression level 6 will be used. For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn f1 with h1 h2 h3 T1 f2 with h1 h4 T1 T2 f3 with h5 the result of hadd -f x.root f1.root f2.root f3.root will be a file x.root with h1 h2 h3 h4 h5 T1 T2 where h1 will be the sum of the 2 histograms in f1 and f2 T1 will be the merge of the Trees in f1 and f2 The files may contain sub-directories. if the source files contains histograms and Trees, one can skip the Trees with hadd -T targetfile source1 source2 ... Wildcarding and indirect files are also supported hadd result.root myfil*.root will merge all files in myfil*.root hadd result.root file1.root @list.txt file2. root myfil*.root will merge file1. root, file2. root, all files in myfil*.root and all files in the indirect text file list.txt ("@" as the first character of the file indicates an indirect file. An indirect file is a text file containing a list of other files, including other indirect files, one line per file). If the sources and and target compression levels are identical (default), the program uses the TChain::Merge function with option "fast", ie the merge will be done without unzipping or unstreaming the baskets (i.e. direct copy of the raw byte on disk). The "fast" mode is typically 5 times faster than the mode unzipping and unstreaming the baskets. NOTE1: By default histograms are added. However hadd does not support the case where histograms have their bit TH1::kIsAverage set. NOTE2: hadd returns a status code: 0 if OK, -1 otherwise Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, [email protected] : rewritten from scratch by Rene Brun (30 November 2005) to support files with nested directories. Toby Burnett implemented the possibility to use indirect files. */ #include "RConfig.h" #include <string> #include "TFile.h" #include "THashList.h" #include "TKey.h" #include "TObjString.h" #include "Riostream.h" #include "TClass.h" #include "TSystem.h" #include <stdlib.h> #include "TFileMerger.h" //___________________________________________________________________________ int main( int argc, char **argv ) { if ( argc < 3 || "-h" == string(argv[1]) || "--help" == string(argv[1]) ) { cout << "Usage: " << argv[0] << " [-f[0-9]] [-k] [-T] [-O] [-n maxopenedfiles] targetfile source1 [source2 source3 ...]" << endl; cout << "This program will add histograms from a list of root files and write them" << endl; cout << "to a target root file. The target file is newly created and must not " << endl; cout << "exist, or if -f (\"force\") is given, must not be one of the source files." << endl; cout << "Supply at least two source files for this to make sense... ;-)" << endl; cout << "If the option -k is used, hadd will not exit on corrupt or non-existant input files but skip the offending files instead." << endl; cout << "If the option -T is used, Trees are not merged" <<endl; cout << "If the option -O is used, when merging TTree, the basket size is re-optimized" <<endl; cout << "If the option -n is used, hadd will open at most 'maxopenedfiles' at once, use 0 to request to use the system maximum." << endl; cout << "When -the -f option is specified, one can also specify the compression" <<endl; cout << "level of the target file. By default the compression level is 1, but" <<endl; cout << "if \"-f0\" is specified, the target file will not be compressed." <<endl; cout << "if \"-f6\" is specified, the compression level 6 will be used." <<endl; cout << "if Target and source files have different compression levels"<<endl; cout << " a slower method is used"<<endl; return 1; } Bool_t force = kFALSE; Bool_t skip_errors = kFALSE; Bool_t reoptimize = kFALSE; Bool_t noTrees = kFALSE; Int_t maxopenedfiles = 0; int outputPlace = 0; int ffirst = 2; Int_t newcomp = 1; for( int a = 1; a < argc; ++a ) { if ( strcmp(argv[a],"-T") == 0 ) { noTrees = kTRUE; ++ffirst; } else if ( strcmp(argv[a],"-f") == 0 ) { force = kTRUE; ++ffirst; } else if ( strcmp(argv[a],"-k") == 0 ) { skip_errors = kTRUE; ++ffirst; } else if ( strcmp(argv[a],"-O") == 0 ) { reoptimize = kTRUE; ++ffirst; } else if ( strcmp(argv[a],"-n") == 0 ) { if (a+1 >= argc) { cerr << "Error: no maximum number of opened was provided after -n.\n"; } else { long request = strtol(argv[a+1], 0, 10); if (request < kMaxLong && request >= 0) { maxopenedfiles = (Int_t)request; ++a; ++ffirst; } else { cerr << "Error: could not parse the max number of opened file passed after -n: " << argv[a+1] << ". We will use the system maximum.\n"; } } ++ffirst; } else if ( argv[a][0] == '-' ) { char ft[4]; for( int j=0; j<=9; ++j ) { snprintf(ft,4,"-f%d",j); if (!strcmp(argv[a],ft)) { force = kTRUE; newcomp = j; ++ffirst; break; } } if (!force) { // Bad argument cerr << "Error: option " << argv[a] << " is not a supported option.\n"; ++ffirst; } } else if (!outputPlace) { outputPlace = a; } } gSystem->Load("libTreePlayer"); const char *targetname = 0; if (outputPlace) { targetname = argv[outputPlace]; } else { targetname = argv[ffirst-1]; } cout << "Target file: " << targetname << endl; TFileMerger merger(kFALSE,kFALSE); merger.SetPrintLevel(99); if (maxopenedfiles > 0) { merger.SetMaxOpenedFiles(maxopenedfiles); } if (!merger.OutputFile(targetname,force,newcomp) ) { cerr << "Error opening target file (does " << argv[ffirst-1] << " exist?)." << endl; cerr << "Pass \"-f\" argument to force re-creation of output file." << endl; exit(1); } for ( int i = ffirst; i < argc; i++ ) { if (argv[i] && argv[i][0]=='@') { std::ifstream indirect_file(argv[i]+1); if( ! indirect_file.is_open() ) { std::cerr<< "Could not open indirect file " << (argv[i]+1) << std::endl; return 1; } while( indirect_file ){ std::string line; std::getline(indirect_file, line); if( !merger.AddFile(line.c_str()) ) { return 1; } } } else if( ! merger.AddFile(argv[i]) ) { if ( skip_errors ) { cerr << "Skipping file with error: " << argv[i] << endl; } else { cerr << "Exiting due to error in " << argv[i] << endl; return 1; } } } if (reoptimize) { merger.SetFastMethod(kFALSE); } else { if (merger.HasCompressionChange()) { // Don't warn if the user any request re-optimization. cout <<"Sources and Target have different compression levels"<<endl; cout <<"Merging will be slower"<<endl; } } merger.SetNotrees(noTrees); Bool_t status = merger.Merge(); if (status) { return 0; } else { return 1; } } <|endoftext|>
<commit_before>/// @file /// @author uentity /// @date 12.01.2016 /// @brief /// @copyright /// This Source Code Form is subject to the terms of the Mozilla Public License, /// v. 2.0. If a copy of the MPL was not distributed with this file, /// You can obtain one at https://mozilla.org/MPL/2.0/ #include <bs/python/common.h> #include <bs/compat/messaging.h> BSPY_ANY_CAST_EXTRA(long double) #include <bs/python/any.h> NAMESPACE_BEGIN(blue_sky::python) void py_bind_signal(py::module&); NAMESPACE_BEGIN() using namespace std; // bs_slot wrapper class py_bs_slot : public bs_slot { public: using bs_slot::bs_slot; void execute(std::any sender, int signal_code, std::any param) const override { // Use modified version of PYBIND11_OVERLOAD_PURE macro code // original implementation would fail with runtime error that pure virtual method is called // if no overload was found. But slot should be safe in sutuation when Python object is // already destroyed. In such a case just DO NOTHING and return. pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bs_slot *>(this), "execute"); if (overload) { auto o = overload(std::move(sender), signal_code, std::move(param)); if (pybind11::detail::cast_is_temporary_value_reference<void>::value) { static pybind11::detail::overload_caster_t<void> caster; return pybind11::detail::cast_ref<void>(std::move(o), caster); } else return pybind11::detail::cast_safe<void>(std::move(o)); } //PYBIND11_OVERLOAD_PURE( // void, // bs_slot, // execute, // std::move(sender), signal_code, std::move(param) //); } }; // bs_imessaging wrapper // template used to flatten trampoline hierarchy -- they don't support multiple inheritance template<typename Next = bs_imessaging> class py_bs_imessaging : public Next { public: using Next::Next; bool subscribe(int signal_code, sp_slot slot) const override { PYBIND11_OVERLOAD_PURE( bool, Next, subscribe, signal_code, std::move(slot) ); } bool unsubscribe(int signal_code, sp_slot slot) const override { PYBIND11_OVERLOAD_PURE( bool, Next, unsubscribe, signal_code, std::move(slot) ); } ulong num_slots(int signal_code) const override { PYBIND11_OVERLOAD_PURE( ulong, Next, num_slots, signal_code ); } bool fire_signal(int signal_code, std::any param, std::any sender) const override { PYBIND11_OVERLOAD_PURE( bool, Next, fire_signal, signal_code, std::move(param), std::move(sender) ); } std::vector< int > get_signal_list() const override { PYBIND11_OVERLOAD_PURE( std::vector< int >, Next, get_signal_list ); } }; void slot_tester(int c, const sp_slot& slot, std::any param) { slot->execute(nullptr, c, std::move(param)); } NAMESPACE_END() // exporting function void py_bind_messaging(py::module& m) { // slot py::class_< bs_slot, py_bs_slot, std::shared_ptr<bs_slot> >(m, "slot") .def(py::init<>()) .def("execute", &bs_slot::execute) ; // signal py::class_< bs_signal, std::shared_ptr< bs_signal > >(m, "signal") .def(py::init<int>()) .def("init", &bs_signal::init) .def_property_readonly("get_code", &bs_signal::get_code) .def("connect", &bs_signal::connect, "slot"_a, "sender"_a = nullptr) .def("disconnect", &bs_signal::disconnect) .def_property_readonly("num_slots", &bs_signal::num_slots) .def("fire", &bs_signal::fire, "sender"_a = nullptr, "param"_a = std::any{}) ; // DEBUG m.def("slot_tester", &slot_tester); // bs_imessaging abstract class py::class_< bs_imessaging, py_bs_imessaging<>, std::shared_ptr<bs_imessaging> >(m, "imessaging") .def("subscribe" , &bs_imessaging::subscribe) .def("unsubscribe" , &bs_imessaging::unsubscribe) .def("num_slots" , &bs_imessaging::num_slots) .def("fire_signal" , &bs_imessaging::fire_signal, "signal_code"_a, "param"_a = nullptr, "sender"_a = nullptr ) .def("get_signal_list" , &bs_imessaging::get_signal_list) ; // bs_messaging bool (bs_messaging::*add_signal_ptr)(int) = &bs_messaging::add_signal; py::class_< bs_messaging, bs_imessaging, objbase, py_bs_imessaging<bs_messaging>, std::shared_ptr<bs_messaging> >(m, "messaging", py::multiple_inheritance()) BSPY_EXPORT_DEF(bs_messaging) .def(py::init_alias<>()) .def(py::init_alias< bs_messaging::sig_range_t >()) .def("subscribe" , &bs_messaging::subscribe) .def("unsubscribe" , &bs_messaging::unsubscribe) .def("num_slots" , &bs_messaging::num_slots) .def("fire_signal" , &bs_messaging::fire_signal, "signal_code"_a, "param"_a = nullptr, "sender"_a = nullptr ) .def("add_signal" , add_signal_ptr) .def("remove_signal" , &bs_messaging::remove_signal) .def("get_signal_list" , &bs_messaging::get_signal_list) .def("clear" , &bs_messaging::clear) .def("test_slot1", [](const bs_messaging& src, const sp_slot& slot, const sp_obj param = nullptr) { slot->execute(src.shared_from_this(), 42, param); }) ; } NAMESPACE_END(blue_sky::python) <commit_msg>python/compat: remove unused `bs_imessaging` and `bs_messaging trampolines<commit_after>/// @file /// @author uentity /// @date 12.01.2016 /// @brief Python bindings for BS signal-slot subsystem /// @copyright /// This Source Code Form is subject to the terms of the Mozilla Public License, /// v. 2.0. If a copy of the MPL was not distributed with this file, /// You can obtain one at https://mozilla.org/MPL/2.0/ #include <bs/python/common.h> #include <bs/compat/messaging.h> BSPY_ANY_CAST_EXTRA(long double) #include <bs/python/any.h> NAMESPACE_BEGIN(blue_sky::python) NAMESPACE_BEGIN() using namespace std; // bs_slot wrapper class py_bs_slot : public bs_slot { public: using bs_slot::bs_slot; void execute(std::any sender, int signal_code, std::any param) const override { // Use modified version of PYBIND11_OVERLOAD_PURE macro code // original implementation would fail with runtime error that pure virtual method is called // if no overload was found. But slot should be safe in sutuation when Python object is // already destroyed. In such a case just DO NOTHING and return. pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bs_slot *>(this), "execute"); if (overload) { auto o = overload(std::move(sender), signal_code, std::move(param)); if (pybind11::detail::cast_is_temporary_value_reference<void>::value) { static pybind11::detail::overload_caster_t<void> caster; return pybind11::detail::cast_ref<void>(std::move(o), caster); } else return pybind11::detail::cast_safe<void>(std::move(o)); } } }; NAMESPACE_END() // exporting function void py_bind_messaging(py::module& m) { // slot py::class_< bs_slot, py_bs_slot, std::shared_ptr<bs_slot> >(m, "slot") .def(py::init<>()) .def("execute", &bs_slot::execute) ; // signal py::class_< bs_signal, std::shared_ptr< bs_signal > >(m, "signal") .def(py::init<int>()) .def("init", &bs_signal::init) .def_property_readonly("get_code", &bs_signal::get_code) .def("connect", &bs_signal::connect, "slot"_a, "sender"_a = nullptr) .def("disconnect", &bs_signal::disconnect) .def_property_readonly("num_slots", &bs_signal::num_slots) .def("fire", &bs_signal::fire, "sender"_a = nullptr, "param"_a = std::any{}) ; // bs_messaging bool (bs_messaging::*add_signal_ptr)(int) = &bs_messaging::add_signal; py::class_< bs_messaging, objbase, std::shared_ptr<bs_messaging> >(m, "messaging", py::multiple_inheritance()) BSPY_EXPORT_DEF(bs_messaging) .def(py::init<>()) .def(py::init<bs_messaging::sig_range_t>()) .def("subscribe" , &bs_messaging::subscribe) .def("unsubscribe" , &bs_messaging::unsubscribe) .def("num_slots" , &bs_messaging::num_slots) .def("fire_signal" , &bs_messaging::fire_signal, "signal_code"_a, "param"_a = nullptr, "sender"_a = nullptr ) .def("add_signal" , add_signal_ptr) .def("remove_signal" , &bs_messaging::remove_signal) .def("get_signal_list" , &bs_messaging::get_signal_list) .def("clear" , &bs_messaging::clear) ; } NAMESPACE_END(blue_sky::python) <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <stdio.h> #include <unistd.h> #include <memory> #include <list> #include <unotools/streamwrap.hxx> #include <unotools/ucbstreamhelper.hxx> #include <comphelper/processfactory.hxx> #include <comphelper/regpathhelper.hxx> #include <cppuhelper/servicefactory.hxx> #include <cppuhelper/bootstrap.hxx> #include <com/sun/star/uno/Reference.h> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/registry/XSimpleRegistry.hpp> #include <ucbhelper/contentbroker.hxx> #include <ucbhelper/configurationkeys.hxx> #include <tools/urlobj.hxx> #include <tools/fsys.hxx> #include <svtools/filedlg.hxx> #include <vcl/window.hxx> #include <vcl/svapp.hxx> #include <vcl/font.hxx> #include <vcl/sound.hxx> #include <vcl/print.hxx> #include <vcl/toolbox.hxx> #include <vcl/help.hxx> #include <vcl/scrbar.hxx> #include <vcl/wrkwin.hxx> #include <vcl/msgbox.hxx> #include <osl/file.hxx> #include <osl/process.h> #include <rtl/bootstrap.hxx> #include <galtheme.hxx> #include <svx/gallery1.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::registry; using namespace ::com::sun::star::lang; typedef ::std::list<rtl::OUString> FileNameList; class GalApp : public Application { public: virtual int Main(); protected: Reference<XMultiServiceFactory> xMSF; void Init(); void InitUCB(); }; Gallery* createGallery( const rtl::OUString& aGalleryURL ) { return new Gallery( aGalleryURL ); } void disposeGallery( Gallery* pGallery ) { delete pGallery; } static void createTheme( rtl::OUString aThemeName, rtl::OUString aGalleryURL, rtl::OUString aDestDir, UINT32 nNumFrom, FileNameList &rFiles ) { Gallery * pGallery( createGallery( aGalleryURL ) ); if (!pGallery ) { fprintf( stderr, "Could't acquire '%s'\n", (const sal_Char *) rtl::OUStringToOString( aGalleryURL, RTL_TEXTENCODING_UTF8 ) ); exit( 1 ); } fprintf( stderr, "Work on gallery '%s'\n", (const sal_Char *) rtl::OUStringToOString( aGalleryURL, RTL_TEXTENCODING_UTF8 ) ); fprintf( stderr, "Existing themes: %lu\n", sal::static_int_cast< unsigned long >( pGallery->GetThemeCount() ) ); if( !pGallery->HasTheme( aThemeName) ) { if( !pGallery->CreateTheme( aThemeName, nNumFrom ) ) { fprintf( stderr, "Failed to create theme\n" ); disposeGallery( pGallery ); exit( 1 ); } } fprintf( stderr, "Existing themes: %lu\n", sal::static_int_cast< unsigned long >( pGallery->GetThemeCount() ) ); SfxListener aListener; GalleryTheme *pGalTheme = pGallery->AcquireTheme( aThemeName, aListener ); if ( pGalTheme == NULL ) { fprintf( stderr, "Failed to acquire theme\n" ); disposeGallery( pGallery ); exit( 1 ); } fprintf( stderr, "Using DestDir: %s\n", (const sal_Char *) rtl::OUStringToOString( aDestDir, RTL_TEXTENCODING_UTF8 ) ); pGalTheme->SetDestDir(String(aDestDir)); FileNameList::const_iterator aIter; for( aIter = rFiles.begin(); aIter != rFiles.end(); aIter++ ) { // Should/could use: // if ( ! pGalTheme->InsertFileOrDirURL( aURL ) ) { // Requires a load more components ... Graphic aGraphic; String aFormat; #if 1 if ( ! pGalTheme->InsertURL( *aIter ) ) fprintf( stderr, "Failed to import '%s'\n", (const sal_Char *) rtl::OUStringToOString( *aIter, RTL_TEXTENCODING_UTF8 ) ); else fprintf( stderr, "Imported file '%s' (%lu)\n", (const sal_Char *) rtl::OUStringToOString( *aIter, RTL_TEXTENCODING_UTF8 ), sal::static_int_cast< unsigned long >( pGalTheme->GetObjectCount() ) ); #else // only loads BMPs SvStream *pStream = ::utl::UcbStreamHelper::CreateStream( *aIter, STREAM_READ ); if (!pStream) { fprintf( stderr, "Can't find image to import\n" ); disposeGallery( pGallery ); exit (1); } *pStream >> aGraphic; delete pStream; if( aGraphic.GetType() == GRAPHIC_NONE ) { fprintf( stderr, "Failed to load '%s'\n", (const sal_Char *) rtl::OUStringToOString( *aIter, RTL_TEXTENCODING_UTF8 ) ); continue; } SgaObjectBmp aObject( aGraphic, *aIter, aFormat ); if ( ! aObject.IsValid() ) { fprintf( stderr, "Failed to create thumbnail for image\n" ); continue; } if ( ! pGalTheme->InsertObject( aObject ) ) { fprintf( stderr, "Failed to insert file or URL\n" ); continue; } #endif } pGallery->ReleaseTheme( pGalTheme, aListener ); disposeGallery( pGallery ); } static void PrintHelp() { fprintf( stdout, "Utility to generate OO.o gallery files\n\n" ); fprintf( stdout, "using: gengal --name <name> --path <dir> [ --destdir <path> ]\n"); fprintf( stdout, " [ --number-from <num> ] [ files ... ]\n\n" ); fprintf( stdout, "options:\n"); fprintf( stdout, " --name <theme>\t\tdefines a name of the created or updated theme.\n"); fprintf( stdout, " --path <dir>\t\tdefines directory where the gallery files are created\n"); fprintf( stdout, "\t\t\tor updated.\n"); fprintf( stdout, " --destdir <dir>\tdefines a path prefix to be removed from the paths\n"); fprintf( stdout, "\t\t\tstored in the gallery files. It is useful to create\n"); fprintf( stdout, "\t\t\tRPM packages using the BuildRoot feature.\n"); fprintf( stdout, " --number-from <num>\tdefines minimal number for the newly created gallery\n"); fprintf( stdout, "\t\t\ttheme files.\n"); fprintf( stdout, " files\t\t\tlists files to be added to the gallery. Absolute paths\n"); fprintf( stdout, "\t\t\tare required.\n"); } static rtl::OUString Smartify( const rtl::OUString &rPath ) { INetURLObject aURL; aURL.SetSmartURL( rPath ); return aURL.GetMainURL( INetURLObject::NO_DECODE ); } #define OUSTRING_CSTR( str ) \ rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US ).getStr() void GalApp::Init() { if( getenv( "OOO_INSTALL_PREFIX" ) == NULL ) { rtl::OUString fileName = GetAppFileName(); int lastSlash = fileName.lastIndexOf( '/' ); #ifdef WNT // Don't know which directory separators GetAppFileName() returns on Windows. // Be safe and take into consideration they might be backslashes. if( fileName.lastIndexOf( '\\' ) > lastSlash ) lastSlash = fileName.lastIndexOf( '\\' ); #endif rtl::OUString baseBinDir = fileName.copy( 0, lastSlash ); rtl::OUString installPrefix = baseBinDir + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/../..")); rtl::OUString envVar(RTL_CONSTASCII_USTRINGPARAM("OOO_INSTALL_PREFIX")); osl_setEnvironment(envVar.pData, installPrefix.pData); } OSL_TRACE( "OOO_INSTALL_PREFIX=%s", getenv( "OOO_INSTALL_PREFIX" ) ); Reference<XComponentContext> xComponentContext = ::cppu::defaultBootstrap_InitialComponentContext(); xMSF = Reference<XMultiServiceFactory> ( xComponentContext->getServiceManager(), UNO_QUERY ); if( !xMSF.is() ) fprintf( stderr, "Failed to bootstrap\n" ); ::comphelper::setProcessServiceFactory( xMSF ); InitUCB(); } void GalApp::InitUCB() { rtl::OUString aEmpty; Sequence< Any > aArgs(6); aArgs[0] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UCB_CONFIGURATION_KEY1_LOCAL)); aArgs[1] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UCB_CONFIGURATION_KEY2_OFFICE)); aArgs[2] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PIPE")); aArgs[3] <<= aEmpty; aArgs[4] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PORTAL")); aArgs[5] <<= aEmpty; if (! ::ucbhelper::ContentBroker::initialize( xMSF, aArgs ) ) fprintf( stderr, "Failed to init content broker\n" ); } int GalApp::Main() { bool bHelp = false; rtl::OUString aPath, aDestDir; rtl::OUString aName(RTL_CONSTASCII_USTRINGPARAM("Default name")); UINT32 nNumFrom = 0; FileNameList aFiles; for( USHORT i = 0; i < GetCommandLineParamCount(); i++ ) { rtl::OUString aParam = GetCommandLineParam( i ); if( aParam.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "--help" ) ) || aParam.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "-h" ) ) ) bHelp = true; else if ( aParam.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "--name" ) ) ) aName = GetCommandLineParam( ++i ); else if ( aParam.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "--path" ) ) ) aPath = Smartify( GetCommandLineParam( ++i ) ); else if ( aParam.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "--destdir" ) ) ) aDestDir = GetCommandLineParam( ++i ); else if ( aParam.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "--number-from" ) ) ) nNumFrom = GetCommandLineParam( ++i ).ToInt32(); else aFiles.push_back( Smartify( aParam ) ); } if( bHelp ) { PrintHelp(); return EXIT_SUCCESS; } createTheme( aName, aPath, aDestDir, nNumFrom, aFiles ); return EXIT_SUCCESS; } GalApp aGalApp; /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>avoid implicit casting<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <stdio.h> #include <unistd.h> #include <memory> #include <list> #include <unotools/streamwrap.hxx> #include <unotools/ucbstreamhelper.hxx> #include <comphelper/processfactory.hxx> #include <comphelper/regpathhelper.hxx> #include <cppuhelper/servicefactory.hxx> #include <cppuhelper/bootstrap.hxx> #include <com/sun/star/uno/Reference.h> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/lang/XInitialization.hpp> #include <com/sun/star/registry/XSimpleRegistry.hpp> #include <ucbhelper/contentbroker.hxx> #include <ucbhelper/configurationkeys.hxx> #include <tools/urlobj.hxx> #include <tools/fsys.hxx> #include <svtools/filedlg.hxx> #include <vcl/window.hxx> #include <vcl/svapp.hxx> #include <vcl/font.hxx> #include <vcl/sound.hxx> #include <vcl/print.hxx> #include <vcl/toolbox.hxx> #include <vcl/help.hxx> #include <vcl/scrbar.hxx> #include <vcl/wrkwin.hxx> #include <vcl/msgbox.hxx> #include <osl/file.hxx> #include <osl/process.h> #include <rtl/bootstrap.hxx> #include <galtheme.hxx> #include <svx/gallery1.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::registry; using namespace ::com::sun::star::lang; typedef ::std::list<rtl::OUString> FileNameList; class GalApp : public Application { public: virtual int Main(); protected: Reference<XMultiServiceFactory> xMSF; void Init(); void InitUCB(); }; Gallery* createGallery( const rtl::OUString& aGalleryURL ) { return new Gallery( aGalleryURL ); } void disposeGallery( Gallery* pGallery ) { delete pGallery; } static void createTheme( rtl::OUString aThemeName, rtl::OUString aGalleryURL, rtl::OUString aDestDir, UINT32 nNumFrom, FileNameList &rFiles ) { Gallery * pGallery( createGallery( aGalleryURL ) ); if (!pGallery ) { fprintf( stderr, "Could't acquire '%s'\n", rtl::OUStringToOString(aGalleryURL, RTL_TEXTENCODING_UTF8).getStr() ); exit( 1 ); } fprintf( stderr, "Work on gallery '%s'\n", rtl::OUStringToOString(aGalleryURL, RTL_TEXTENCODING_UTF8).getStr() ); fprintf( stderr, "Existing themes: %lu\n", sal::static_int_cast< unsigned long >( pGallery->GetThemeCount() ) ); if( !pGallery->HasTheme( aThemeName) ) { if( !pGallery->CreateTheme( aThemeName, nNumFrom ) ) { fprintf( stderr, "Failed to create theme\n" ); disposeGallery( pGallery ); exit( 1 ); } } fprintf( stderr, "Existing themes: %lu\n", sal::static_int_cast< unsigned long >( pGallery->GetThemeCount() ) ); SfxListener aListener; GalleryTheme *pGalTheme = pGallery->AcquireTheme( aThemeName, aListener ); if ( pGalTheme == NULL ) { fprintf( stderr, "Failed to acquire theme\n" ); disposeGallery( pGallery ); exit( 1 ); } fprintf( stderr, "Using DestDir: %s\n", rtl::OUStringToOString(aDestDir, RTL_TEXTENCODING_UTF8).getStr() ); pGalTheme->SetDestDir(String(aDestDir)); FileNameList::const_iterator aIter; for( aIter = rFiles.begin(); aIter != rFiles.end(); aIter++ ) { // Should/could use: // if ( ! pGalTheme->InsertFileOrDirURL( aURL ) ) { // Requires a load more components ... Graphic aGraphic; String aFormat; #if 1 if ( ! pGalTheme->InsertURL( *aIter ) ) fprintf( stderr, "Failed to import '%s'\n", rtl::OUStringToOString(*aIter, RTL_TEXTENCODING_UTF8).getStr() ); else fprintf( stderr, "Imported file '%s' (%lu)\n", rtl::OUStringToOString(*aIter, RTL_TEXTENCODING_UTF8).getStr(), sal::static_int_cast< unsigned long >( pGalTheme->GetObjectCount() ) ); #else // only loads BMPs SvStream *pStream = ::utl::UcbStreamHelper::CreateStream( *aIter, STREAM_READ ); if (!pStream) { fprintf( stderr, "Can't find image to import\n" ); disposeGallery( pGallery ); exit (1); } *pStream >> aGraphic; delete pStream; if( aGraphic.GetType() == GRAPHIC_NONE ) { fprintf( stderr, "Failed to load '%s'\n", (const sal_Char *) rtl::OUStringToOString( *aIter, RTL_TEXTENCODING_UTF8 ) ); continue; } SgaObjectBmp aObject( aGraphic, *aIter, aFormat ); if ( ! aObject.IsValid() ) { fprintf( stderr, "Failed to create thumbnail for image\n" ); continue; } if ( ! pGalTheme->InsertObject( aObject ) ) { fprintf( stderr, "Failed to insert file or URL\n" ); continue; } #endif } pGallery->ReleaseTheme( pGalTheme, aListener ); disposeGallery( pGallery ); } static void PrintHelp() { fprintf( stdout, "Utility to generate OO.o gallery files\n\n" ); fprintf( stdout, "using: gengal --name <name> --path <dir> [ --destdir <path> ]\n"); fprintf( stdout, " [ --number-from <num> ] [ files ... ]\n\n" ); fprintf( stdout, "options:\n"); fprintf( stdout, " --name <theme>\t\tdefines a name of the created or updated theme.\n"); fprintf( stdout, " --path <dir>\t\tdefines directory where the gallery files are created\n"); fprintf( stdout, "\t\t\tor updated.\n"); fprintf( stdout, " --destdir <dir>\tdefines a path prefix to be removed from the paths\n"); fprintf( stdout, "\t\t\tstored in the gallery files. It is useful to create\n"); fprintf( stdout, "\t\t\tRPM packages using the BuildRoot feature.\n"); fprintf( stdout, " --number-from <num>\tdefines minimal number for the newly created gallery\n"); fprintf( stdout, "\t\t\ttheme files.\n"); fprintf( stdout, " files\t\t\tlists files to be added to the gallery. Absolute paths\n"); fprintf( stdout, "\t\t\tare required.\n"); } static rtl::OUString Smartify( const rtl::OUString &rPath ) { INetURLObject aURL; aURL.SetSmartURL( rPath ); return aURL.GetMainURL( INetURLObject::NO_DECODE ); } #define OUSTRING_CSTR( str ) \ rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US ).getStr() void GalApp::Init() { if( getenv( "OOO_INSTALL_PREFIX" ) == NULL ) { rtl::OUString fileName = GetAppFileName(); int lastSlash = fileName.lastIndexOf( '/' ); #ifdef WNT // Don't know which directory separators GetAppFileName() returns on Windows. // Be safe and take into consideration they might be backslashes. if( fileName.lastIndexOf( '\\' ) > lastSlash ) lastSlash = fileName.lastIndexOf( '\\' ); #endif rtl::OUString baseBinDir = fileName.copy( 0, lastSlash ); rtl::OUString installPrefix = baseBinDir + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/../..")); rtl::OUString envVar(RTL_CONSTASCII_USTRINGPARAM("OOO_INSTALL_PREFIX")); osl_setEnvironment(envVar.pData, installPrefix.pData); } OSL_TRACE( "OOO_INSTALL_PREFIX=%s", getenv( "OOO_INSTALL_PREFIX" ) ); Reference<XComponentContext> xComponentContext = ::cppu::defaultBootstrap_InitialComponentContext(); xMSF = Reference<XMultiServiceFactory> ( xComponentContext->getServiceManager(), UNO_QUERY ); if( !xMSF.is() ) fprintf( stderr, "Failed to bootstrap\n" ); ::comphelper::setProcessServiceFactory( xMSF ); InitUCB(); } void GalApp::InitUCB() { rtl::OUString aEmpty; Sequence< Any > aArgs(6); aArgs[0] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UCB_CONFIGURATION_KEY1_LOCAL)); aArgs[1] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(UCB_CONFIGURATION_KEY2_OFFICE)); aArgs[2] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PIPE")); aArgs[3] <<= aEmpty; aArgs[4] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PORTAL")); aArgs[5] <<= aEmpty; if (! ::ucbhelper::ContentBroker::initialize( xMSF, aArgs ) ) fprintf( stderr, "Failed to init content broker\n" ); } int GalApp::Main() { bool bHelp = false; rtl::OUString aPath, aDestDir; rtl::OUString aName(RTL_CONSTASCII_USTRINGPARAM("Default name")); UINT32 nNumFrom = 0; FileNameList aFiles; for( USHORT i = 0; i < GetCommandLineParamCount(); i++ ) { rtl::OUString aParam = GetCommandLineParam( i ); if( aParam.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "--help" ) ) || aParam.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "-h" ) ) ) bHelp = true; else if ( aParam.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "--name" ) ) ) aName = GetCommandLineParam( ++i ); else if ( aParam.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "--path" ) ) ) aPath = Smartify( GetCommandLineParam( ++i ) ); else if ( aParam.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "--destdir" ) ) ) aDestDir = GetCommandLineParam( ++i ); else if ( aParam.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "--number-from" ) ) ) nNumFrom = GetCommandLineParam( ++i ).ToInt32(); else aFiles.push_back( Smartify( aParam ) ); } if( bHelp ) { PrintHelp(); return EXIT_SUCCESS; } createTheme( aName, aPath, aDestDir, nNumFrom, aFiles ); return EXIT_SUCCESS; } GalApp aGalApp; /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/********** tell emacs we use -*- c++ -*- style comments ******************* $Revision: 1.5 $ $Author: trey $ $Date: 2006-04-28 20:33:54 $ @file zmdpSolve.cc @brief No brief Copyright (c) 2002-2006, Trey Smith. 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 <assert.h> #include <sys/time.h> #include <getopt.h> #include <signal.h> #include <iostream> #include <fstream> #include "zmdpCommonTime.h" #include "solverUtils.h" using namespace std; using namespace MatrixUtils; using namespace zmdp; struct OutputParams { const char* outFileName; double timeoutSeconds; OutputParams(void); }; OutputParams::OutputParams(void) { outFileName = "out.policy"; timeoutSeconds = -1; } bool userTerminatedG = false; void sigIntHandler(int sig) { userTerminatedG = true; printf("*** received SIGINT, user pressed control-C ***\n" "terminating run and writing output policy as soon as the solver returns control\n"); fflush(stdout); } void setSignalHandler(int sig, void (*handler)(int)) { struct sigaction act; memset (&act, 0, sizeof(act)); act.sa_handler = handler; act.sa_flags = SA_RESTART; if (-1 == sigaction (sig, &act, NULL)) { cerr << "ERROR: unable to set handler for signal " << sig << endl; exit(EXIT_FAILURE); } } void doSolve(const SolverParams& p, const OutputParams& op) { StopWatch run; setSignalHandler(SIGINT, &sigIntHandler); init_matrix_utils(); printf("%05d reading model file and allocating data structures\n", (int) run.elapsedTime()); SolverObjects so; constructSolverObjects(so, p); if (!so.bounds->getSupportsPolicyOutput()) { cerr << "ERROR: with selected options, policy output is not supported:" << endl; cerr << " in order to enable policy output, problem must be a POMDP; if" << endl; cout << " it is, try adding the '-v convex' and '--lower-bound' options" << endl; exit(EXIT_FAILURE); } // initialize the solver printf("%05d calculating initial heuristics\n", (int) run.elapsedTime()); so.solver->planInit(so.sim->getModel(), p.targetPrecision); printf("%05d finished initialization, beginning to improve policy\n", (int) run.elapsedTime()); double lastPrintTime = -1000; bool reachedTargetPrecision = false; bool reachedTimeout = false; int numSolverCalls = 0; while (!(reachedTargetPrecision || reachedTimeout || userTerminatedG)) { // make a call to the solver reachedTargetPrecision = so.solver->planFixedTime(so.sim->getModel()->getInitialState(), /* maxTime = */ -1, p.targetPrecision); numSolverCalls++; // check timeout double elapsed = run.elapsedTime(); if (op.timeoutSeconds > 0 && elapsed >= op.timeoutSeconds) { reachedTimeout = true; } // print a progress update every 10 seconds if ((elapsed - lastPrintTime > 10) || reachedTargetPrecision || reachedTimeout || userTerminatedG) { ValueInterval intv = so.solver->getValueAt(so.sim->getModel()->getInitialState()); printf("%05d %6d calls to solver, bounds [%8.4f .. %8.4f], precision %g\n", (int) elapsed, numSolverCalls, intv.l, intv.u, (intv.u - intv.l)); lastPrintTime = elapsed; } } // say why the run ended if (reachedTargetPrecision) { printf("%05d terminating run; reached target precision of %g\n", (int) run.elapsedTime(), p.targetPrecision); } else if (reachedTimeout) { printf("%05d terminating run; passed specified timeout of %g seconds\n", (int) run.elapsedTime(), op.timeoutSeconds); } else { printf("%05d terminating run; caught SIGINT from user\n", (int) run.elapsedTime()); } // write out a policy printf("%05d writing policy to '%s'\n", (int) run.elapsedTime(), op.outFileName); so.bounds->writePolicy(op.outFileName); printf("%05d done\n", (int) run.elapsedTime()); } void usage(const char* cmdName) { cerr << "usage: " << cmdName << " OPTIONS <model>\n" " -h or --help Print this help\n" " --version Print version information (CFLAGS used at compilation)\n" "\n" "Solver options:\n" " -s or --search Specifies search strategy. Valid choices:\n" " rtdp, lrtdp, hdp, hsvi, frtdp [default: frtdp]\n" " -t or --type Specifies problem type. Valid choices:\n" " racetrack, pomdp [default: infer from model filename]\n" " -v or --value Specifies value function representation. Valid choices\n" " depend on problem type. With -t pomdp, choices are:\n" " point, convex [default: convex]\n" " For other problem types, choices are:\n" " point [default: point]\n" " -f or --fast Use fast (but very picky) alternate POMDP parser\n" " -p or --precision Set target precision in solution quality; run ends when\n" " target is reached [default: 1e-3]\n" " --weak-heuristic Avoid spending time generating a good upper bound heuristic\n" " (only valid for some problems, interpretation depends on\n" " the problem; e.g. sets h_U = 0 for racetrack)\n" " --lower-bound Forces zmdpSolve to maintain a lower bound and use it for\n" " action selection, even if it is not used during search.\n" " --upper-bound Forces zmdpSolve to use the upper bound for action selection\n" " (normally the lower bound is used if it is available).\n" "\n" "Policy output options:\n" " -o or --output Specifies name of policy output file [default: 'out.policy']\n" " --timeout Specifies a timeout in seconds. If running time exceeds\n" " the specified value, zmdpSolve writes out a policy\n" " and terminates [default: no maximum]\n" "\n" "Examples:\n" " " << cmdName << " RockSample_4_4.pomdp\n" " " << cmdName << " large-b.racetrack\n" " " << cmdName << " --timeout 60 --output my.policy RockSample_4_4.pomdp\n" " " << cmdName << " --search lrtdp --value point RockSample_4_4.pomdp\n" " " << cmdName << " -f RockSample_5_7.pomdp\n" "\n" ; exit(-1); } int main(int argc, char **argv) { static char shortOptions[] = "hs:t:v:fo:"; static struct option longOptions[]={ {"help", 0,NULL,'h'}, {"version", 0,NULL,'V'}, {"search", 1,NULL,'s'}, {"type", 1,NULL,'t'}, {"value", 1,NULL,'v'}, {"fast", 0,NULL,'f'}, {"precision", 1,NULL,'p'}, {"weak-heuristic",0,NULL,'W'}, {"lower-bound", 0,NULL,'L'}, {"upper-bound", 0,NULL,'U'}, {"output", 1,NULL,'o'}, {"timeout", 1,NULL,'T'}, {NULL,0,0,0} }; SolverParams p; OutputParams op; #if USE_DEBUG_PRINT // save arguments for debug printout later ostringstream outs; for (int i=1; i < argc; i++) { outs << argv[i] << " "; } #endif p.cmdName = argv[0]; while (1) { char optchar = getopt_long(argc,argv,shortOptions,longOptions,NULL); if (optchar == -1) break; switch (optchar) { case 'h': // help usage(argv[0]); break; case 'V': // version cout << "CFLAGS = " << CFLAGS << endl; exit(EXIT_SUCCESS); break; case 's': // search p.setStrategy(optarg); break; case 't': // type p.setProbType(optarg); break; case 'v': // value p.setValueRepr(optarg); break; case 'f': // fast p.useFastParser = true; break; case 'p': // precision p.targetPrecision = atof(optarg); break; case 'W': // weak-heuristic p.useHeuristic = false; break; case 'L': // lower-bound p.forceLowerBound = true; break; case 'U': // upper-bound p.forceUpperBoundActionSelection = true; break; case 'o': // output op.outFileName = optarg; break; case 'T': // timeout op.timeoutSeconds = atof(optarg); break; case '?': // unknown option case ':': // option with missing parameter // getopt() prints an informative error message cerr << endl; usage(argv[0]); break; default: abort(); // never reach this point } } if (argc-optind != 1) { cerr << "ERROR: wrong number of arguments (should be 1)" << endl << endl; usage(argv[0]); } p.probName = argv[optind++]; p.inferMissingValues(); #if USE_DEBUG_PRINT printf("CFLAGS = %s\n", CFLAGS); printf("ARGS = %s\n", outs.str().c_str()); fflush(stdout); #endif doSolve(p, op); return 0; } /*************************************************************************** * REVISION HISTORY: * $Log: not supported by cvs2svn $ * Revision 1.4 2006/04/28 17:57:41 trey * changed to use apache license * * Revision 1.3 2006/04/27 23:42:54 trey * improved error diagnostic for policy output * * Revision 1.2 2006/04/27 23:19:14 trey * removed unnecessary #include of Interleave.h * * Revision 1.1 2006/04/27 23:07:24 trey * initial check-in * * ***************************************************************************/ <commit_msg>moved installation of the SIGINT handler to after initialization, so an interrupt during initialization causes the solver to exit immediately<commit_after>/********** tell emacs we use -*- c++ -*- style comments ******************* $Revision: 1.6 $ $Author: trey $ $Date: 2006-06-01 16:49:54 $ @file zmdpSolve.cc @brief No brief Copyright (c) 2002-2006, Trey Smith. 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 <assert.h> #include <sys/time.h> #include <getopt.h> #include <signal.h> #include <iostream> #include <fstream> #include "zmdpCommonTime.h" #include "solverUtils.h" using namespace std; using namespace MatrixUtils; using namespace zmdp; struct OutputParams { const char* outFileName; double timeoutSeconds; OutputParams(void); }; OutputParams::OutputParams(void) { outFileName = "out.policy"; timeoutSeconds = -1; } bool userTerminatedG = false; void sigIntHandler(int sig) { userTerminatedG = true; printf("*** received SIGINT, user pressed control-C ***\n" "terminating run and writing output policy as soon as the solver returns control\n"); fflush(stdout); } void setSignalHandler(int sig, void (*handler)(int)) { struct sigaction act; memset (&act, 0, sizeof(act)); act.sa_handler = handler; act.sa_flags = SA_RESTART; if (-1 == sigaction (sig, &act, NULL)) { cerr << "ERROR: unable to set handler for signal " << sig << endl; exit(EXIT_FAILURE); } } void doSolve(const SolverParams& p, const OutputParams& op) { StopWatch run; init_matrix_utils(); printf("%05d reading model file and allocating data structures\n", (int) run.elapsedTime()); SolverObjects so; constructSolverObjects(so, p); if (!so.bounds->getSupportsPolicyOutput()) { cerr << "ERROR: with selected options, policy output is not supported:" << endl; cerr << " in order to enable policy output, problem must be a POMDP; if" << endl; cout << " it is, try adding the '-v convex' and '--lower-bound' options" << endl; exit(EXIT_FAILURE); } // initialize the solver printf("%05d calculating initial heuristics\n", (int) run.elapsedTime()); so.solver->planInit(so.sim->getModel(), p.targetPrecision); printf("%05d finished initialization, beginning to improve policy\n", (int) run.elapsedTime()); setSignalHandler(SIGINT, &sigIntHandler); double lastPrintTime = -1000; bool reachedTargetPrecision = false; bool reachedTimeout = false; int numSolverCalls = 0; while (!(reachedTargetPrecision || reachedTimeout || userTerminatedG)) { // make a call to the solver reachedTargetPrecision = so.solver->planFixedTime(so.sim->getModel()->getInitialState(), /* maxTime = */ -1, p.targetPrecision); numSolverCalls++; // check timeout double elapsed = run.elapsedTime(); if (op.timeoutSeconds > 0 && elapsed >= op.timeoutSeconds) { reachedTimeout = true; } // print a progress update every 10 seconds if ((elapsed - lastPrintTime > 10) || reachedTargetPrecision || reachedTimeout || userTerminatedG) { ValueInterval intv = so.solver->getValueAt(so.sim->getModel()->getInitialState()); printf("%05d %6d calls to solver, bounds [%8.4f .. %8.4f], precision %g\n", (int) elapsed, numSolverCalls, intv.l, intv.u, (intv.u - intv.l)); lastPrintTime = elapsed; } } // say why the run ended if (reachedTargetPrecision) { printf("%05d terminating run; reached target precision of %g\n", (int) run.elapsedTime(), p.targetPrecision); } else if (reachedTimeout) { printf("%05d terminating run; passed specified timeout of %g seconds\n", (int) run.elapsedTime(), op.timeoutSeconds); } else { printf("%05d terminating run; caught SIGINT from user\n", (int) run.elapsedTime()); } // write out a policy printf("%05d writing policy to '%s'\n", (int) run.elapsedTime(), op.outFileName); so.bounds->writePolicy(op.outFileName); printf("%05d done\n", (int) run.elapsedTime()); } void usage(const char* cmdName) { cerr << "usage: " << cmdName << " OPTIONS <model>\n" " -h or --help Print this help\n" " --version Print version information (CFLAGS used at compilation)\n" "\n" "Solver options:\n" " -s or --search Specifies search strategy. Valid choices:\n" " rtdp, lrtdp, hdp, hsvi, frtdp [default: frtdp]\n" " -t or --type Specifies problem type. Valid choices:\n" " racetrack, pomdp [default: infer from model filename]\n" " -v or --value Specifies value function representation. Valid choices\n" " depend on problem type. With -t pomdp, choices are:\n" " point, convex [default: convex]\n" " For other problem types, choices are:\n" " point [default: point]\n" " -f or --fast Use fast (but very picky) alternate POMDP parser\n" " -p or --precision Set target precision in solution quality; run ends when\n" " target is reached [default: 1e-3]\n" " --weak-heuristic Avoid spending time generating a good upper bound heuristic\n" " (only valid for some problems, interpretation depends on\n" " the problem; e.g. sets h_U = 0 for racetrack)\n" " --lower-bound Forces zmdpSolve to maintain a lower bound and use it for\n" " action selection, even if it is not used during search.\n" " --upper-bound Forces zmdpSolve to use the upper bound for action selection\n" " (normally the lower bound is used if it is available).\n" "\n" "Policy output options:\n" " -o or --output Specifies name of policy output file [default: 'out.policy']\n" " --timeout Specifies a timeout in seconds. If running time exceeds\n" " the specified value, zmdpSolve writes out a policy\n" " and terminates [default: no maximum]\n" "\n" "Examples:\n" " " << cmdName << " RockSample_4_4.pomdp\n" " " << cmdName << " large-b.racetrack\n" " " << cmdName << " --timeout 60 --output my.policy RockSample_4_4.pomdp\n" " " << cmdName << " --search lrtdp --value point RockSample_4_4.pomdp\n" " " << cmdName << " -f RockSample_5_7.pomdp\n" "\n" ; exit(-1); } int main(int argc, char **argv) { static char shortOptions[] = "hs:t:v:fo:"; static struct option longOptions[]={ {"help", 0,NULL,'h'}, {"version", 0,NULL,'V'}, {"search", 1,NULL,'s'}, {"type", 1,NULL,'t'}, {"value", 1,NULL,'v'}, {"fast", 0,NULL,'f'}, {"precision", 1,NULL,'p'}, {"weak-heuristic",0,NULL,'W'}, {"lower-bound", 0,NULL,'L'}, {"upper-bound", 0,NULL,'U'}, {"output", 1,NULL,'o'}, {"timeout", 1,NULL,'T'}, {NULL,0,0,0} }; SolverParams p; OutputParams op; #if USE_DEBUG_PRINT // save arguments for debug printout later ostringstream outs; for (int i=1; i < argc; i++) { outs << argv[i] << " "; } #endif p.cmdName = argv[0]; while (1) { char optchar = getopt_long(argc,argv,shortOptions,longOptions,NULL); if (optchar == -1) break; switch (optchar) { case 'h': // help usage(argv[0]); break; case 'V': // version cout << "CFLAGS = " << CFLAGS << endl; exit(EXIT_SUCCESS); break; case 's': // search p.setStrategy(optarg); break; case 't': // type p.setProbType(optarg); break; case 'v': // value p.setValueRepr(optarg); break; case 'f': // fast p.useFastParser = true; break; case 'p': // precision p.targetPrecision = atof(optarg); break; case 'W': // weak-heuristic p.useHeuristic = false; break; case 'L': // lower-bound p.forceLowerBound = true; break; case 'U': // upper-bound p.forceUpperBoundActionSelection = true; break; case 'o': // output op.outFileName = optarg; break; case 'T': // timeout op.timeoutSeconds = atof(optarg); break; case '?': // unknown option case ':': // option with missing parameter // getopt() prints an informative error message cerr << endl; usage(argv[0]); break; default: abort(); // never reach this point } } if (argc-optind != 1) { cerr << "ERROR: wrong number of arguments (should be 1)" << endl << endl; usage(argv[0]); } p.probName = argv[optind++]; p.inferMissingValues(); #if USE_DEBUG_PRINT printf("CFLAGS = %s\n", CFLAGS); printf("ARGS = %s\n", outs.str().c_str()); fflush(stdout); #endif doSolve(p, op); return 0; } /*************************************************************************** * REVISION HISTORY: * $Log: not supported by cvs2svn $ * Revision 1.5 2006/04/28 20:33:54 trey * added handling of SIGINT * * Revision 1.4 2006/04/28 17:57:41 trey * changed to use apache license * * Revision 1.3 2006/04/27 23:42:54 trey * improved error diagnostic for policy output * * Revision 1.2 2006/04/27 23:19:14 trey * removed unnecessary #include of Interleave.h * * Revision 1.1 2006/04/27 23:07:24 trey * initial check-in * * ***************************************************************************/ <|endoftext|>
<commit_before>#include <iostream> #include <osg/Notify> #include <osg/MatrixTransform> #include <osg/PositionAttitudeTransform> #include <osg/Geometry> #include <osg/Geode> #include <osg/ShapeDrawable> #include <osgUtil/Optimizer> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgProducer/Viewer> osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime) { // set up the animation path osg::AnimationPath* animationPath = new osg::AnimationPath; animationPath->setLoopMode(osg::AnimationPath::LOOP); int numSamples = 40; float yaw = 0.0f; float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f); float roll = osg::inDegrees(30.0f); double time=0.0f; double time_delta = looptime/(double)numSamples; for(int i=0;i<numSamples;++i) { osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f)); osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0))); animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation)); yaw += yaw_delta; time += time_delta; } return animationPath; }// end createAnimationPath osg::MatrixTransform* createEarthTranslationAndTilt( double RorbitEarth, double tiltEarth ) { osg::MatrixTransform* earthPositioned = new osg::MatrixTransform; //earthPositioned->setDataVariance(osg::Object::STATIC); earthPositioned->setMatrix(osg::Matrix::translate(osg::Vec3( 0.0, RorbitEarth, 0.0 ) )* osg::Matrix::scale(1.0, 1.0, 1.0)* osg::Matrix::rotate(osg::inDegrees( tiltEarth ),0.0f,0.0f,1.0f)); return earthPositioned; }// end createEarthTranslationAndTilt osg::MatrixTransform* createRotation( double orbit, double speed ) { osg::Vec3 center( 0.0, 0.0, 0.0 ); float animationLength = 10.0f; osg::AnimationPath* animationPath = createAnimationPath( center, orbit, animationLength ); osg::MatrixTransform* rotation = new osg::MatrixTransform; rotation->setUpdateCallback( new osg::AnimationPathCallback( animationPath, 0.0f, speed ) ); return rotation; }// end createEarthRotation osg::MatrixTransform* createMoonTranslation( double RorbitMoon ) { osg::MatrixTransform* moonPositioned = new osg::MatrixTransform; //earthPositioned->setDataVariance(osg::Object::STATIC); //earthPositioned->setMatrix(osg::Matrix::translate(osg::Vec3( RorbitEarth, 0.0, 0.0 ) )* moonPositioned->setMatrix(osg::Matrix::translate(osg::Vec3( 0.0, RorbitMoon, 0.0 ) )* //earthPositioned->setMatrix(osg::Matrix::translate(osg::Vec3( 0.0, 0.0, RorbitEarth ) )* osg::Matrix::scale(1.0, 1.0, 1.0)* osg::Matrix::rotate(osg::inDegrees(0.0f),0.0f,0.0f,1.0f)); return moonPositioned; }// end createMoonTranslation osg::Geode* createPlanet( double radius, std::string name, osg::Vec4 color ) { // create a cube shape osg::Sphere *planetSphere = new osg::Sphere( osg::Vec3( 0.0, 0.0, 0.0 ), radius ); // create a container that makes the sphere drawable osg::ShapeDrawable *sPlanetSphere = new osg::ShapeDrawable( planetSphere ); // set the object color sPlanetSphere->setColor( color ); // create a geode object to as a container for our drawable sphere object osg::Geode* geodePlanet = new osg::Geode(); geodePlanet->setName( name ); // add our drawable sphere to the geode container geodePlanet->addDrawable( sPlanetSphere ); return( geodePlanet ); }// end createPlanet class SolarSystem { public: double _radiusSun; double _radiusEarth; double _RorbitEarth; double _tiltEarth; double _rotateSpeedEarthAndMoon; double _rotateSpeedEarth; double _radiusMoon; double _RorbitMoon; double _rotateSpeedMoon; SolarSystem( double _radiusSun = 20.0, double _radiusEarth = 10.0, double _RorbitEarth = 100.0, double _tiltEarth = 5.0, double _rotateSpeedEarthAndMoon = 5.0, double _rotateSpeedEarth = 5.0, double _radiusMoon = 2.0, double _RorbitMoon = 20.0, double _rotateSpeedMoon = 5.0 ) {} osg::Group* built() { osg::Group* thisSystem = new osg::Group; // create the sun osg::Node* sun = createPlanet( _radiusSun, "Sun", osg::Vec4( 1.0f, 1.0f, 0.5f, 1.0f) ); // stick sun right under root, no transformations for the sun thisSystem->addChild( sun ); //creating right side of the graph with earth and moon and the rotations above it // create earth and moon osg::Node* earth = createPlanet( _radiusEarth, "Earth", osg::Vec4( 0.0f, 0.0f, 1.0f, 1.0f) ); osg::Node* moon = createPlanet( _radiusMoon, "Moon", osg::Vec4( 1.0f, 1.0f, 1.0f, 1.0f) ); // create transformations for the earthMoonGroup osg::MatrixTransform* aroundSunRotation = createRotation( _RorbitEarth, _rotateSpeedEarthAndMoon ); osg::MatrixTransform* earthPosition = createEarthTranslationAndTilt( _RorbitEarth, _tiltEarth ); //Group with earth and moon under it osg::Group* earthMoonGroup = new osg::Group; //transformation to rotate the earth around itself osg::MatrixTransform* earthRotationAroundItself = createRotation ( 0.0, _rotateSpeedEarth ); //transformations for the moon osg::MatrixTransform* moonAroundEarthXform = createRotation( _RorbitMoon, _rotateSpeedMoon ); osg::MatrixTransform* moonTranslation = createMoonTranslation( _RorbitMoon ); moonTranslation->addChild( moon ); moonAroundEarthXform->addChild( moonTranslation ); earthMoonGroup->addChild( moonAroundEarthXform ); earthRotationAroundItself->addChild( earth ); earthMoonGroup->addChild( earthRotationAroundItself ); earthPosition->addChild( earthMoonGroup ); aroundSunRotation->addChild( earthPosition ); thisSystem->addChild( aroundSunRotation ); return( thisSystem ); } void printParameters() { std::cout << "radiusSun\t= " << _radiusSun << std::endl; std::cout << "radiusEarth\t= " << _radiusEarth << std::endl; std::cout << "RorbitEarth\t= " << _RorbitEarth << std::endl; std::cout << "tiltEarth\t= " << _tiltEarth << std::endl; std::cout << "rotateSpeedEarthAndMoon= " << _rotateSpeedEarthAndMoon << std::endl; std::cout << "rotateSpeedEarth= " << _rotateSpeedEarth << std::endl; std::cout << "radiusMoon\t= " << _radiusMoon << std::endl; std::cout << "RorbitMoon\t= " << _RorbitMoon << std::endl; std::cout << "rotateSpeedMoon\t= " << _rotateSpeedMoon << std::endl; } }; // end SolarSystem int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of osg::AnimationPath and UpdateCallbacks for adding animation to your scenes."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); // initialize the viewer. osgProducer::Viewer viewer(arguments); // set up the value with sensible default event handlers. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); SolarSystem solarSystem; while (arguments.read("--radiusSun",solarSystem._radiusSun)) { } while (arguments.read("--radiusEarth",solarSystem._radiusEarth)) { } while (arguments.read("--RorbitEarth",solarSystem._RorbitEarth)) { } while (arguments.read("--tiltEarth",solarSystem._tiltEarth)) { } while (arguments.read("--rotateSpeedEarthAndMoon",solarSystem._rotateSpeedEarthAndMoon)) { } while (arguments.read("--rotateSpeedEarth",solarSystem._rotateSpeedEarth)) { } while (arguments.read("--radiusMoon",solarSystem._radiusMoon)) { } while (arguments.read("--RorbitMoon",solarSystem._RorbitMoon)) { } while (arguments.read("--rotateSpeedMoon",solarSystem._rotateSpeedMoon)) { } // solarSystem.printParameters(); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { std::cout << "setup the following arguments: " << std::endl; std::cout << "--radiusSun: double" << std::endl; std::cout << "--radiusEarth: double" << std::endl; std::cout << "--RorbitEarth: double" << std::endl; std::cout << "--tiltEarth: double" << std::endl; std::cout << "--rotateSpeedEarthAndMoon: double" << std::endl; std::cout << "--rotateSpeedEarth: double" << std::endl; std::cout << "--radiusMoon: double" << std::endl; std::cout << "--RorbitMoon: double" << std::endl; std::cout << "--rotateSpeedMoon: double" << std::endl; return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } osg::Group* root = solarSystem.built(); /* // tilt the scene so the default eye position is looking down on the model. osg::MatrixTransform* rootnode = new osg::MatrixTransform; rootnode->setMatrix(osg::Matrix::rotate(osg::inDegrees(30.0f),1.0f,0.0f,0.0f)); rootnode->addChild(model); */ // run optimization over the scene graph osgUtil::Optimizer optimzer; optimzer.optimize( root ); // set the scene to render viewer.setSceneData( root ); // create the windows and run the threads. viewer.realize(); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } // wait for all cull and draw threads to complete before exit. viewer.sync(); return 0; } <commit_msg>From Rainer, updates to osgplanet.<commit_after>#include <iostream> #include <osg/Notify> #include <osg/MatrixTransform> #include <osg/PositionAttitudeTransform> #include <osg/Geometry> #include <osg/Geode> #include <osg/ShapeDrawable> #include <osg/Texture2D> #include <osgUtil/Optimizer> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgProducer/Viewer> osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime) { // set up the animation path osg::AnimationPath* animationPath = new osg::AnimationPath; animationPath->setLoopMode(osg::AnimationPath::LOOP); int numSamples = 40; float yaw = 0.0f; float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f); float roll = osg::inDegrees(30.0f); double time=0.0f; double time_delta = looptime/(double)numSamples; for(int i=0;i<numSamples;++i) { osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f)); osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0))); animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation)); yaw += yaw_delta; time += time_delta; } return animationPath; }// end createAnimationPath osg::MatrixTransform* createEarthTranslationAndTilt( double RorbitEarth, double tiltEarth ) { osg::MatrixTransform* earthPositioned = new osg::MatrixTransform; //earthPositioned->setDataVariance(osg::Object::STATIC); earthPositioned->setMatrix(osg::Matrix::translate(osg::Vec3( 0.0, RorbitEarth, 0.0 ) )* osg::Matrix::scale(1.0, 1.0, 1.0)* osg::Matrix::rotate(osg::inDegrees( tiltEarth ),0.0f,0.0f,1.0f)); return earthPositioned; }// end createEarthTranslationAndTilt osg::MatrixTransform* createRotation( double orbit, double speed ) { osg::Vec3 center( 0.0, 0.0, 0.0 ); float animationLength = 10.0f; osg::AnimationPath* animationPath = createAnimationPath( center, orbit, animationLength ); osg::MatrixTransform* rotation = new osg::MatrixTransform; rotation->setUpdateCallback( new osg::AnimationPathCallback( animationPath, 0.0f, speed ) ); return rotation; }// end createEarthRotation osg::MatrixTransform* createMoonTranslation( double RorbitMoon ) { osg::MatrixTransform* moonPositioned = new osg::MatrixTransform; //earthPositioned->setDataVariance(osg::Object::STATIC); //earthPositioned->setMatrix(osg::Matrix::translate(osg::Vec3( RorbitEarth, 0.0, 0.0 ) )* moonPositioned->setMatrix(osg::Matrix::translate(osg::Vec3( 0.0, RorbitMoon, 0.0 ) )* //earthPositioned->setMatrix(osg::Matrix::translate(osg::Vec3( 0.0, 0.0, RorbitEarth ) )* osg::Matrix::scale(1.0, 1.0, 1.0)* osg::Matrix::rotate(osg::inDegrees(0.0f),0.0f,0.0f,1.0f)); return moonPositioned; }// end createMoonTranslation osg::Geode* createPlanet( double radius, const std::string& name, const osg::Vec4& color , const std::string& textureName ) { // create a cube shape osg::Sphere *planetSphere = new osg::Sphere( osg::Vec3( 0.0, 0.0, 0.0 ), radius ); // create a container that makes the sphere drawable osg::ShapeDrawable *sPlanetSphere = new osg::ShapeDrawable( planetSphere ); // set the object color sPlanetSphere->setColor( color ); if( !textureName.empty() ) { osg::Image* image = osgDB::readImageFile( textureName ); if ( image ) { sPlanetSphere->getOrCreateStateSet()->setTextureAttributeAndModes( 0, new osg::Texture2D( image ), osg::StateAttribute::ON ); // reset the object color to white to allow the texture to set the colour. sPlanetSphere->setColor( osg::Vec4(1.0f,1.0f,1.0f,1.0f) ); } } // create a geode object to as a container for our drawable sphere object osg::Geode* geodePlanet = new osg::Geode(); geodePlanet->setName( name ); // add our drawable sphere to the geode container geodePlanet->addDrawable( sPlanetSphere ); return( geodePlanet ); }// end createPlanet //--radiusSun 5.0 --radiusEarth 2.0 --RorbitEarth 10.0 --RorbitMoon 2.0 --radiusMoon 0.5 --tiltEarth 18.0 --rotateSpeedEarth 1.0 //--rotateSpeedMoon 1.0 --rotateSpeedEarthAndMoon 1.0 class SolarSystem { public: double _radiusSun; double _radiusEarth; double _RorbitEarth; double _tiltEarth; double _rotateSpeedEarthAndMoon; double _rotateSpeedEarth; double _radiusMoon; double _RorbitMoon; double _rotateSpeedMoon; SolarSystem() { _radiusSun = 5.0; _radiusEarth = 2.0; _RorbitEarth = 10.0; _tiltEarth = 18.0; _rotateSpeedEarthAndMoon = 1.0; _rotateSpeedEarth = 1.0; _radiusMoon = 0.5; _RorbitMoon = 2.0; _rotateSpeedMoon = 1.0; } osg::Group* built() { osg::Group* thisSystem = new osg::Group; // create the sun osg::Node* sun = createPlanet( _radiusSun, "Sun", osg::Vec4( 1.0f, 1.0f, 0.5f, 1.0f), "" ); // stick sun right under root, no transformations for the sun thisSystem->addChild( sun ); //creating right side of the graph with earth and moon and the rotations above it // create earth and moon osg::Node* earth = createPlanet( _radiusEarth, "Earth", osg::Vec4( 0.0f, 0.0f, 1.0f, 1.0f), "Images/land_shallow_topo_2048.jpg" ); osg::Node* moon = createPlanet( _radiusMoon, "Moon", osg::Vec4( 1.0f, 1.0f, 1.0f, 1.0f), "Images/moon256128.TGA" ); // create transformations for the earthMoonGroup osg::MatrixTransform* aroundSunRotation = createRotation( _RorbitEarth, _rotateSpeedEarthAndMoon ); osg::MatrixTransform* earthPosition = createEarthTranslationAndTilt( _RorbitEarth, _tiltEarth ); //Group with earth and moon under it osg::Group* earthMoonGroup = new osg::Group; //transformation to rotate the earth around itself osg::MatrixTransform* earthRotationAroundItself = createRotation ( 0.0, _rotateSpeedEarth ); //transformations for the moon osg::MatrixTransform* moonAroundEarthXform = createRotation( _RorbitMoon, _rotateSpeedMoon ); osg::MatrixTransform* moonTranslation = createMoonTranslation( _RorbitMoon ); moonTranslation->addChild( moon ); moonAroundEarthXform->addChild( moonTranslation ); earthMoonGroup->addChild( moonAroundEarthXform ); earthRotationAroundItself->addChild( earth ); earthMoonGroup->addChild( earthRotationAroundItself ); earthPosition->addChild( earthMoonGroup ); aroundSunRotation->addChild( earthPosition ); thisSystem->addChild( aroundSunRotation ); return( thisSystem ); } void printParameters() { std::cout << "radiusSun\t= " << _radiusSun << std::endl; std::cout << "radiusEarth\t= " << _radiusEarth << std::endl; std::cout << "RorbitEarth\t= " << _RorbitEarth << std::endl; std::cout << "tiltEarth\t= " << _tiltEarth << std::endl; std::cout << "rotateSpeedEarthAndMoon= " << _rotateSpeedEarthAndMoon << std::endl; std::cout << "rotateSpeedEarth= " << _rotateSpeedEarth << std::endl; std::cout << "radiusMoon\t= " << _radiusMoon << std::endl; std::cout << "RorbitMoon\t= " << _RorbitMoon << std::endl; std::cout << "rotateSpeedMoon\t= " << _rotateSpeedMoon << std::endl; } }; // end SolarSystem int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of osg::AnimationPath and UpdateCallbacks for adding animation to your scenes."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); // initialize the viewer. osgProducer::Viewer viewer(arguments); // set up the value with sensible default event handlers. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); SolarSystem solarSystem; while (arguments.read("--radiusSun",solarSystem._radiusSun)) { } while (arguments.read("--radiusEarth",solarSystem._radiusEarth)) { } while (arguments.read("--RorbitEarth",solarSystem._RorbitEarth)) { } while (arguments.read("--tiltEarth",solarSystem._tiltEarth)) { } while (arguments.read("--rotateSpeedEarthAndMoon",solarSystem._rotateSpeedEarthAndMoon)) { } while (arguments.read("--rotateSpeedEarth",solarSystem._rotateSpeedEarth)) { } while (arguments.read("--radiusMoon",solarSystem._radiusMoon)) { } while (arguments.read("--RorbitMoon",solarSystem._RorbitMoon)) { } while (arguments.read("--rotateSpeedMoon",solarSystem._rotateSpeedMoon)) { } solarSystem.printParameters(); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { std::cout << "setup the following arguments: " << std::endl; std::cout << "--radiusSun: double" << std::endl; std::cout << "--radiusEarth: double" << std::endl; std::cout << "--RorbitEarth: double" << std::endl; std::cout << "--tiltEarth: double" << std::endl; std::cout << "--rotateSpeedEarthAndMoon: double" << std::endl; std::cout << "--rotateSpeedEarth: double" << std::endl; std::cout << "--radiusMoon: double" << std::endl; std::cout << "--RorbitMoon: double" << std::endl; std::cout << "--rotateSpeedMoon: double" << std::endl; return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } osg::Group* root = solarSystem.built(); /* // tilt the scene so the default eye position is looking down on the model. osg::MatrixTransform* rootnode = new osg::MatrixTransform; rootnode->setMatrix(osg::Matrix::rotate(osg::inDegrees(30.0f),1.0f,0.0f,0.0f)); rootnode->addChild(model); */ // run optimization over the scene graph osgUtil::Optimizer optimzer; optimzer.optimize( root ); // set the scene to render viewer.setSceneData( root ); // create the windows and run the threads. viewer.realize(); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } // wait for all cull and draw threads to complete before exit. viewer.sync(); return 0; } <|endoftext|>
<commit_before><commit_msg>Fixed bug in transaction test<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: datalock.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 03:46:50 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONFIGMGR_DATALOCK_HXX #define CONFIGMGR_DATALOCK_HXX namespace configmgr { // ----------------------------------------------------------------------------- namespace memory { // ------------------------------------------------------------------------- /// class controlling access to a memory::Segment struct DataLock { virtual void acquireReadAccess() = 0; virtual void releaseReadAccess() = 0; virtual void acquireWriteAccess() = 0; virtual void releaseWriteAccess() = 0; protected: virtual ~DataLock() {} }; // ------------------------------------------------------------------------- } // ----------------------------------------------------------------------------- } // namespace configmgr #endif // CONFIGMGR_DATALOCK_HXX <commit_msg>INTEGRATION: CWS configrefactor01 (1.3.84); FILE MERGED 2007/10/11 16:14:08 mmeeks 1.3.84.3: Issue number: i#82311# Submitted by: mmeeks Add threaded unit tests, fix locking issues in apitreeimplobj.cxx Add UnoApiLockClearable, and UnoApiLockReleaser (prolly needed for the next tests) 2007/01/16 12:18:20 mmeeks 1.3.84.2: Submitted by: mmeeks Kill 'memory::Segment' - no longer needed. Bin some other (empty / redundant) headers. 2007/01/08 20:48:54 mmeeks 1.3.84.1: Issue number: Submitted by: mmeeks Substantial configmgr re-factoring #1 ... + remove endless typedef chains + remove custom allocator & associated complexity + remove Pointer, and 'Address' classes<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: datalock.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: ihi $ $Date: 2007-11-23 14:18:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONFIGMGR_DATALOCK_HXX_ #define CONFIGMGR_DATALOCK_HXX_ #include <osl/mutex.hxx> namespace configmgr { class UnoApiLock { static osl::Mutex aCoreLock; public: static volatile oslInterlockedCount nHeld; UnoApiLock() { acquire(); } ~UnoApiLock() { release(); } static osl::Mutex &getLock() { return aCoreLock; } static void acquire() { aCoreLock.acquire(); nHeld++; } static void release() { nHeld--; aCoreLock.release(); } static bool isHeld() { return nHeld != 0; } }; class UnoApiLockReleaser { oslInterlockedCount mnCount; public: UnoApiLockReleaser(); ~UnoApiLockReleaser(); }; class UnoApiLockClearable : public UnoApiLock { bool mbSet; public: UnoApiLockClearable() : mbSet(true) { acquire(); } ~UnoApiLockClearable() { clear(); } void clear() { if (mbSet) { mbSet = false; release(); } } }; } using configmgr::UnoApiLock; #endif // CONFIGMGR_DATALOCK_HXX_ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xexch.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: ka $ $Date: 2001-06-22 15:46:24 $ * * 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 --------------------------------------------------------------- #include <sot/formats.hxx> #include <tools/vcompat.hxx> #ifndef _SVX_XFLASIT_HXX #include <xflasit.hxx> #endif #ifndef SVX_XFILLIT0_HXX #include <xfillit0.hxx> #endif #ifndef _SFXIPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SFX_WHITER_HXX #include <svtools/whiter.hxx> #endif #ifndef _SFXIPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #include "xdef.hxx" #include "xexch.hxx" TYPEINIT1_AUTOFACTORY( XFillExchangeData, SvDataCopyStream ); /************************************************************************* |* |* Default-Ctor (Fuer Assign()) |* *************************************************************************/ XFillExchangeData::XFillExchangeData() : pPool( NULL ), pXFillAttrSetItem( NULL ) { } /************************************************************************* |* |* Ctor |* *************************************************************************/ XFillExchangeData::XFillExchangeData( const XFillAttrSetItem rXFillAttrSetItem ) : pPool( rXFillAttrSetItem.GetItemSet().GetPool() ), pXFillAttrSetItem( (XFillAttrSetItem*) rXFillAttrSetItem.Clone( rXFillAttrSetItem.GetItemSet().GetPool() ) ) { } /************************************************************************* |* |* Dtor |* *************************************************************************/ XFillExchangeData::~XFillExchangeData() { delete pXFillAttrSetItem; } /************************************************************************* |* |* |* *************************************************************************/ ULONG XFillExchangeData::RegisterClipboardFormatName() { return( SOT_FORMATSTR_ID_XFA ); } /****************************************************************************** |* |* Binaer-Export (z.Z. ohne Versionsverwaltung, da nicht persistent!) |* \******************************************************************************/ SvStream& operator<<( SvStream& rOStm, const XFillExchangeData& rData ) { if( rData.pXFillAttrSetItem ) { USHORT nItemVersion = rData.pXFillAttrSetItem->GetVersion( (USHORT) rOStm.GetVersion() ); SfxWhichIter aIter( rData.pXFillAttrSetItem->GetItemSet() ); USHORT nWhich = aIter.FirstWhich(); const SfxPoolItem* pItem; ULONG nItemCount = 0, nFirstPos = rOStm.Tell(); rOStm << nItemCount; while( nWhich ) { if( SFX_ITEM_SET == rData.pXFillAttrSetItem->GetItemSet().GetItemState( nWhich, FALSE, &pItem ) ) { VersionCompat aCompat( rOStm, STREAM_WRITE ); const USHORT nItemVersion = pItem->GetVersion( (USHORT) rOStm.GetVersion() ); rOStm << nWhich << nItemVersion; pItem->Store( rOStm, nItemVersion ); nItemCount++; } nWhich = aIter.NextWhich(); } const ULONG nLastPos = rOStm.Tell(); rOStm.Seek( nFirstPos ); rOStm << nItemCount; rOStm.Seek( nLastPos ); } return rOStm; } /****************************************************************************** |* |* Binaer-Import (z.Z. ohne Versionsverwaltung, da nicht persistent!) |* \******************************************************************************/ SvStream& operator>>( SvStream& rIStm, XFillExchangeData& rData ) { DBG_ASSERT( rData.pPool, "XFillExchangeData has no pool" ); SfxItemSet* pSet = new SfxItemSet ( *rData.pPool, XATTR_FILL_FIRST, XATTR_FILL_LAST ); SfxPoolItem* pNewItem; ULONG nItemCount = 0; USHORT nWhich, nItemVersion; rIStm >> nItemCount; if( nItemCount > ( XATTR_FILL_LAST - XATTR_FILL_FIRST + 1 ) ) nItemCount = ( XATTR_FILL_LAST - XATTR_FILL_FIRST + 1 ); for( ULONG i = 0; i < nItemCount; i++ ) { VersionCompat aCompat( rIStm, STREAM_READ ); rIStm >> nWhich >> nItemVersion; if( nWhich ) { pNewItem = rData.pPool->GetDefaultItem( nWhich ).Create( rIStm, nItemVersion ); if( pNewItem ) { pSet->Put( *pNewItem ); delete pNewItem; } } } delete rData.pXFillAttrSetItem; rData.pXFillAttrSetItem = new XFillAttrSetItem( pSet ); rData.pPool = rData.pXFillAttrSetItem->GetItemSet().GetPool(); return rIStm; } /************************************************************************* |* |* XBitmap& XBitmap::operator=( const XBitmap& rXBmp ) |* *************************************************************************/ XFillExchangeData& XFillExchangeData::operator=( const XFillExchangeData& rData ) { delete pXFillAttrSetItem; if( rData.pXFillAttrSetItem ) pXFillAttrSetItem = (XFillAttrSetItem*) rData.pXFillAttrSetItem->Clone( pPool = rData.pXFillAttrSetItem->GetItemSet().GetPool() ); else { pPool = NULL; pXFillAttrSetItem = NULL; } return( *this ); } <commit_msg>INTEGRATION: CWS ooo19126 (1.3.1654); FILE MERGED 2005/09/05 14:28:29 rt 1.3.1654.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xexch.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:19:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // include --------------------------------------------------------------- #include <sot/formats.hxx> #include <tools/vcompat.hxx> #ifndef _SVX_XFLASIT_HXX #include <xflasit.hxx> #endif #ifndef SVX_XFILLIT0_HXX #include <xfillit0.hxx> #endif #ifndef _SFXIPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SFX_WHITER_HXX #include <svtools/whiter.hxx> #endif #ifndef _SFXIPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #include "xdef.hxx" #include "xexch.hxx" TYPEINIT1_AUTOFACTORY( XFillExchangeData, SvDataCopyStream ); /************************************************************************* |* |* Default-Ctor (Fuer Assign()) |* *************************************************************************/ XFillExchangeData::XFillExchangeData() : pPool( NULL ), pXFillAttrSetItem( NULL ) { } /************************************************************************* |* |* Ctor |* *************************************************************************/ XFillExchangeData::XFillExchangeData( const XFillAttrSetItem rXFillAttrSetItem ) : pPool( rXFillAttrSetItem.GetItemSet().GetPool() ), pXFillAttrSetItem( (XFillAttrSetItem*) rXFillAttrSetItem.Clone( rXFillAttrSetItem.GetItemSet().GetPool() ) ) { } /************************************************************************* |* |* Dtor |* *************************************************************************/ XFillExchangeData::~XFillExchangeData() { delete pXFillAttrSetItem; } /************************************************************************* |* |* |* *************************************************************************/ ULONG XFillExchangeData::RegisterClipboardFormatName() { return( SOT_FORMATSTR_ID_XFA ); } /****************************************************************************** |* |* Binaer-Export (z.Z. ohne Versionsverwaltung, da nicht persistent!) |* \******************************************************************************/ SvStream& operator<<( SvStream& rOStm, const XFillExchangeData& rData ) { if( rData.pXFillAttrSetItem ) { USHORT nItemVersion = rData.pXFillAttrSetItem->GetVersion( (USHORT) rOStm.GetVersion() ); SfxWhichIter aIter( rData.pXFillAttrSetItem->GetItemSet() ); USHORT nWhich = aIter.FirstWhich(); const SfxPoolItem* pItem; ULONG nItemCount = 0, nFirstPos = rOStm.Tell(); rOStm << nItemCount; while( nWhich ) { if( SFX_ITEM_SET == rData.pXFillAttrSetItem->GetItemSet().GetItemState( nWhich, FALSE, &pItem ) ) { VersionCompat aCompat( rOStm, STREAM_WRITE ); const USHORT nItemVersion = pItem->GetVersion( (USHORT) rOStm.GetVersion() ); rOStm << nWhich << nItemVersion; pItem->Store( rOStm, nItemVersion ); nItemCount++; } nWhich = aIter.NextWhich(); } const ULONG nLastPos = rOStm.Tell(); rOStm.Seek( nFirstPos ); rOStm << nItemCount; rOStm.Seek( nLastPos ); } return rOStm; } /****************************************************************************** |* |* Binaer-Import (z.Z. ohne Versionsverwaltung, da nicht persistent!) |* \******************************************************************************/ SvStream& operator>>( SvStream& rIStm, XFillExchangeData& rData ) { DBG_ASSERT( rData.pPool, "XFillExchangeData has no pool" ); SfxItemSet* pSet = new SfxItemSet ( *rData.pPool, XATTR_FILL_FIRST, XATTR_FILL_LAST ); SfxPoolItem* pNewItem; ULONG nItemCount = 0; USHORT nWhich, nItemVersion; rIStm >> nItemCount; if( nItemCount > ( XATTR_FILL_LAST - XATTR_FILL_FIRST + 1 ) ) nItemCount = ( XATTR_FILL_LAST - XATTR_FILL_FIRST + 1 ); for( ULONG i = 0; i < nItemCount; i++ ) { VersionCompat aCompat( rIStm, STREAM_READ ); rIStm >> nWhich >> nItemVersion; if( nWhich ) { pNewItem = rData.pPool->GetDefaultItem( nWhich ).Create( rIStm, nItemVersion ); if( pNewItem ) { pSet->Put( *pNewItem ); delete pNewItem; } } } delete rData.pXFillAttrSetItem; rData.pXFillAttrSetItem = new XFillAttrSetItem( pSet ); rData.pPool = rData.pXFillAttrSetItem->GetItemSet().GetPool(); return rIStm; } /************************************************************************* |* |* XBitmap& XBitmap::operator=( const XBitmap& rXBmp ) |* *************************************************************************/ XFillExchangeData& XFillExchangeData::operator=( const XFillExchangeData& rData ) { delete pXFillAttrSetItem; if( rData.pXFillAttrSetItem ) pXFillAttrSetItem = (XFillAttrSetItem*) rData.pXFillAttrSetItem->Clone( pPool = rData.pXFillAttrSetItem->GetItemSet().GetPool() ); else { pPool = NULL; pXFillAttrSetItem = NULL; } return( *this ); } <|endoftext|>
<commit_before>void runProtonAnalysisQA() { TStopwatch timer; timer.Start(); runProof(200000,"/COMMON/COMMON/LHC08c11_10TeV_0.5T"); //use data sets //runProof(200); //use ascii files timer.Stop(); timer.Print(); } //_________________________________________________// void runProof(Int_t stats = 0, const char* dataset = 0x0) { TStopwatch timer; timer.Start(); TString outputFilename1 = "Protons.QA.root"; TString outputFilename2 = "Protons.MC.QA.root"; TString outputFilename3 = "Protons.QA.Histograms.root"; printf("****** Connect to PROOF *******\n"); TProof::Open("alicecaf.cern.ch"); gProof->SetParallel(); // Enable the Analysis Package gProof->UploadPackage("STEERBase.par"); gProof->EnablePackage("STEERBase"); gProof->UploadPackage("ESD.par"); gProof->EnablePackage("ESD"); gProof->UploadPackage("AOD.par"); gProof->EnablePackage("AOD"); gProof->UploadPackage("ANALYSIS.par"); gProof->EnablePackage("ANALYSIS"); gProof->UploadPackage("ANALYSISalice.par"); gProof->EnablePackage("ANALYSISalice"); gProof->UploadPackage("CORRFW.par"); gProof->EnablePackage("CORRFW"); gProof->UploadPackage("PWG2spectra.par"); gProof->EnablePackage("PWG2spectra"); gProof->Load("AliAnalysisTaskProtonsQA.cxx++"); //____________________________________________// // Make the analysis manager AliAnalysisManager *mgr = new AliAnalysisManager("TestManager"); AliVEventHandler* esdH = new AliESDInputHandler; mgr->SetInputEventHandler(esdH); AliMCEventHandler *mc = new AliMCEventHandler(); mgr->SetMCtruthEventHandler(mc); //____________________________________________// // 1st Proton task AliAnalysisTaskProtonsQA *taskProtonsQA = new AliAnalysisTaskProtonsQA("TaskProtonsQA"); mgr->AddTask(taskProtonsQA); // Create containers for input/output AliAnalysisDataContainer *cinput1 = mgr->CreateContainer("dataChain", TChain::Class(), AliAnalysisManager::kInputContainer); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("globalQAList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename1.Data()); AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("pdgCodeList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename2.Data()); AliAnalysisDataContainer *coutput3 = mgr->CreateContainer("mcProcessList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename2.Data()); AliAnalysisDataContainer *coutput4 = mgr->CreateContainer("acceptedCutList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename3.Data()); AliAnalysisDataContainer *coutput5 = mgr->CreateContainer("acceptedDCAList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename3.Data()); //____________________________________________// mgr->ConnectInput(taskProtonsQA,0,cinput1); mgr->ConnectOutput(taskProtonsQA,0,coutput1); mgr->ConnectOutput(taskProtonsQA,1,coutput2); mgr->ConnectOutput(taskProtonsQA,2,coutput3); mgr->ConnectOutput(taskProtonsQA,3,coutput4); mgr->ConnectOutput(taskProtonsQA,4,coutput5); if (!mgr->InitAnalysis()) return; mgr->PrintStatus(); if(dataset) mgr->StartAnalysis("proof",dataset,stats); else { // You should get this macro and the txt file from: // http://aliceinfo.cern.ch/Offline/Analysis/CAF/ gROOT->LoadMacro("CreateESDChain.C"); TChain* chain = 0x0; chain = CreateESDChain("ESD82XX_30K.txt",stats); chain->SetBranchStatus("*Calo*",0); mgr->StartAnalysis("proof",chain); //mgr->StartAnalysis("local",chain); } timer.Stop(); timer.Print(); } //_________________________________________________// Int_t setupPar(const char* pararchivename) { /////////////////// // Setup PAR File// /////////////////// if (pararchivename) { char processline[1024]; sprintf(processline,".! tar xvzf %s.par",pararchivename); gROOT->ProcessLine(processline); const char* ocwd = gSystem->WorkingDirectory(); gSystem->ChangeDirectory(pararchivename); // check for BUILD.sh and execute if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) { printf("*******************************\n"); printf("*** Building PAR archive ***\n"); printf("*******************************\n"); if (gSystem->Exec("PROOF-INF/BUILD.sh")) { Error("runAnalysis","Cannot Build the PAR Archive! - Abort!"); return -1; } } // check for SETUP.C and execute if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) { printf("*******************************\n"); printf("*** Setup PAR archive ***\n"); printf("*******************************\n"); gROOT->Macro("PROOF-INF/SETUP.C"); } gSystem->ChangeDirectory("../"); } return 1; } <commit_msg>Adding the file that didn't want to be added - sorry<commit_after>void runProtonAnalysisQA() { TStopwatch timer; timer.Start(); runProof(200000,"/COMMON/COMMON/LHC08c11_10TeV_0.5T"); //use data sets //runInteractive("wn.xml"); timer.Stop(); timer.Print(); } //_________________________________________________// void runInteractive(const char *collectionfile) { TString outputFilename1 = "Protons.QA.root"; TString outputFilename2 = "Protons.MC.QA.root"; TString outputFilename3 = "Protons.QA.Histograms.root"; TString outputFilename4 = "Protons.Efficiency.root"; TGrid::Connect("alien://"); //Setup the par files setupPar("STEERBase"); gSystem->Load("libSTEERBase.so"); setupPar("ESD"); gSystem->Load("libESD.so"); setupPar("AOD"); gSystem->Load("libAOD.so"); setupPar("ANALYSIS"); gSystem->Load("libANALYSIS.so"); setupPar("ANALYSISalice"); gSystem->Load("libANALYSISalice.so"); setupPar("CORRFW"); gSystem->Load("libCORRFW.so"); setupPar("PWG2spectra"); gSystem->Load("libPWG2spectra.so"); gROOT->LoadMacro("AliAnalysisTaskProtonsQA.cxx+"); //____________________________________________// //Usage of event tags AliTagAnalysis *analysis = new AliTagAnalysis(); TChain *chain = 0x0; chain = analysis->GetChainFromCollection(collectionfile,"esdTree"); //____________________________________________// // Make the analysis manager AliAnalysisManager *mgr = new AliAnalysisManager("TestManager"); AliVEventHandler* esdH = new AliESDInputHandler; mgr->SetInputEventHandler(esdH); AliMCEventHandler *mc = new AliMCEventHandler(); mgr->SetMCtruthEventHandler(mc); //____________________________________________// // 1st Proton task AliAnalysisTaskProtonsQA *taskProtonsQA = new AliAnalysisTaskProtonsQA("TaskProtonsQA"); mgr->AddTask(taskProtonsQA); // Create containers for input/output AliAnalysisDataContainer *cinput1 = mgr->CreateContainer("dataChain", TChain::Class(), AliAnalysisManager::kInputContainer); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("globalQAList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename1.Data()); AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("pdgCodeList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename2.Data()); AliAnalysisDataContainer *coutput3 = mgr->CreateContainer("mcProcessList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename2.Data()); AliAnalysisDataContainer *coutput4 = mgr->CreateContainer("acceptedCutList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename3.Data()); AliAnalysisDataContainer *coutput5 = mgr->CreateContainer("acceptedDCAList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename3.Data()); AliAnalysisDataContainer *coutput6 = mgr->CreateContainer("efficiencyList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename4.Data()); //____________________________________________// mgr->ConnectInput(taskProtonsQA,0,cinput1); mgr->ConnectOutput(taskProtonsQA,0,coutput1); mgr->ConnectOutput(taskProtonsQA,1,coutput2); mgr->ConnectOutput(taskProtonsQA,2,coutput3); mgr->ConnectOutput(taskProtonsQA,3,coutput4); mgr->ConnectOutput(taskProtonsQA,4,coutput5); mgr->ConnectOutput(taskProtonsQA,5,coutput6); if (!mgr->InitAnalysis()) return; mgr->PrintStatus(); mgr->StartAnalysis("local",chain); } //_________________________________________________// void runProof(Int_t stats = 0, const char* dataset = 0x0) { TString outputFilename1 = "Protons.QA.root"; TString outputFilename2 = "Protons.MC.QA.root"; TString outputFilename3 = "Protons.QA.Histograms.root"; TString outputFilename4 = "Protons.Efficiency.root"; printf("****** Connect to PROOF *******\n"); TProof::Open("alicecaf.cern.ch"); gProof->SetParallel(); // Enable the Analysis Package gProof->UploadPackage("STEERBase.par"); gProof->EnablePackage("STEERBase"); gProof->UploadPackage("ESD.par"); gProof->EnablePackage("ESD"); gProof->UploadPackage("AOD.par"); gProof->EnablePackage("AOD"); gProof->UploadPackage("ANALYSIS.par"); gProof->EnablePackage("ANALYSIS"); gProof->UploadPackage("ANALYSISalice.par"); gProof->EnablePackage("ANALYSISalice"); gProof->UploadPackage("CORRFW.par"); gProof->EnablePackage("CORRFW"); gProof->UploadPackage("PWG2spectra.par"); gProof->EnablePackage("PWG2spectra"); gProof->Load("AliAnalysisTaskProtonsQA.cxx++"); //____________________________________________// // Make the analysis manager AliAnalysisManager *mgr = new AliAnalysisManager("TestManager"); AliVEventHandler* esdH = new AliESDInputHandler; mgr->SetInputEventHandler(esdH); AliMCEventHandler *mc = new AliMCEventHandler(); mgr->SetMCtruthEventHandler(mc); //____________________________________________// // 1st Proton task AliAnalysisTaskProtonsQA *taskProtonsQA = new AliAnalysisTaskProtonsQA("TaskProtonsQA"); mgr->AddTask(taskProtonsQA); // Create containers for input/output AliAnalysisDataContainer *cinput1 = mgr->CreateContainer("dataChain", TChain::Class(), AliAnalysisManager::kInputContainer); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("globalQAList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename1.Data()); AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("pdgCodeList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename2.Data()); AliAnalysisDataContainer *coutput3 = mgr->CreateContainer("mcProcessList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename2.Data()); AliAnalysisDataContainer *coutput4 = mgr->CreateContainer("acceptedCutList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename3.Data()); AliAnalysisDataContainer *coutput5 = mgr->CreateContainer("acceptedDCAList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename3.Data()); AliAnalysisDataContainer *coutput6 = mgr->CreateContainer("efficiencyList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFilename4.Data()); //____________________________________________// mgr->ConnectInput(taskProtonsQA,0,cinput1); mgr->ConnectOutput(taskProtonsQA,0,coutput1); mgr->ConnectOutput(taskProtonsQA,1,coutput2); mgr->ConnectOutput(taskProtonsQA,2,coutput3); mgr->ConnectOutput(taskProtonsQA,3,coutput4); mgr->ConnectOutput(taskProtonsQA,4,coutput5); mgr->ConnectOutput(taskProtonsQA,5,coutput6); if (!mgr->InitAnalysis()) return; mgr->PrintStatus(); if(dataset) mgr->StartAnalysis("proof",dataset,stats); else { // You should get this macro and the txt file from: // http://aliceinfo.cern.ch/Offline/Analysis/CAF/ gROOT->LoadMacro("CreateESDChain.C"); TChain* chain = 0x0; chain = CreateESDChain("ESD82XX_30K.txt",stats); chain->SetBranchStatus("*Calo*",0); mgr->StartAnalysis("proof",chain); //mgr->StartAnalysis("local",chain); } } //_________________________________________________// Int_t setupPar(const char* pararchivename) { /////////////////// // Setup PAR File// /////////////////// if (pararchivename) { char processline[1024]; sprintf(processline,".! tar xvzf %s.par",pararchivename); gROOT->ProcessLine(processline); const char* ocwd = gSystem->WorkingDirectory(); gSystem->ChangeDirectory(pararchivename); // check for BUILD.sh and execute if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) { printf("*******************************\n"); printf("*** Building PAR archive ***\n"); printf("*******************************\n"); if (gSystem->Exec("PROOF-INF/BUILD.sh")) { Error("runAnalysis","Cannot Build the PAR Archive! - Abort!"); return -1; } } // check for SETUP.C and execute if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) { printf("*******************************\n"); printf("*** Setup PAR archive ***\n"); printf("*******************************\n"); gROOT->Macro("PROOF-INF/SETUP.C"); } gSystem->ChangeDirectory("../"); } return 1; } <|endoftext|>
<commit_before>#ifndef KEYBOARDMANAGER_HPP #define KEYBOARDMANAGER_HPP #include <map> #include <string> #include <functional> #include <SFML/Window/Event.hpp> #include <SFML/Window/Keyboard.hpp> #include "Binding.hpp" namespace swift { template<typename T> class InputManager { public: using BindingType = Binding<T>; void add(T input, const typename BindingType::Callback& f, bool onPress = false) { bindings.emplace_back(std::forward<T, const typename BindingType::Callback&, bool>(input, f, onPress)); } void operator()(const sf::Event& e) { for(auto& k : bindings) { k(e); } } private: std::vector<BindingType> bindings; }; } #endif // KEYBOARDMANAGER_HPP <commit_msg>Fixed issue with std::forward<commit_after>#ifndef KEYBOARDMANAGER_HPP #define KEYBOARDMANAGER_HPP #include <map> #include <string> #include <functional> #include <SFML/Window/Event.hpp> #include <SFML/Window/Keyboard.hpp> #include "Binding.hpp" namespace swift { template<typename T> class InputManager { public: using BindingType = Binding<T>; void add(T input, const typename BindingType::Callback& f, bool onPress = false) { bindings.emplace_back(input, f, onPress); } void operator()(const sf::Event& e) { for(auto& k : bindings) { k(e); } } private: std::vector<BindingType> bindings; }; } #endif // KEYBOARDMANAGER_HPP <|endoftext|>
<commit_before>// Unit Tests for Scintilla internal data structures #include <string.h> #include <algorithm> #include "Platform.h" #include "CharClassify.h" #include "catch.hpp" // Test CharClassify. class CharClassifyTest { // Avoid warnings, private so never called. CharClassifyTest(const CharClassifyTest &); protected: CharClassifyTest() { pcc = new CharClassify(); for (int ch = 0; ch < 256; ch++) { if (ch == '\r' || ch == '\n') charClass[ch] = CharClassify::ccNewLine; else if (ch < 0x20 || ch == ' ') charClass[ch] = CharClassify::ccSpace; else if (ch >= 0x80 || isalnum(ch) || ch == '_') charClass[ch] = CharClassify::ccWord; else charClass[ch] = CharClassify::ccPunctuation; } } ~CharClassifyTest() { delete pcc; pcc = 0; } CharClassify *pcc; CharClassify::cc charClass[256]; static const char* GetClassName(CharClassify::cc charClass) { switch(charClass) { #define CASE(c) case CharClassify::c: return #c CASE(ccSpace); CASE(ccNewLine); CASE(ccWord); CASE(ccPunctuation); #undef CASE default: return "<unknown>"; } } }; TEST_CASE_METHOD(CharClassifyTest, "Defaults") { for (int i = 0; i < 256; i++) { if (charClass[i] != pcc->GetClass(i)) std::cerr << "Character " << i << " should be class " << GetClassName(charClass[i]) << ", but got " << GetClassName(pcc->GetClass(i)) << std::endl; REQUIRE(charClass[i] == pcc->GetClass(i)); } } TEST_CASE_METHOD(CharClassifyTest, "Custom") { unsigned char buf[2] = {0, 0}; for (int i = 0; i < 256; i++) { CharClassify::cc thisClass = CharClassify::cc(i % 4); buf[0] = i; pcc->SetCharClasses(buf, thisClass); charClass[i] = thisClass; } for (int i = 0; i < 256; i++) { if (charClass[i] != pcc->GetClass(i)) std::cerr << "Character " << i << " should be class " << GetClassName(charClass[i]) << ", but got " << GetClassName(pcc->GetClass(i)) << std::endl; REQUIRE(charClass[i] == pcc->GetClass(i)); } } TEST_CASE_METHOD(CharClassifyTest, "CharsOfClass") { unsigned char buf[2] = {0, 0}; for (int i = 1; i < 256; i++) { CharClassify::cc thisClass = CharClassify::cc(i % 4); buf[0] = i; pcc->SetCharClasses(buf, thisClass); charClass[i] = thisClass; } for (int classVal = 0; classVal < 4; ++classVal) { CharClassify::cc thisClass = CharClassify::cc(classVal % 4); int size = pcc->GetCharsOfClass(thisClass, NULL); unsigned char* buffer = reinterpret_cast<unsigned char*>(malloc(size + 1)); CHECK(buffer); buffer[size] = '\0'; pcc->GetCharsOfClass(thisClass, buffer); for (int i = 1; i < 256; i++) { if (charClass[i] == thisClass) { if (!memchr(reinterpret_cast<char*>(buffer), i, size)) std::cerr << "Character " << i << " should be class " << GetClassName(thisClass) << ", but was not in GetCharsOfClass;" << " it is reported to be " << GetClassName(pcc->GetClass(i)) << std::endl; REQUIRE(memchr(reinterpret_cast<char*>(buffer), i, size)); } else { if (memchr(reinterpret_cast<char*>(buffer), i, size)) std::cerr << "Character " << i << " should not be class " << GetClassName(thisClass) << ", but was in GetCharsOfClass" << " it is reported to be " << GetClassName(pcc->GetClass(i)) << std::endl; REQUIRE_FALSE(memchr(reinterpret_cast<char*>(buffer), i, size)); } } free(buffer); } } <commit_msg>Avoid warning from cppcheck.<commit_after>// Unit Tests for Scintilla internal data structures #include <string.h> #include <algorithm> #include "Platform.h" #include "CharClassify.h" #include "catch.hpp" // Test CharClassify. class CharClassifyTest { // Avoid warnings, private so never called. CharClassifyTest(const CharClassifyTest &); protected: CharClassifyTest() { pcc = new CharClassify(); for (int ch = 0; ch < 256; ch++) { if (ch == '\r' || ch == '\n') charClass[ch] = CharClassify::ccNewLine; else if (ch < 0x20 || ch == ' ') charClass[ch] = CharClassify::ccSpace; else if (ch >= 0x80 || isalnum(ch) || ch == '_') charClass[ch] = CharClassify::ccWord; else charClass[ch] = CharClassify::ccPunctuation; } } ~CharClassifyTest() { delete pcc; pcc = 0; } CharClassify *pcc; CharClassify::cc charClass[256]; static const char* GetClassName(CharClassify::cc charClass) { switch(charClass) { #define CASE(c) case CharClassify::c: return #c CASE(ccSpace); CASE(ccNewLine); CASE(ccWord); CASE(ccPunctuation); #undef CASE default: return "<unknown>"; } } }; TEST_CASE_METHOD(CharClassifyTest, "Defaults") { for (int i = 0; i < 256; i++) { if (charClass[i] != pcc->GetClass(i)) std::cerr << "Character " << i << " should be class " << GetClassName(charClass[i]) << ", but got " << GetClassName(pcc->GetClass(i)) << std::endl; REQUIRE(charClass[i] == pcc->GetClass(i)); } } TEST_CASE_METHOD(CharClassifyTest, "Custom") { unsigned char buf[2] = {0, 0}; for (int i = 0; i < 256; i++) { CharClassify::cc thisClass = CharClassify::cc(i % 4); buf[0] = i; pcc->SetCharClasses(buf, thisClass); charClass[i] = thisClass; } for (int i = 0; i < 256; i++) { if (charClass[i] != pcc->GetClass(i)) std::cerr << "Character " << i << " should be class " << GetClassName(charClass[i]) << ", but got " << GetClassName(pcc->GetClass(i)) << std::endl; REQUIRE(charClass[i] == pcc->GetClass(i)); } } TEST_CASE_METHOD(CharClassifyTest, "CharsOfClass") { unsigned char buf[2] = {0, 0}; for (int i = 1; i < 256; i++) { CharClassify::cc thisClass = CharClassify::cc(i % 4); buf[0] = i; pcc->SetCharClasses(buf, thisClass); charClass[i] = thisClass; } for (int classVal = 0; classVal < 4; ++classVal) { CharClassify::cc thisClass = CharClassify::cc(classVal % 4); int size = pcc->GetCharsOfClass(thisClass, NULL); unsigned char* buffer = new unsigned char[size + 1]; buffer[size] = '\0'; pcc->GetCharsOfClass(thisClass, buffer); for (int i = 1; i < 256; i++) { if (charClass[i] == thisClass) { if (!memchr(reinterpret_cast<char*>(buffer), i, size)) std::cerr << "Character " << i << " should be class " << GetClassName(thisClass) << ", but was not in GetCharsOfClass;" << " it is reported to be " << GetClassName(pcc->GetClass(i)) << std::endl; REQUIRE(memchr(reinterpret_cast<char*>(buffer), i, size)); } else { if (memchr(reinterpret_cast<char*>(buffer), i, size)) std::cerr << "Character " << i << " should not be class " << GetClassName(thisClass) << ", but was in GetCharsOfClass" << " it is reported to be " << GetClassName(pcc->GetClass(i)) << std::endl; REQUIRE_FALSE(memchr(reinterpret_cast<char*>(buffer), i, size)); } } delete []buffer; } } <|endoftext|>
<commit_before><commit_msg>tests:Fix signed/unsigned compare warning<commit_after><|endoftext|>
<commit_before>#include <silicium/async_process.hpp> #include <silicium/http/parse_request.hpp> #include <silicium/http/generate_response.hpp> #include <silicium/asio/tcp_acceptor.hpp> #include <silicium/observable/spawn_coroutine.hpp> #include <iostream> namespace { } int main() { boost::asio::io_service io; Si::spawn_coroutine([&io](Si::spawn_context yield) { auto acceptor = Si::asio::make_tcp_acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 8080)); for (;;) { auto client = (*yield.get_one(Si::ref(acceptor)))->get(); assert(client); } }); io.run(); } <commit_msg>serve a form with a working submit button<commit_after>#include <silicium/async_process.hpp> #include <silicium/http/generate_response.hpp> #include <silicium/http/receive_request.hpp> #include <silicium/asio/tcp_acceptor.hpp> #include <silicium/asio/writing_observable.hpp> #include <silicium/sink/iterator_sink.hpp> #include <silicium/observable/spawn_coroutine.hpp> #include <iostream> namespace { void respond(boost::asio::ip::tcp::socket &client, Si::memory_range status, Si::memory_range status_text, Si::memory_range content, Si::spawn_context &yield) { std::vector<char> response; auto const response_sink = Si::make_container_sink(response); Si::http::generate_status_line(response_sink, "HTTP/1.1", status, status_text); Si::http::generate_header(response_sink, "Content-Length", boost::lexical_cast<Si::noexcept_string>(content.size())); Si::http::generate_header(response_sink, "Content-Type", "text/html"); Si::http::finish_headers(response_sink); Si::append(response_sink, content); boost::system::error_code error = Si::asio::write(client, Si::make_memory_range(response), yield); if (!!error) { std::cerr << "Could not respond to " << client.remote_endpoint() << ": " << error << '\n'; } else { client.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error); if (!!error) { std::cerr << "Could not shutdown connection to " << client.remote_endpoint() << ": " << error << '\n'; } } } void trigger_build() { std::cerr << "Build triggered (TODO)\n"; } } int main() { boost::asio::io_service io; Si::spawn_coroutine([&io](Si::spawn_context yield) { auto acceptor = Si::asio::make_tcp_acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 8080)); for (;;) { std::shared_ptr<boost::asio::ip::tcp::socket> client = (*yield.get_one(Si::ref(acceptor))).get(); assert(client); Si::spawn_coroutine([client = std::move(client)](Si::spawn_context yield) { Si::error_or<Si::optional<Si::http::request>> const received = Si::http::receive_request(*client, yield); if (received.is_error()) { std::cerr << "Error when receiving request from " << client->remote_endpoint() << ": " << received.error() << '\n'; return; } Si::optional<Si::http::request> const &maybe_request = received.get(); if (!maybe_request) { return respond(*client, Si::make_c_str_range("400"), Si::make_c_str_range("Bad Request"), Si::make_c_str_range("the server could not parse the request"), yield); } Si::http::request const &request = *maybe_request; if (request.method != "POST" && request.method != "GET") { return respond(*client, Si::make_c_str_range("405"), Si::make_c_str_range("Method Not Allowed"), Si::make_c_str_range("this HTTP method is not supported by this server"), yield); } if (request.path != "/") { return respond(*client, Si::make_c_str_range("404"), Si::make_c_str_range("Not Found"), Si::make_c_str_range("unknown path"), yield); } if (request.method == "POST") { trigger_build(); } char const * const page = "<html>" "<body>" "<form action=\"/\" method=\"POST\">" "<input type=\"submit\" value=\"Trigger build\"/>" "</form>" "</body>" "</html>"; return respond(*client, Si::make_c_str_range("200"), Si::make_c_str_range("OK"), Si::make_c_str_range(page), yield); }); } }); io.run(); } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" #include <Eigen/QR> template<typename MatrixType> void qr(const MatrixType& m) { typedef typename MatrixType::Index Index; Index rows = m.rows(); Index cols = m.cols(); typedef typename MatrixType::Scalar Scalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> MatrixQType; MatrixType a = MatrixType::Random(rows,cols); HouseholderQR<MatrixType> qrOfA(a); MatrixQType q = qrOfA.householderQ(); VERIFY_IS_UNITARY(q); MatrixType r = qrOfA.matrixQR().template triangularView<Upper>(); VERIFY_IS_APPROX(a, qrOfA.householderQ() * r); } template<typename MatrixType, int Cols2> void qr_fixedsize() { enum { Rows = MatrixType::RowsAtCompileTime, Cols = MatrixType::ColsAtCompileTime }; typedef typename MatrixType::Scalar Scalar; Matrix<Scalar,Rows,Cols> m1 = Matrix<Scalar,Rows,Cols>::Random(); HouseholderQR<Matrix<Scalar,Rows,Cols> > qr(m1); Matrix<Scalar,Rows,Cols> r = qr.matrixQR(); // FIXME need better way to construct trapezoid for(int i = 0; i < Rows; i++) for(int j = 0; j < Cols; j++) if(i>j) r(i,j) = Scalar(0); VERIFY_IS_APPROX(m1, qr.householderQ() * r); Matrix<Scalar,Cols,Cols2> m2 = Matrix<Scalar,Cols,Cols2>::Random(Cols,Cols2); Matrix<Scalar,Rows,Cols2> m3 = m1*m2; m2 = Matrix<Scalar,Cols,Cols2>::Random(Cols,Cols2); m2 = qr.solve(m3); VERIFY_IS_APPROX(m3, m1*m2); } template<typename MatrixType> void qr_invertible() { using std::log; using std::abs; typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar; typedef typename MatrixType::Scalar Scalar; int size = internal::random<int>(10,50); MatrixType m1(size, size), m2(size, size), m3(size, size); m1 = MatrixType::Random(size,size); if (internal::is_same<RealScalar,float>::value) { // let's build a matrix more stable to inverse MatrixType a = MatrixType::Random(size,size*2); m1 += a * a.adjoint(); } HouseholderQR<MatrixType> qr(m1); m3 = MatrixType::Random(size,size); m2 = qr.solve(m3); VERIFY_IS_APPROX(m3, m1*m2); // now construct a matrix with prescribed determinant m1.setZero(); for(int i = 0; i < size; i++) m1(i,i) = internal::random<Scalar>(); RealScalar absdet = abs(m1.diagonal().prod()); m3 = qr.householderQ(); // get a unitary m1 = m3 * m1 * m3; qr.compute(m1); VERIFY_IS_APPROX(absdet, qr.absDeterminant()); VERIFY_IS_APPROX(log(absdet), qr.logAbsDeterminant()); } template<typename MatrixType> void qr_verify_assert() { MatrixType tmp; HouseholderQR<MatrixType> qr; VERIFY_RAISES_ASSERT(qr.matrixQR()) VERIFY_RAISES_ASSERT(qr.solve(tmp)) VERIFY_RAISES_ASSERT(qr.householderQ()) VERIFY_RAISES_ASSERT(qr.absDeterminant()) VERIFY_RAISES_ASSERT(qr.logAbsDeterminant()) } void test_qr() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( qr(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE),internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_2( qr(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2),internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2))) ); CALL_SUBTEST_3(( qr_fixedsize<Matrix<float,3,4>, 2 >() )); CALL_SUBTEST_4(( qr_fixedsize<Matrix<double,6,2>, 4 >() )); CALL_SUBTEST_5(( qr_fixedsize<Matrix<double,2,5>, 7 >() )); CALL_SUBTEST_11( qr(Matrix<float,1,1>()) ); } for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( qr_invertible<MatrixXf>() ); CALL_SUBTEST_6( qr_invertible<MatrixXd>() ); CALL_SUBTEST_7( qr_invertible<MatrixXcf>() ); CALL_SUBTEST_8( qr_invertible<MatrixXcd>() ); } CALL_SUBTEST_9(qr_verify_assert<Matrix3f>()); CALL_SUBTEST_10(qr_verify_assert<Matrix3d>()); CALL_SUBTEST_1(qr_verify_assert<MatrixXf>()); CALL_SUBTEST_6(qr_verify_assert<MatrixXd>()); CALL_SUBTEST_7(qr_verify_assert<MatrixXcf>()); CALL_SUBTEST_8(qr_verify_assert<MatrixXcd>()); // Test problem size constructors CALL_SUBTEST_12(HouseholderQR<MatrixXf>(10, 20)); } <commit_msg>reduce false negative in the qr unit test<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" #include <Eigen/QR> template<typename MatrixType> void qr(const MatrixType& m) { typedef typename MatrixType::Index Index; Index rows = m.rows(); Index cols = m.cols(); typedef typename MatrixType::Scalar Scalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> MatrixQType; MatrixType a = MatrixType::Random(rows,cols); HouseholderQR<MatrixType> qrOfA(a); MatrixQType q = qrOfA.householderQ(); VERIFY_IS_UNITARY(q); MatrixType r = qrOfA.matrixQR().template triangularView<Upper>(); VERIFY_IS_APPROX(a, qrOfA.householderQ() * r); } template<typename MatrixType, int Cols2> void qr_fixedsize() { enum { Rows = MatrixType::RowsAtCompileTime, Cols = MatrixType::ColsAtCompileTime }; typedef typename MatrixType::Scalar Scalar; Matrix<Scalar,Rows,Cols> m1 = Matrix<Scalar,Rows,Cols>::Random(); HouseholderQR<Matrix<Scalar,Rows,Cols> > qr(m1); Matrix<Scalar,Rows,Cols> r = qr.matrixQR(); // FIXME need better way to construct trapezoid for(int i = 0; i < Rows; i++) for(int j = 0; j < Cols; j++) if(i>j) r(i,j) = Scalar(0); VERIFY_IS_APPROX(m1, qr.householderQ() * r); Matrix<Scalar,Cols,Cols2> m2 = Matrix<Scalar,Cols,Cols2>::Random(Cols,Cols2); Matrix<Scalar,Rows,Cols2> m3 = m1*m2; m2 = Matrix<Scalar,Cols,Cols2>::Random(Cols,Cols2); m2 = qr.solve(m3); VERIFY_IS_APPROX(m3, m1*m2); } template<typename MatrixType> void qr_invertible() { using std::log; using std::abs; using std::pow; using std::max; typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar; typedef typename MatrixType::Scalar Scalar; int size = internal::random<int>(10,50); MatrixType m1(size, size), m2(size, size), m3(size, size); m1 = MatrixType::Random(size,size); if (internal::is_same<RealScalar,float>::value) { // let's build a matrix more stable to inverse MatrixType a = MatrixType::Random(size,size*4); m1 += a * a.adjoint(); } HouseholderQR<MatrixType> qr(m1); m3 = MatrixType::Random(size,size); m2 = qr.solve(m3); VERIFY_IS_APPROX(m3, m1*m2); // now construct a matrix with prescribed determinant m1.setZero(); for(int i = 0; i < size; i++) m1(i,i) = internal::random<Scalar>(); RealScalar absdet = abs(m1.diagonal().prod()); m3 = qr.householderQ(); // get a unitary m1 = m3 * m1 * m3; qr.compute(m1); VERIFY_IS_APPROX(log(absdet), qr.logAbsDeterminant()); // This test is tricky if the determinant becomes too small. // Since we generate random numbers with magnitude rrange [0,1], the average determinant is 0.5^size VERIFY_IS_MUCH_SMALLER_THAN( abs(absdet-qr.absDeterminant()), (max)(RealScalar(pow(0.5,size)),(max)(abs(absdet),abs(qr.absDeterminant()))) ); } template<typename MatrixType> void qr_verify_assert() { MatrixType tmp; HouseholderQR<MatrixType> qr; VERIFY_RAISES_ASSERT(qr.matrixQR()) VERIFY_RAISES_ASSERT(qr.solve(tmp)) VERIFY_RAISES_ASSERT(qr.householderQ()) VERIFY_RAISES_ASSERT(qr.absDeterminant()) VERIFY_RAISES_ASSERT(qr.logAbsDeterminant()) } void test_qr() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( qr(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE),internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_2( qr(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2),internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2))) ); CALL_SUBTEST_3(( qr_fixedsize<Matrix<float,3,4>, 2 >() )); CALL_SUBTEST_4(( qr_fixedsize<Matrix<double,6,2>, 4 >() )); CALL_SUBTEST_5(( qr_fixedsize<Matrix<double,2,5>, 7 >() )); CALL_SUBTEST_11( qr(Matrix<float,1,1>()) ); } for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( qr_invertible<MatrixXf>() ); CALL_SUBTEST_6( qr_invertible<MatrixXd>() ); CALL_SUBTEST_7( qr_invertible<MatrixXcf>() ); CALL_SUBTEST_8( qr_invertible<MatrixXcd>() ); } CALL_SUBTEST_9(qr_verify_assert<Matrix3f>()); CALL_SUBTEST_10(qr_verify_assert<Matrix3d>()); CALL_SUBTEST_1(qr_verify_assert<MatrixXf>()); CALL_SUBTEST_6(qr_verify_assert<MatrixXd>()); CALL_SUBTEST_7(qr_verify_assert<MatrixXcf>()); CALL_SUBTEST_8(qr_verify_assert<MatrixXcd>()); // Test problem size constructors CALL_SUBTEST_12(HouseholderQR<MatrixXf>(10, 20)); } <|endoftext|>
<commit_before><commit_msg>tests: Do not call vkQueueBindSparse() when sparse bindings are not supported<commit_after><|endoftext|>
<commit_before>// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/testing/dart_isolate_runner.h" namespace flutter { namespace testing { AutoIsolateShutdown::AutoIsolateShutdown(std::shared_ptr<DartIsolate> isolate, fml::RefPtr<fml::TaskRunner> runner) : isolate_(std::move(isolate)), runner_(std::move(runner)) {} AutoIsolateShutdown::~AutoIsolateShutdown() { if (!IsValid()) { return; } fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( runner_, [isolate = std::move(isolate_), &latch]() { if (!isolate->Shutdown()) { FML_LOG(ERROR) << "Could not shutdown isolate."; FML_CHECK(false); } latch.Signal(); }); latch.Wait(); } [[nodiscard]] bool AutoIsolateShutdown::RunInIsolateScope( std::function<bool(void)> closure) { if (!IsValid()) { return false; } bool result = false; fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( runner_, [this, &result, &latch, closure]() { tonic::DartIsolateScope scope(isolate_->isolate()); tonic::DartApiScope api_scope; if (closure) { result = closure(); } latch.Signal(); }); latch.Wait(); return true; } void RunDartCodeInIsolate(DartVMRef& vm_ref, std::unique_ptr<AutoIsolateShutdown>& result, const Settings& settings, const TaskRunners& task_runners, std::string entrypoint, const std::vector<std::string>& args, const std::string& fixtures_path, fml::WeakPtr<IOManager> io_manager) { FML_CHECK(task_runners.GetPlatformTaskRunner()->RunsTasksOnCurrentThread()); if (!vm_ref) { return; } auto vm_data = vm_ref.GetVMData(); if (!vm_data) { return; } auto weak_isolate = DartIsolate::CreateRootIsolate( vm_data->GetSettings(), // settings vm_data->GetIsolateSnapshot(), // isolate snapshot std::move(task_runners), // task runners nullptr, // window {}, // snapshot delegate io_manager, // io manager {}, // unref queue {}, // image decoder "main.dart", // advisory uri "main", // advisory entrypoint nullptr, // flags settings.isolate_create_callback, // isolate create callback settings.isolate_shutdown_callback // isolate shutdown callback ); auto root_isolate = std::make_unique<AutoIsolateShutdown>( weak_isolate.lock(), task_runners.GetUITaskRunner()); if (!root_isolate->IsValid()) { FML_LOG(ERROR) << "Could not create isolate."; return; } if (root_isolate->get()->GetPhase() != DartIsolate::Phase::LibrariesSetup) { FML_LOG(ERROR) << "Created isolate is in unexpected phase."; return; } if (!DartVM::IsRunningPrecompiledCode()) { auto kernel_file_path = fml::paths::JoinPaths({fixtures_path, "kernel_blob.bin"}); if (!fml::IsFile(kernel_file_path)) { FML_LOG(ERROR) << "Could not locate kernel file."; return; } auto kernel_file = fml::OpenFile(kernel_file_path.c_str(), false, fml::FilePermission::kRead); if (!kernel_file.is_valid()) { FML_LOG(ERROR) << "Kernel file descriptor was invalid."; return; } auto kernel_mapping = std::make_unique<fml::FileMapping>(kernel_file); if (kernel_mapping->GetMapping() == nullptr) { FML_LOG(ERROR) << "Could not setup kernel mapping."; return; } if (!root_isolate->get()->PrepareForRunningFromKernel( std::move(kernel_mapping))) { FML_LOG(ERROR) << "Could not prepare to run the isolate from the kernel file."; return; } } else { if (!root_isolate->get()->PrepareForRunningFromPrecompiledCode()) { FML_LOG(ERROR) << "Could not prepare to run the isolate from precompiled code."; return; } } if (root_isolate->get()->GetPhase() != DartIsolate::Phase::Ready) { FML_LOG(ERROR) << "Isolate is in unexpected phase."; return; } if (!root_isolate->get()->Run(entrypoint, args, settings.root_isolate_create_callback)) { FML_LOG(ERROR) << "Could not run the method \"" << entrypoint << "\" in the isolate."; return; } root_isolate->get()->AddIsolateShutdownCallback( settings.root_isolate_shutdown_callback); result = std::move(root_isolate); } std::unique_ptr<AutoIsolateShutdown> RunDartCodeInIsolate( DartVMRef& vm_ref, const Settings& settings, const TaskRunners& task_runners, std::string entrypoint, const std::vector<std::string>& args, const std::string& fixtures_path, fml::WeakPtr<IOManager> io_manager) { std::unique_ptr<AutoIsolateShutdown> result; fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners.GetPlatformTaskRunner(), fml::MakeCopyable([&]() mutable { RunDartCodeInIsolate(vm_ref, result, settings, task_runners, entrypoint, args, fixtures_path, io_manager); latch.Signal(); })); latch.Wait(); return result; } } // namespace testing } // namespace flutter <commit_msg>In tests run dart code on ui(rather than on platform) thread. (#17686)<commit_after>// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/testing/dart_isolate_runner.h" namespace flutter { namespace testing { AutoIsolateShutdown::AutoIsolateShutdown(std::shared_ptr<DartIsolate> isolate, fml::RefPtr<fml::TaskRunner> runner) : isolate_(std::move(isolate)), runner_(std::move(runner)) {} AutoIsolateShutdown::~AutoIsolateShutdown() { if (!IsValid()) { return; } fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( runner_, [isolate = std::move(isolate_), &latch]() { if (!isolate->Shutdown()) { FML_LOG(ERROR) << "Could not shutdown isolate."; FML_CHECK(false); } latch.Signal(); }); latch.Wait(); } [[nodiscard]] bool AutoIsolateShutdown::RunInIsolateScope( std::function<bool(void)> closure) { if (!IsValid()) { return false; } bool result = false; fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( runner_, [this, &result, &latch, closure]() { tonic::DartIsolateScope scope(isolate_->isolate()); tonic::DartApiScope api_scope; if (closure) { result = closure(); } latch.Signal(); }); latch.Wait(); return true; } void RunDartCodeInIsolate(DartVMRef& vm_ref, std::unique_ptr<AutoIsolateShutdown>& result, const Settings& settings, const TaskRunners& task_runners, std::string entrypoint, const std::vector<std::string>& args, const std::string& fixtures_path, fml::WeakPtr<IOManager> io_manager) { FML_CHECK(task_runners.GetUITaskRunner()->RunsTasksOnCurrentThread()); if (!vm_ref) { return; } auto vm_data = vm_ref.GetVMData(); if (!vm_data) { return; } auto weak_isolate = DartIsolate::CreateRootIsolate( vm_data->GetSettings(), // settings vm_data->GetIsolateSnapshot(), // isolate snapshot std::move(task_runners), // task runners nullptr, // window {}, // snapshot delegate io_manager, // io manager {}, // unref queue {}, // image decoder "main.dart", // advisory uri "main", // advisory entrypoint nullptr, // flags settings.isolate_create_callback, // isolate create callback settings.isolate_shutdown_callback // isolate shutdown callback ); auto root_isolate = std::make_unique<AutoIsolateShutdown>( weak_isolate.lock(), task_runners.GetUITaskRunner()); if (!root_isolate->IsValid()) { FML_LOG(ERROR) << "Could not create isolate."; return; } if (root_isolate->get()->GetPhase() != DartIsolate::Phase::LibrariesSetup) { FML_LOG(ERROR) << "Created isolate is in unexpected phase."; return; } if (!DartVM::IsRunningPrecompiledCode()) { auto kernel_file_path = fml::paths::JoinPaths({fixtures_path, "kernel_blob.bin"}); if (!fml::IsFile(kernel_file_path)) { FML_LOG(ERROR) << "Could not locate kernel file."; return; } auto kernel_file = fml::OpenFile(kernel_file_path.c_str(), false, fml::FilePermission::kRead); if (!kernel_file.is_valid()) { FML_LOG(ERROR) << "Kernel file descriptor was invalid."; return; } auto kernel_mapping = std::make_unique<fml::FileMapping>(kernel_file); if (kernel_mapping->GetMapping() == nullptr) { FML_LOG(ERROR) << "Could not setup kernel mapping."; return; } if (!root_isolate->get()->PrepareForRunningFromKernel( std::move(kernel_mapping))) { FML_LOG(ERROR) << "Could not prepare to run the isolate from the kernel file."; return; } } else { if (!root_isolate->get()->PrepareForRunningFromPrecompiledCode()) { FML_LOG(ERROR) << "Could not prepare to run the isolate from precompiled code."; return; } } if (root_isolate->get()->GetPhase() != DartIsolate::Phase::Ready) { FML_LOG(ERROR) << "Isolate is in unexpected phase."; return; } if (!root_isolate->get()->Run(entrypoint, args, settings.root_isolate_create_callback)) { FML_LOG(ERROR) << "Could not run the method \"" << entrypoint << "\" in the isolate."; return; } root_isolate->get()->AddIsolateShutdownCallback( settings.root_isolate_shutdown_callback); result = std::move(root_isolate); } std::unique_ptr<AutoIsolateShutdown> RunDartCodeInIsolate( DartVMRef& vm_ref, const Settings& settings, const TaskRunners& task_runners, std::string entrypoint, const std::vector<std::string>& args, const std::string& fixtures_path, fml::WeakPtr<IOManager> io_manager) { std::unique_ptr<AutoIsolateShutdown> result; fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners.GetUITaskRunner(), fml::MakeCopyable([&]() mutable { RunDartCodeInIsolate(vm_ref, result, settings, task_runners, entrypoint, args, fixtures_path, io_manager); latch.Signal(); })); latch.Wait(); return result; } } // namespace testing } // namespace flutter <|endoftext|>
<commit_before>//Copyright (c) 2019 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include <gtest/gtest.h> #include "../src/Application.h" //To set up a scene and load settings that the layer plan and merger need. #include "../src/FanSpeedLayerTime.h" //Required to construct a layer plan. Doesn't influence our tests. #include "../src/pathPlanning/GCodePath.h" //The paths that we're going to be merging. #include "../src/LayerPlan.h" //Constructing plans that the mergers can merge lines in. #include "../src/MergeInfillLines.h" //The class under test. #include "../src/RetractionConfig.h" //Required to construct a layer plan. Doesn't influence our tests. #include "../src/Slice.h" //To set up a scene and load settings that the layer plan and merger need. #include "../src/settings/types/LayerIndex.h" //Required to construct a layer plan. Doesn't influence our tests. namespace cura { class MergeInfillLinesTest : public testing::Test { public: //These settings don't matter for this test so they are all the same for every fixture. const size_t extruder_nr = 0; const LayerIndex layer_nr = 0; const bool is_initial_layer = false; const bool is_raft_layer = false; const coord_t layer_thickness = 100; /* * A merger to test with. */ ExtruderPlan* extruder_plan; MergeInfillLines* merger; /* * These fields are required for constructing layer plans and must be held * constant for as long as the lifetime of the plans. Construct them once * and store them in this fixture class. */ const FanSpeedLayerTimeSettings fan_speed_layer_time; const RetractionConfig retraction_config; const GCodePathConfig skin_config; /* * A path of skin lines without any points. */ GCodePath empty_skin; /* * A path of a single skin line. */ GCodePath single_skin; /* * A path of multiple skin lines that together form a straight line. * * This path should not get merged together to a single line. */ GCodePath lengthwise_skin; MergeInfillLinesTest() : fan_speed_layer_time() , retraction_config() , skin_config(PrintFeatureType::Skin, 400, layer_thickness, 1, GCodePathConfig::SpeedDerivatives{50, 1000, 10}) , empty_skin(skin_config, "merge_infill_lines_mesh", SpaceFillType::None, 1.0, false) , single_skin(skin_config, "merge_infill_lines_mesh", SpaceFillType::Lines, 1.0, false) , lengthwise_skin(skin_config, "merge_infill_lines_mesh", SpaceFillType::Lines, 1.0, false) { single_skin.points.emplace_back(1000, 0); lengthwise_skin.points = {Point(1000, 0), Point(2000, 0), Point(3000, 0), Point(4000, 0)}; } void SetUp() { //Set up a scene so that we may request settings. Application::getInstance().current_slice = new Slice(1); Application::getInstance().current_slice->scene.extruders.emplace_back(0, nullptr); ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders.back(); train.settings.add("machine_nozzle_size", "0.4"); train.settings.add("meshfix_maximum_deviation", "0.1"); extruder_plan = new ExtruderPlan(extruder_nr, layer_nr, is_initial_layer, is_raft_layer, layer_thickness, fan_speed_layer_time, retraction_config); merger = new MergeInfillLines(*extruder_plan); } void TearDown() { delete extruder_plan; delete merger; delete Application::getInstance().current_slice; } }; TEST_F(MergeInfillLinesTest, CalcPathLengthEmpty) { EXPECT_EQ(0, merger->calcPathLength(Point(0, 0), empty_skin)); } TEST_F(MergeInfillLinesTest, CalcPathLengthSingle) { EXPECT_EQ(1000, merger->calcPathLength(Point(0, 0), single_skin)); } TEST_F(MergeInfillLinesTest, CalcPathLengthMultiple) { EXPECT_EQ(4000, merger->calcPathLength(Point(0, 0), lengthwise_skin)); } } //namespace cura<commit_msg>Add integration test for merging empty paths<commit_after>//Copyright (c) 2019 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include <gtest/gtest.h> #include "../src/Application.h" //To set up a scene and load settings that the layer plan and merger need. #include "../src/FanSpeedLayerTime.h" //Required to construct a layer plan. Doesn't influence our tests. #include "../src/pathPlanning/GCodePath.h" //The paths that we're going to be merging. #include "../src/LayerPlan.h" //Constructing plans that the mergers can merge lines in. #include "../src/MergeInfillLines.h" //The class under test. #include "../src/RetractionConfig.h" //Required to construct a layer plan. Doesn't influence our tests. #include "../src/Slice.h" //To set up a scene and load settings that the layer plan and merger need. #include "../src/settings/types/LayerIndex.h" //Required to construct a layer plan. Doesn't influence our tests. namespace cura { class MergeInfillLinesTest : public testing::Test { public: //These settings don't matter for this test so they are all the same for every fixture. const size_t extruder_nr = 0; const LayerIndex layer_nr = 0; const bool is_initial_layer = false; const bool is_raft_layer = false; const coord_t layer_thickness = 100; /* * A merger to test with. */ ExtruderPlan* extruder_plan; MergeInfillLines* merger; /* * These fields are required for constructing layer plans and must be held * constant for as long as the lifetime of the plans. Construct them once * and store them in this fixture class. */ const FanSpeedLayerTimeSettings fan_speed_layer_time; const RetractionConfig retraction_config; const GCodePathConfig skin_config; /* * A path of skin lines without any points. */ GCodePath empty_skin; /* * A path of a single skin line. */ GCodePath single_skin; /* * A path of multiple skin lines that together form a straight line. * * This path should not get merged together to a single line. */ GCodePath lengthwise_skin; MergeInfillLinesTest() : fan_speed_layer_time() , retraction_config() , skin_config(PrintFeatureType::Skin, 400, layer_thickness, 1, GCodePathConfig::SpeedDerivatives{50, 1000, 10}) , empty_skin(skin_config, "merge_infill_lines_mesh", SpaceFillType::None, 1.0, false) , single_skin(skin_config, "merge_infill_lines_mesh", SpaceFillType::Lines, 1.0, false) , lengthwise_skin(skin_config, "merge_infill_lines_mesh", SpaceFillType::Lines, 1.0, false) { single_skin.points.emplace_back(1000, 0); lengthwise_skin.points = {Point(1000, 0), Point(2000, 0), Point(3000, 0), Point(4000, 0)}; } void SetUp() { //Set up a scene so that we may request settings. Application::getInstance().current_slice = new Slice(1); Application::getInstance().current_slice->scene.extruders.emplace_back(0, nullptr); ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders.back(); train.settings.add("machine_nozzle_size", "0.4"); train.settings.add("meshfix_maximum_deviation", "0.1"); extruder_plan = new ExtruderPlan(extruder_nr, layer_nr, is_initial_layer, is_raft_layer, layer_thickness, fan_speed_layer_time, retraction_config); merger = new MergeInfillLines(*extruder_plan); } void TearDown() { delete extruder_plan; delete merger; delete Application::getInstance().current_slice; } }; TEST_F(MergeInfillLinesTest, CalcPathLengthEmpty) { EXPECT_EQ(0, merger->calcPathLength(Point(0, 0), empty_skin)); } TEST_F(MergeInfillLinesTest, CalcPathLengthSingle) { EXPECT_EQ(1000, merger->calcPathLength(Point(0, 0), single_skin)); } TEST_F(MergeInfillLinesTest, CalcPathLengthMultiple) { EXPECT_EQ(4000, merger->calcPathLength(Point(0, 0), lengthwise_skin)); } TEST_F(MergeInfillLinesTest, MergeEmpty) { std::vector<GCodePath> paths; //Empty. No paths to merge. Point starting_position(0, 0); const bool result = merger->mergeInfillLines(paths, starting_position); EXPECT_FALSE(result); EXPECT_EQ(paths.size(), 0); } } //namespace cura<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: zoom.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2005-01-21 16:56:06 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif // include --------------------------------------------------------------- #ifndef _SHL_HXX #include <tools/shl.hxx> #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef _SFXITEMPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SFX_OBJSH_HXX #include <sfx2/objsh.hxx> #endif #ifndef _SV_MSGBOX_HXX //autogen wg. RET_OK, RET_CANCEL #include <vcl/msgbox.hxx> #endif #pragma hdrstop #define _SVX_ZOOM_CXX #include "dialogs.hrc" #include "zoom.hrc" #include "zoom.hxx" #include "zoomitem.hxx" #include "dialmgr.hxx" #ifndef _SVX_ZOOM_DEF_HXX #include "zoom_def.hxx" #endif // static ---------------------------------------------------------------- static USHORT pRanges[] = { SID_ATTR_ZOOM, SID_ATTR_ZOOM, 0 }; #define SPECIAL_FACTOR ((USHORT)0xFFFF) // class SvxZoomDialog --------------------------------------------------- USHORT SvxZoomDialog::GetFactor() const { if ( a200Btn.IsChecked() ) return 200; if ( a150Btn.IsChecked() ) return 150; if ( a100Btn.IsChecked() ) return 100; if ( a75Btn.IsChecked() ) return 75; if ( a50Btn.IsChecked() ) return 50; if ( aUserBtn.IsChecked() ) return (USHORT)aUserEdit.GetValue(); else return SPECIAL_FACTOR; } // ----------------------------------------------------------------------- void SvxZoomDialog::SetFactor( USHORT nNewFactor, USHORT nBtnId ) { aUserEdit.Disable(); if ( !nBtnId ) { if ( nNewFactor == 200 ) { a200Btn.Check(); a200Btn.GrabFocus(); } else if ( nNewFactor == 150 ) { a150Btn.Check(); a150Btn.GrabFocus(); } else if ( nNewFactor == 100 ) { a100Btn.Check(); a100Btn.GrabFocus(); } else if ( nNewFactor == 75 ) { a75Btn.Check(); a75Btn.GrabFocus(); } else if ( nNewFactor == 50 ) { a50Btn.Check(); a50Btn.GrabFocus(); } else { aUserBtn.Check(); aUserEdit.Enable(); aUserEdit.SetValue( (long)nNewFactor ); aUserEdit.GrabFocus(); } } else { aUserEdit.SetValue( (long)nNewFactor ); if ( ZOOMBTN_OPTIMAL == nBtnId ) { aOptimalBtn.Check(); aOptimalBtn.GrabFocus(); } else if ( ZOOMBTN_PAGEWIDTH == nBtnId ) { aPageWidthBtn.Check(); aPageWidthBtn.GrabFocus(); } else if ( ZOOMBTN_WHOLEPAGE == nBtnId ) { aWholePageBtn.Check(); aWholePageBtn.GrabFocus(); } } } // ----------------------------------------------------------------------- void SvxZoomDialog::SetButtonText( USHORT nBtnId, const String& rNewTxt ) { switch ( nBtnId ) { case ZOOMBTN_OPTIMAL: // Optimal-Button aOptimalBtn.SetText( rNewTxt ); break; case ZOOMBTN_PAGEWIDTH: // Seitenbreite-Button aPageWidthBtn.SetText( rNewTxt ); break; case ZOOMBTN_WHOLEPAGE: // Ganze Seite-Button aWholePageBtn.SetText( rNewTxt ); break; default: DBG_ERROR( "wrong button number" ); } } // ----------------------------------------------------------------------- void SvxZoomDialog::HideButton( USHORT nBtnId ) { switch ( nBtnId ) { case ZOOMBTN_OPTIMAL: // Optimal-Button aOptimalBtn.Hide(); break; case ZOOMBTN_PAGEWIDTH: // Seitenbreite-Button aPageWidthBtn.Hide(); break; case ZOOMBTN_WHOLEPAGE: // Ganze Seite-Button aWholePageBtn.Hide(); break; default: DBG_ERROR( "Falsche Button-Nummer!!!" ); } } // ----------------------------------------------------------------------- void SvxZoomDialog::SetLimits( USHORT nMin, USHORT nMax ) { DBG_ASSERT( nMin < nMax, "invalid limits" ); aUserEdit.SetMin( nMin ); aUserEdit.SetFirst( nMin ); aUserEdit.SetMax( nMax ); aUserEdit.SetLast( nMax ); } // ----------------------------------------------------------------------- void SvxZoomDialog::SetSpinSize( USHORT nNewSpin ) { aUserEdit.SetSpinSize( nNewSpin ); } // ----------------------------------------------------------------------- SvxZoomDialog::SvxZoomDialog( Window* pParent, const SfxItemSet& rCoreSet ) : SfxModalDialog( pParent, SVX_RES( RID_SVXDLG_ZOOM ) ), a200Btn ( this, ResId( BTN_200 ) ), a150Btn ( this, ResId( BTN_150 ) ), a100Btn ( this, ResId( BTN_100 ) ), a75Btn ( this, ResId( BTN_75 ) ), a50Btn ( this, ResId( BTN_50 ) ), aOptimalBtn ( this, ResId( BTN_OPTIMAL ) ), aPageWidthBtn ( this, ResId( BTN_PAGE_WIDTH ) ), aWholePageBtn ( this, ResId( BTN_WHOLE_PAGE ) ), aUserBtn ( this, ResId( BTN_USER ) ), aUserEdit ( this, ResId( ED_USER ) ), aZoomFl ( this, ResId( FL_ZOOM ) ), aOKBtn ( this, ResId( BTN_ZOOM_OK ) ), aCancelBtn ( this, ResId( BTN_ZOOM_CANCEL ) ), aHelpBtn ( this, ResId( BTN_ZOOM_HELP ) ), rSet ( rCoreSet ), pOutSet ( NULL ), bModified ( FALSE ) { Link aLink = LINK( this, SvxZoomDialog, UserHdl ); a200Btn.SetClickHdl( aLink ); a150Btn.SetClickHdl( aLink ); a100Btn.SetClickHdl( aLink ); a75Btn.SetClickHdl( aLink ); a50Btn.SetClickHdl( aLink ); aOptimalBtn.SetClickHdl( aLink ); aPageWidthBtn.SetClickHdl( aLink ); aWholePageBtn.SetClickHdl( aLink ); aUserBtn.SetClickHdl( aLink ); aOKBtn.SetClickHdl( LINK( this, SvxZoomDialog, OKHdl ) ); aUserEdit.SetModifyHdl( LINK( this, SvxZoomDialog, SpinHdl ) ); // Default-Werte USHORT nValue = 100; USHORT nMin = 10; USHORT nMax = 1000; // ggf. erst den alten Wert besorgen const SfxUInt16Item* pOldUserItem = 0; SfxObjectShell* pSh = SfxObjectShell::Current(); if ( pSh ) pOldUserItem = (const SfxUInt16Item*)pSh->GetItem( SID_ATTR_ZOOM_USER ); if ( pOldUserItem ) nValue = pOldUserItem->GetValue(); // UserEdit initialisieren if ( nMin > nValue ) nMin = nValue; if ( nMax < nValue ) nMax = nValue; aUserEdit.SetMin( nMin ); aUserEdit.SetFirst( nMin ); aUserEdit.SetMax( nMax ); aUserEdit.SetLast( nMax ); aUserEdit.SetValue( nValue ); const SfxPoolItem& rItem = rSet.Get( rSet.GetPool()->GetWhich( SID_ATTR_ZOOM ) ); if ( rItem.ISA(SvxZoomItem) ) { const SvxZoomItem& rZoomItem = (const SvxZoomItem&)rItem; USHORT nValue = rZoomItem.GetValue(); SvxZoomType eType = rZoomItem.GetType(); USHORT nValSet = rZoomItem.GetValueSet(); USHORT nBtnId = 0; switch ( eType ) { case SVX_ZOOM_OPTIMAL: nBtnId = ZOOMBTN_OPTIMAL; break; case SVX_ZOOM_PAGEWIDTH: nBtnId = ZOOMBTN_PAGEWIDTH; break; case SVX_ZOOM_WHOLEPAGE: nBtnId = ZOOMBTN_WHOLEPAGE; break; case SVX_ZOOM_PERCENT: break; } // ggf. Buttons disablen if ( !(SVX_ZOOM_ENABLE_50 & nValSet) ) a50Btn.Disable(); if ( !(SVX_ZOOM_ENABLE_75 & nValSet) ) a75Btn.Disable(); if ( !(SVX_ZOOM_ENABLE_100 & nValSet) ) a100Btn.Disable(); if ( !(SVX_ZOOM_ENABLE_150 & nValSet) ) a150Btn.Disable(); if ( !(SVX_ZOOM_ENABLE_200 & nValSet) ) a200Btn.Disable(); if ( !(SVX_ZOOM_ENABLE_OPTIMAL & nValSet) ) aOptimalBtn.Disable(); if ( !(SVX_ZOOM_ENABLE_PAGEWIDTH & nValSet) ) aPageWidthBtn.Disable(); if ( !(SVX_ZOOM_ENABLE_WHOLEPAGE & nValSet) ) aWholePageBtn.Disable(); SetFactor( nValue, nBtnId ); } else { USHORT nValue = ( (const SfxUInt16Item&)rItem ).GetValue(); SetFactor( nValue ); } FreeResource(); } // ----------------------------------------------------------------------- SvxZoomDialog::~SvxZoomDialog() { delete pOutSet; pOutSet = 0; } // ----------------------------------------------------------------------- USHORT* SvxZoomDialog::GetRanges() { return pRanges; } // ----------------------------------------------------------------------- IMPL_LINK( SvxZoomDialog, UserHdl, RadioButton *, pBtn ) { bModified |= TRUE; USHORT nFactor = GetFactor(); if ( pBtn == &aUserBtn ) { aUserEdit.Enable(); aUserEdit.GrabFocus(); } else aUserEdit.Disable(); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxZoomDialog, SpinHdl, MetricField *, EMPTYARG ) { if ( !aUserBtn.IsChecked() ) return 0; bModified |= TRUE; return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxZoomDialog, OKHdl, Button *, pBtn ) { if ( bModified || &aOKBtn != pBtn ) { SvxZoomItem aItem( SVX_ZOOM_PERCENT, 0, rSet.GetPool()->GetWhich( SID_ATTR_ZOOM ) ); if ( &aOKBtn == pBtn ) { USHORT nFactor = GetFactor(); if ( SPECIAL_FACTOR == nFactor ) { if ( aOptimalBtn.IsChecked() ) aItem.SetType( SVX_ZOOM_OPTIMAL ); else if ( aPageWidthBtn.IsChecked() ) aItem.SetType( SVX_ZOOM_PAGEWIDTH ); else if ( aWholePageBtn.IsChecked() ) aItem.SetType( SVX_ZOOM_WHOLEPAGE ); } else aItem.SetValue( nFactor ); } else { DBG_ERROR( "Wrong Button" ); return 0; } pOutSet = new SfxItemSet( rSet ); pOutSet->Put( aItem ); // Wert aus dem UserEdit "uber den Dialog hinaus merken SfxObjectShell* pSh = SfxObjectShell::Current(); if ( pSh ) pSh->PutItem( SfxUInt16Item( SID_ATTR_ZOOM_USER, (UINT16)aUserEdit.GetValue() ) ); EndDialog( RET_OK ); } else EndDialog( RET_CANCEL ); return 0; } <commit_msg>INTEGRATION: CWS ooo19126 (1.4.430); FILE MERGED 2005/09/05 14:22:14 rt 1.4.430.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: zoom.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 22:23:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif // include --------------------------------------------------------------- #ifndef _SHL_HXX #include <tools/shl.hxx> #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef _SFXITEMPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SFX_OBJSH_HXX #include <sfx2/objsh.hxx> #endif #ifndef _SV_MSGBOX_HXX //autogen wg. RET_OK, RET_CANCEL #include <vcl/msgbox.hxx> #endif #pragma hdrstop #define _SVX_ZOOM_CXX #include "dialogs.hrc" #include "zoom.hrc" #include "zoom.hxx" #include "zoomitem.hxx" #include "dialmgr.hxx" #ifndef _SVX_ZOOM_DEF_HXX #include "zoom_def.hxx" #endif // static ---------------------------------------------------------------- static USHORT pRanges[] = { SID_ATTR_ZOOM, SID_ATTR_ZOOM, 0 }; #define SPECIAL_FACTOR ((USHORT)0xFFFF) // class SvxZoomDialog --------------------------------------------------- USHORT SvxZoomDialog::GetFactor() const { if ( a200Btn.IsChecked() ) return 200; if ( a150Btn.IsChecked() ) return 150; if ( a100Btn.IsChecked() ) return 100; if ( a75Btn.IsChecked() ) return 75; if ( a50Btn.IsChecked() ) return 50; if ( aUserBtn.IsChecked() ) return (USHORT)aUserEdit.GetValue(); else return SPECIAL_FACTOR; } // ----------------------------------------------------------------------- void SvxZoomDialog::SetFactor( USHORT nNewFactor, USHORT nBtnId ) { aUserEdit.Disable(); if ( !nBtnId ) { if ( nNewFactor == 200 ) { a200Btn.Check(); a200Btn.GrabFocus(); } else if ( nNewFactor == 150 ) { a150Btn.Check(); a150Btn.GrabFocus(); } else if ( nNewFactor == 100 ) { a100Btn.Check(); a100Btn.GrabFocus(); } else if ( nNewFactor == 75 ) { a75Btn.Check(); a75Btn.GrabFocus(); } else if ( nNewFactor == 50 ) { a50Btn.Check(); a50Btn.GrabFocus(); } else { aUserBtn.Check(); aUserEdit.Enable(); aUserEdit.SetValue( (long)nNewFactor ); aUserEdit.GrabFocus(); } } else { aUserEdit.SetValue( (long)nNewFactor ); if ( ZOOMBTN_OPTIMAL == nBtnId ) { aOptimalBtn.Check(); aOptimalBtn.GrabFocus(); } else if ( ZOOMBTN_PAGEWIDTH == nBtnId ) { aPageWidthBtn.Check(); aPageWidthBtn.GrabFocus(); } else if ( ZOOMBTN_WHOLEPAGE == nBtnId ) { aWholePageBtn.Check(); aWholePageBtn.GrabFocus(); } } } // ----------------------------------------------------------------------- void SvxZoomDialog::SetButtonText( USHORT nBtnId, const String& rNewTxt ) { switch ( nBtnId ) { case ZOOMBTN_OPTIMAL: // Optimal-Button aOptimalBtn.SetText( rNewTxt ); break; case ZOOMBTN_PAGEWIDTH: // Seitenbreite-Button aPageWidthBtn.SetText( rNewTxt ); break; case ZOOMBTN_WHOLEPAGE: // Ganze Seite-Button aWholePageBtn.SetText( rNewTxt ); break; default: DBG_ERROR( "wrong button number" ); } } // ----------------------------------------------------------------------- void SvxZoomDialog::HideButton( USHORT nBtnId ) { switch ( nBtnId ) { case ZOOMBTN_OPTIMAL: // Optimal-Button aOptimalBtn.Hide(); break; case ZOOMBTN_PAGEWIDTH: // Seitenbreite-Button aPageWidthBtn.Hide(); break; case ZOOMBTN_WHOLEPAGE: // Ganze Seite-Button aWholePageBtn.Hide(); break; default: DBG_ERROR( "Falsche Button-Nummer!!!" ); } } // ----------------------------------------------------------------------- void SvxZoomDialog::SetLimits( USHORT nMin, USHORT nMax ) { DBG_ASSERT( nMin < nMax, "invalid limits" ); aUserEdit.SetMin( nMin ); aUserEdit.SetFirst( nMin ); aUserEdit.SetMax( nMax ); aUserEdit.SetLast( nMax ); } // ----------------------------------------------------------------------- void SvxZoomDialog::SetSpinSize( USHORT nNewSpin ) { aUserEdit.SetSpinSize( nNewSpin ); } // ----------------------------------------------------------------------- SvxZoomDialog::SvxZoomDialog( Window* pParent, const SfxItemSet& rCoreSet ) : SfxModalDialog( pParent, SVX_RES( RID_SVXDLG_ZOOM ) ), a200Btn ( this, ResId( BTN_200 ) ), a150Btn ( this, ResId( BTN_150 ) ), a100Btn ( this, ResId( BTN_100 ) ), a75Btn ( this, ResId( BTN_75 ) ), a50Btn ( this, ResId( BTN_50 ) ), aOptimalBtn ( this, ResId( BTN_OPTIMAL ) ), aPageWidthBtn ( this, ResId( BTN_PAGE_WIDTH ) ), aWholePageBtn ( this, ResId( BTN_WHOLE_PAGE ) ), aUserBtn ( this, ResId( BTN_USER ) ), aUserEdit ( this, ResId( ED_USER ) ), aZoomFl ( this, ResId( FL_ZOOM ) ), aOKBtn ( this, ResId( BTN_ZOOM_OK ) ), aCancelBtn ( this, ResId( BTN_ZOOM_CANCEL ) ), aHelpBtn ( this, ResId( BTN_ZOOM_HELP ) ), rSet ( rCoreSet ), pOutSet ( NULL ), bModified ( FALSE ) { Link aLink = LINK( this, SvxZoomDialog, UserHdl ); a200Btn.SetClickHdl( aLink ); a150Btn.SetClickHdl( aLink ); a100Btn.SetClickHdl( aLink ); a75Btn.SetClickHdl( aLink ); a50Btn.SetClickHdl( aLink ); aOptimalBtn.SetClickHdl( aLink ); aPageWidthBtn.SetClickHdl( aLink ); aWholePageBtn.SetClickHdl( aLink ); aUserBtn.SetClickHdl( aLink ); aOKBtn.SetClickHdl( LINK( this, SvxZoomDialog, OKHdl ) ); aUserEdit.SetModifyHdl( LINK( this, SvxZoomDialog, SpinHdl ) ); // Default-Werte USHORT nValue = 100; USHORT nMin = 10; USHORT nMax = 1000; // ggf. erst den alten Wert besorgen const SfxUInt16Item* pOldUserItem = 0; SfxObjectShell* pSh = SfxObjectShell::Current(); if ( pSh ) pOldUserItem = (const SfxUInt16Item*)pSh->GetItem( SID_ATTR_ZOOM_USER ); if ( pOldUserItem ) nValue = pOldUserItem->GetValue(); // UserEdit initialisieren if ( nMin > nValue ) nMin = nValue; if ( nMax < nValue ) nMax = nValue; aUserEdit.SetMin( nMin ); aUserEdit.SetFirst( nMin ); aUserEdit.SetMax( nMax ); aUserEdit.SetLast( nMax ); aUserEdit.SetValue( nValue ); const SfxPoolItem& rItem = rSet.Get( rSet.GetPool()->GetWhich( SID_ATTR_ZOOM ) ); if ( rItem.ISA(SvxZoomItem) ) { const SvxZoomItem& rZoomItem = (const SvxZoomItem&)rItem; USHORT nValue = rZoomItem.GetValue(); SvxZoomType eType = rZoomItem.GetType(); USHORT nValSet = rZoomItem.GetValueSet(); USHORT nBtnId = 0; switch ( eType ) { case SVX_ZOOM_OPTIMAL: nBtnId = ZOOMBTN_OPTIMAL; break; case SVX_ZOOM_PAGEWIDTH: nBtnId = ZOOMBTN_PAGEWIDTH; break; case SVX_ZOOM_WHOLEPAGE: nBtnId = ZOOMBTN_WHOLEPAGE; break; case SVX_ZOOM_PERCENT: break; } // ggf. Buttons disablen if ( !(SVX_ZOOM_ENABLE_50 & nValSet) ) a50Btn.Disable(); if ( !(SVX_ZOOM_ENABLE_75 & nValSet) ) a75Btn.Disable(); if ( !(SVX_ZOOM_ENABLE_100 & nValSet) ) a100Btn.Disable(); if ( !(SVX_ZOOM_ENABLE_150 & nValSet) ) a150Btn.Disable(); if ( !(SVX_ZOOM_ENABLE_200 & nValSet) ) a200Btn.Disable(); if ( !(SVX_ZOOM_ENABLE_OPTIMAL & nValSet) ) aOptimalBtn.Disable(); if ( !(SVX_ZOOM_ENABLE_PAGEWIDTH & nValSet) ) aPageWidthBtn.Disable(); if ( !(SVX_ZOOM_ENABLE_WHOLEPAGE & nValSet) ) aWholePageBtn.Disable(); SetFactor( nValue, nBtnId ); } else { USHORT nValue = ( (const SfxUInt16Item&)rItem ).GetValue(); SetFactor( nValue ); } FreeResource(); } // ----------------------------------------------------------------------- SvxZoomDialog::~SvxZoomDialog() { delete pOutSet; pOutSet = 0; } // ----------------------------------------------------------------------- USHORT* SvxZoomDialog::GetRanges() { return pRanges; } // ----------------------------------------------------------------------- IMPL_LINK( SvxZoomDialog, UserHdl, RadioButton *, pBtn ) { bModified |= TRUE; USHORT nFactor = GetFactor(); if ( pBtn == &aUserBtn ) { aUserEdit.Enable(); aUserEdit.GrabFocus(); } else aUserEdit.Disable(); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxZoomDialog, SpinHdl, MetricField *, EMPTYARG ) { if ( !aUserBtn.IsChecked() ) return 0; bModified |= TRUE; return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxZoomDialog, OKHdl, Button *, pBtn ) { if ( bModified || &aOKBtn != pBtn ) { SvxZoomItem aItem( SVX_ZOOM_PERCENT, 0, rSet.GetPool()->GetWhich( SID_ATTR_ZOOM ) ); if ( &aOKBtn == pBtn ) { USHORT nFactor = GetFactor(); if ( SPECIAL_FACTOR == nFactor ) { if ( aOptimalBtn.IsChecked() ) aItem.SetType( SVX_ZOOM_OPTIMAL ); else if ( aPageWidthBtn.IsChecked() ) aItem.SetType( SVX_ZOOM_PAGEWIDTH ); else if ( aWholePageBtn.IsChecked() ) aItem.SetType( SVX_ZOOM_WHOLEPAGE ); } else aItem.SetValue( nFactor ); } else { DBG_ERROR( "Wrong Button" ); return 0; } pOutSet = new SfxItemSet( rSet ); pOutSet->Put( aItem ); // Wert aus dem UserEdit "uber den Dialog hinaus merken SfxObjectShell* pSh = SfxObjectShell::Current(); if ( pSh ) pSh->PutItem( SfxUInt16Item( SID_ATTR_ZOOM_USER, (UINT16)aUserEdit.GetValue() ) ); EndDialog( RET_OK ); } else EndDialog( RET_CANCEL ); return 0; } <|endoftext|>
<commit_before>/// /// anax tests /// An open source C++ entity system. /// /// Copyright (C) 2013-2014 Miguel Martin ([email protected]) /// /// 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 "lest.hpp" #include <anax/ComponentFilter.hpp> #include "Components.hpp" constexpr const unsigned MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST = 4; // All posibilities (with fail or pass): // require // requiresOneOf // exclude // require and exclude // require and requiresOneOf // requiresOneOf and exclude // require, requiresOneOf, and exclude // // TODO: fix maintainability of this code... It's just a lot of copy pasta atm const lest::test specification[] = { CASE("require (pass)") { anax::ComponentFilter filter; filter.requires<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList)); }, CASE("require (fail)") { anax::ComponentFilter filter; filter.requires<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requiesOneOf (pass with one)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList)); }, CASE("requiesOneOf (pass with all)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList)); }, CASE("requiesOneOf (fail)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = false; typeList[VelocityComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("exclude (pass)") { anax::ComponentFilter filter; filter.excludes<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = false; typeList[VelocityComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("exclude (fail via one)") { anax::ComponentFilter filter; filter.excludes<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("exclude (fail via all)") { anax::ComponentFilter filter; filter.excludes<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requiresOneOf and exclude (pass)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.excludes<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PositionComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList)); }, CASE("requiresOneOf and exclude (fail)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.excludes<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PositionComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("require and requiresOneOf (pass)") { anax::ComponentFilter filter; filter.requires<PlayerComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PositionComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList)); }, CASE("require and requiresOneOf (fail via requirement)") { anax::ComponentFilter filter; filter.requires<PlayerComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = true; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("require and requiresOneOf (fail via requiresOneOf)") { anax::ComponentFilter filter; filter.requires<PlayerComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = false; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("require and requiresOneOf (fail via all)") { anax::ComponentFilter filter; filter.requires<PlayerComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = false; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requiresOneOf and exclude (pass)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.exclude<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList)); }, CASE("requiresOneOf and exclude (fail via requiresOneOf)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.exclude<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requiresOneOf and exclude (fail via exclude)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.exclude<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requiresOneOf and exclude (fail via all)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.exclude<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("require, requiresOneOf and exclude (pass)") { anax::ComponentFilter filter; filter.require<NPCComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.exclude<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[NPCComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList)); }, CASE("require, requiresOneOf and exclude (fail via require)") { anax::ComponentFilter filter; filter.require<NPCComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.exclude<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[NPCComponent::GetTypeId()] = false; typeList[VelocityComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("require, requiresOneOf and exclude (fail via requiresOneOf)") { anax::ComponentFilter filter; filter.require<NPCComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.exclude<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[NPCComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("require, requiresOneOf and exclude (fail via exclude)") { anax::ComponentFilter filter; filter.require<NPCComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.exclude<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[NPCComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("require, requiresOneOf and exclude (fail via all)") { anax::ComponentFilter filter; filter.require<NPCComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.exclude<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[NPCComponent::GetTypeId()] = false; typeList[VelocityComponent::GetTypeId()] = false; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList) == false); } }; int main(int argc, char* argv[]) { return lest::run(specification, argc, argv); } <commit_msg>Fixed compilation errors in ComponentFilter tests<commit_after>/// /// anax tests /// An open source C++ entity system. /// /// Copyright (C) 2013-2014 Miguel Martin ([email protected]) /// /// 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 "lest.hpp" #include <anax/ComponentFilter.hpp> #include "Components.hpp" constexpr const unsigned MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST = 4; // All posibilities (with fail or pass): // requires // requiresOneOf // excludes // requires and excludes // requires and requiresOneOf // requiresOneOf and excludes // requires, requiresOneOf, and excludes // // TODO: fix maintainability of this code... It's just a lot of copy pasta atm const lest::test specification[] = { CASE("requires (pass)") { anax::ComponentFilter filter; filter.requires<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList)); }, CASE("requires (fail)") { anax::ComponentFilter filter; filter.requires<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requiesOneOf (pass with one)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList)); }, CASE("requiesOneOf (pass with all)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList)); }, CASE("requiesOneOf (fail)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = false; typeList[VelocityComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("excludes (pass)") { anax::ComponentFilter filter; filter.excludes<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = false; typeList[VelocityComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("excludes (fail via one)") { anax::ComponentFilter filter; filter.excludes<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("excludes (fail via all)") { anax::ComponentFilter filter; filter.excludes<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PlayerComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requiresOneOf and excludes (pass)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.excludes<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PositionComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList)); }, CASE("requiresOneOf and excludes (fail)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.excludes<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PositionComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requires and requiresOneOf (pass)") { anax::ComponentFilter filter; filter.requires<PlayerComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[PositionComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList)); }, CASE("requires and requiresOneOf (fail via requiresment)") { anax::ComponentFilter filter; filter.requires<PlayerComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = true; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requires and requiresOneOf (fail via requiresOneOf)") { anax::ComponentFilter filter; filter.requires<PlayerComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = false; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requires and requiresOneOf (fail via all)") { anax::ComponentFilter filter; filter.requires<PlayerComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = false; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requiresOneOf and excludes (pass)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.excludes<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList)); }, CASE("requiresOneOf and excludes (fail via requiresOneOf)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.excludes<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requiresOneOf and excludes (fail via excludes)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.excludes<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requiresOneOf and excludes (fail via all)") { anax::ComponentFilter filter; filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.excludes<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[VelocityComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requires, requiresOneOf and excludes (pass)") { anax::ComponentFilter filter; filter.requires<NPCComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.excludes<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[NPCComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList)); }, CASE("requires, requiresOneOf and excludes (fail via requires)") { anax::ComponentFilter filter; filter.requires<NPCComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.excludes<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[NPCComponent::GetTypeId()] = false; typeList[VelocityComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requires, requiresOneOf and excludes (fail via requiresOneOf)") { anax::ComponentFilter filter; filter.requires<NPCComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.excludes<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[NPCComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = false; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = false; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requires, requiresOneOf and excludes (fail via excludes)") { anax::ComponentFilter filter; filter.requires<NPCComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.excludes<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[NPCComponent::GetTypeId()] = true; typeList[VelocityComponent::GetTypeId()] = true; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList) == false); }, CASE("requires, requiresOneOf and excludes (fail via all)") { anax::ComponentFilter filter; filter.requires<NPCComponent>(); filter.requiresOneOf<PositionComponent, VelocityComponent>(); filter.excludes<PlayerComponent>(); anax::ComponentTypeList typeList(MAXIMUM_AMOUNT_OF_COMPONENT_TYPES_TO_TEST); typeList[NPCComponent::GetTypeId()] = false; typeList[VelocityComponent::GetTypeId()] = false; typeList[PositionComponent::GetTypeId()] = false; typeList[PlayerComponent::GetTypeId()] = true; EXPECT(filter.doesPassFilter(typeList) == false); } }; int main(int argc, char* argv[]) { return lest::run(specification, argc, argv); } <|endoftext|>
<commit_before>//Copyright (c) 2021 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include <gtest/gtest.h> #include "../src/settings/Settings.h" //Settings to generate walls with. #include "../src/utils/polygon.h" //To create example polygons. #include "../src/sliceDataStorage.h" //Sl #include "../src/WallsComputation.h" //Unit under test. namespace cura { /*! * Fixture that provides a basis for testing wall computation. */ class WallsComputationTest : public testing::Test { public: /*! * Settings to slice with. This is linked in the walls_computation fixture. */ Settings settings; /*! * WallsComputation instance to test with. The layer index will be 100. */ WallsComputation walls_computation; /*! * Basic 10x10mm square shape to work with. */ Polygons square_shape; WallsComputationTest() : walls_computation(settings, LayerIndex(100)) { square_shape.emplace_back(); square_shape.back().emplace_back(0, 0); square_shape.back().emplace_back(MM2INT(10), 0); square_shape.back().emplace_back(MM2INT(10), MM2INT(10)); square_shape.back().emplace_back(0, MM2INT(10)); //Settings for a simple 2 walls, about as basic as possible. settings.add("alternate_extra_perimeter", "false"); settings.add("beading_strategy_type", "inward_distributed"); settings.add("fill_outline_gaps", "false"); settings.add("initial_layer_line_width_factor", "100"); settings.add("magic_spiralize", "false"); settings.add("meshfix_maximum_deviation", "0.1"); settings.add("meshfix_maximum_extrusion_area_deviation", "0.01"); settings.add("meshfix_maximum_resolution", "0.01"); settings.add("min_bead_width", "0"); settings.add("min_feature_size", "0"); settings.add("wall_0_extruder_nr", "0"); settings.add("wall_0_inset", "0"); settings.add("wall_line_count", "2"); settings.add("wall_line_width_0", "0.4"); settings.add("wall_line_width_x", "0.4"); settings.add("wall_transition_angle", "30"); settings.add("wall_transition_filter_distance", "1"); settings.add("wall_transition_length", "1"); settings.add("wall_transition_threshold", "50"); settings.add("wall_x_extruder_nr", "0"); } }; /*! * Tests if something is generated in the basic happy case. */ TEST_F(WallsComputationTest, GenerateWallsForLayerSinglePart) { SliceLayer layer; layer.parts.emplace_back(); SliceLayerPart& part = layer.parts.back(); part.outline.add(square_shape); //Run the test. walls_computation.generateWalls(&layer); //Verify that something was generated. EXPECT_FALSE(part.wall_toolpaths.empty()) << "There must be some walls."; EXPECT_GT(part.print_outline.area(), 0) << "The print outline must encompass the outer wall, so it must be more than 0."; EXPECT_LE(part.print_outline.area(), square_shape.area()) << "The print outline must stay within the bounds of the original part."; EXPECT_GT(part.inner_area.area(), 0) << "The inner area must be within the innermost wall. There are not enough walls to fill the entire part, so there is a positive inner area."; EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part."; } /*! * Tests if the inner area is properly set. */ TEST_F(WallsComputationTest, GenerateWallsZeroWalls) { settings.add("wall_line_count", "0"); SliceLayer layer; layer.parts.emplace_back(); SliceLayerPart& part = layer.parts.back(); part.outline.add(square_shape); //Run the test. walls_computation.generateWalls(&layer); //Verify that there is still an inner area, outline and parts. EXPECT_EQ(part.inner_area.area(), square_shape.area()) << "There are no walls, so the inner area (for infill/skin) needs to be the entire part."; EXPECT_EQ(part.print_outline.area(), square_shape.area()) << "There are no walls, so the print outline encompasses the inner area exactly."; EXPECT_EQ(part.outline.area(), square_shape.area()) << "The outline is not modified."; EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part."; } }<commit_msg>Fix test<commit_after>//Copyright (c) 2021 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include <gtest/gtest.h> #include "../src/settings/Settings.h" //Settings to generate walls with. #include "../src/utils/polygon.h" //To create example polygons. #include "../src/sliceDataStorage.h" //Sl #include "../src/WallsComputation.h" //Unit under test. namespace cura { /*! * Fixture that provides a basis for testing wall computation. */ class WallsComputationTest : public testing::Test { public: /*! * Settings to slice with. This is linked in the walls_computation fixture. */ Settings settings; /*! * WallsComputation instance to test with. The layer index will be 100. */ WallsComputation walls_computation; /*! * Basic 10x10mm square shape to work with. */ Polygons square_shape; WallsComputationTest() : walls_computation(settings, LayerIndex(100)) { square_shape.emplace_back(); square_shape.back().emplace_back(0, 0); square_shape.back().emplace_back(MM2INT(10), 0); square_shape.back().emplace_back(MM2INT(10), MM2INT(10)); square_shape.back().emplace_back(0, MM2INT(10)); //Settings for a simple 2 walls, about as basic as possible. settings.add("alternate_extra_perimeter", "false"); settings.add("beading_strategy_type", "inward_distributed"); settings.add("fill_outline_gaps", "false"); settings.add("initial_layer_line_width_factor", "100"); settings.add("magic_spiralize", "false"); settings.add("meshfix_maximum_deviation", "0.1"); settings.add("meshfix_maximum_extrusion_area_deviation", "0.01"); settings.add("meshfix_maximum_resolution", "0.01"); settings.add("min_bead_width", "0"); settings.add("min_feature_size", "0"); settings.add("wall_0_extruder_nr", "0"); settings.add("wall_0_inset", "0"); settings.add("wall_line_count", "2"); settings.add("wall_line_width_0", "0.4"); settings.add("wall_line_width_x", "0.4"); settings.add("wall_transition_angle", "30"); settings.add("wall_transition_filter_distance", "1"); settings.add("wall_transition_length", "1"); settings.add("wall_transition_threshold", "50"); settings.add("wall_x_extruder_nr", "0"); settings.add("wall_distribution_count", "2"); } }; /*! * Tests if something is generated in the basic happy case. */ TEST_F(WallsComputationTest, GenerateWallsForLayerSinglePart) { SliceLayer layer; layer.parts.emplace_back(); SliceLayerPart& part = layer.parts.back(); part.outline.add(square_shape); //Run the test. walls_computation.generateWalls(&layer); //Verify that something was generated. EXPECT_FALSE(part.wall_toolpaths.empty()) << "There must be some walls."; EXPECT_GT(part.print_outline.area(), 0) << "The print outline must encompass the outer wall, so it must be more than 0."; EXPECT_LE(part.print_outline.area(), square_shape.area()) << "The print outline must stay within the bounds of the original part."; EXPECT_GT(part.inner_area.area(), 0) << "The inner area must be within the innermost wall. There are not enough walls to fill the entire part, so there is a positive inner area."; EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part."; } /*! * Tests if the inner area is properly set. */ TEST_F(WallsComputationTest, GenerateWallsZeroWalls) { settings.add("wall_line_count", "0"); SliceLayer layer; layer.parts.emplace_back(); SliceLayerPart& part = layer.parts.back(); part.outline.add(square_shape); //Run the test. walls_computation.generateWalls(&layer); //Verify that there is still an inner area, outline and parts. EXPECT_EQ(part.inner_area.area(), square_shape.area()) << "There are no walls, so the inner area (for infill/skin) needs to be the entire part."; EXPECT_EQ(part.print_outline.area(), square_shape.area()) << "There are no walls, so the print outline encompasses the inner area exactly."; EXPECT_EQ(part.outline.area(), square_shape.area()) << "The outline is not modified."; EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part."; } } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_GDT_EVALUATION_ELLIPTIC_HH #define DUNE_GDT_EVALUATION_ELLIPTIC_HH #include <tuple> #include <type_traits> #include <dune/common/dynmatrix.hh> #include <dune/common/typetraits.hh> #include <dune/common/static_assert.hh> #include <dune/stuff/functions/interfaces.hh> #include "interface.hh" namespace Dune { namespace GDT { namespace LocalEvaluation { // forward, to be used in the traits template< class LocalizableFunctionImp > class Elliptic; /** * \brief Traits for the Elliptic evaluation. */ template< class LocalizableFunctionImp > class EllipticTraits { public: typedef Elliptic< LocalizableFunctionImp > derived_type; typedef LocalizableFunctionImp LocalizableFunctionType; static_assert(std::is_base_of< Dune::Stuff::IsLocalizableFunction, LocalizableFunctionImp >::value, "LocalizableFunctionImp has to be derived from Stuff::IsLocalizableFunction."); }; /** * \brief Computes an elliptic evaluation. */ template< class LocalizableFunctionImp > class Elliptic : public LocalEvaluation::Codim0Interface< EllipticTraits< LocalizableFunctionImp >, 2 > { public: typedef EllipticTraits< LocalizableFunctionImp > Traits; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; Elliptic(const LocalizableFunctionType& inducingFunction) : inducingFunction_(inducingFunction) {} template< class EntityType > class LocalfunctionTuple { typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType; public: typedef std::tuple< std::shared_ptr< LocalfunctionType > > Type; }; template< class EntityType > typename LocalfunctionTuple< EntityType >::Type localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /** * \brief extracts the local functions and calls the correct order() method */ template< class E, class D, int d, class R, int rT, int rCT, int rA, int rCA > size_t order(const typename LocalfunctionTuple< E >::Type& localFuncs, const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& ansatzBase) const { const auto localFunction = std::get< 0 >(localFuncs); return order(*localFunction, testBase, ansatzBase); } /** * \todo add copydoc * \return localFunction.order() + (testBase.order() - 1) + (ansatzBase.order() - 1) */ template< class E, class D, int d, class R, int rL, int rCL, int rT, int rCT, int rA, int rCA > size_t order(const Stuff::LocalfunctionInterface< E, D, d, R, rL, rCL >& localFunction, const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& ansatzBase) const { return std::max(int(localFunction.order() + testBase.order() + ansatzBase.order() - 2), 0); } /** * \brief extracts the local functions and calls the correct evaluate() method */ template< class E, class D, int d, class R, int rT, int rCT, int rA, int rCA > static void evaluate(const typename LocalfunctionTuple< E >::Type& localFuncs, const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& ansatzBase, const Dune::FieldVector< D, d >& localPoint, Dune::DynamicMatrix< R >& ret) { const auto localFunction = std::get< 0 >(localFuncs); evaluate(*localFunction, testBase, ansatzBase, localPoint, ret); } template< class E, class D, int d, class R, int rL, int rCL, int rT, int rCT, int rA, int rCA > static void evaluate(const Stuff::LocalfunctionInterface< E, D, d, R, rL, rCL >& /*localFunction*/, const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& /*testBase*/, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& /*ansatzBase*/, const Dune::FieldVector< D, d >& /*localPoint*/, Dune::DynamicMatrix< R >& /*ret*/) { static_assert(Dune::AlwaysFalse< R >::value, "Not implemented for these dimensions!"); } /** * \brief Computes an elliptic evaluation for a scalar local function and scalar or vector valued basefunctionsets. * \tparam E EntityType * \tparam D DomainFieldType * \tparam d dimDomain * \tparam R RangeFieldType */ template< class E, class D, int d, class R, int r > static void evaluate(const Stuff::LocalfunctionInterface< E, D, d, R, 1, 1 >& localFunction, const Stuff::LocalfunctionSetInterface< E, D, d, R, r, 1 >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, r, 1 >& ansatzBase, const Dune::FieldVector< D, d >& localPoint, Dune::DynamicMatrix< R >& ret) { typedef typename Stuff::LocalfunctionSetInterface< E, D, d, R, r, 1 >::JacobianRangeType JacobianRangeType; // evaluate local function const auto functionValue = localFunction.evaluate(localPoint); // evaluate test gradient const size_t rows = testBase.size(); std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0)); testBase.jacobian(localPoint, testGradients); // evaluate ansatz gradient const size_t cols = ansatzBase.size(); std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0)); ansatzBase.jacobian(localPoint, ansatzGradients); // compute products assert(ret.rows() >= rows); assert(ret.cols() >= cols); for (size_t ii = 0; ii < rows; ++ii) { auto& retRow = ret[ii]; for (size_t jj = 0; jj < cols; ++jj) { retRow[jj] = functionValue * (ansatzGradients[jj][0] * testGradients[ii][0]); } } } // ... evaluate< ..., 1, 1 >(...) /** * \brief Computes an elliptic evaluation for a 2x2 matrix-valued local function and matrix-valued basefunctionsets. * \tparam E EntityType * \tparam D DomainFieldType * \tparam d dimDomain * \tparam R RangeFieldType * \note Unfortunately we need this explicit specialization, otherwise the compiler will complain for 1d grids. */ template< class E, class D, int d, class R > static void evaluate(const Stuff::LocalfunctionInterface< E, D, d, R, 2, 2 >& localFunction, const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& ansatzBase, const Dune::FieldVector< D, d >& localPoint, Dune::DynamicMatrix< R >& ret) { evaluate_matrix_valued_(localFunction, testBase, ansatzBase, localPoint, ret); } /** * \brief Computes an elliptic evaluation for a 3x3 matrix-valued local function and matrix-valued basefunctionsets. * \tparam E EntityType * \tparam D DomainFieldType * \tparam d dimDomain * \tparam R RangeFieldType * \note Unfortunately we need this explicit specialization, otherwise the compiler will complain for 1d grids. */ template< class E, class D, int d, class R > static void evaluate(const Stuff::LocalfunctionInterface< E, D, d, R, 3, 3 >& localFunction, const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& ansatzBase, const Dune::FieldVector< D, d >& localPoint, Dune::DynamicMatrix< R >& ret) { evaluate_matrix_valued_(localFunction, testBase, ansatzBase, localPoint, ret); } private: template< class E, class D, int d, class R > static void evaluate_matrix_valued_(const Stuff::LocalfunctionInterface< E, D, d, R, d, d >& localFunction, const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& ansatzBase, const Dune::FieldVector< D, d >& localPoint, Dune::DynamicMatrix< R >& ret) { typedef typename Stuff::LocalfunctionInterface< E, D, d, R, d, d >::RangeType DiffusionRangeType; typedef typename Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >::JacobianRangeType JacobianRangeType; typedef typename Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >::RangeType RangeType; // evaluate local function const DiffusionRangeType functionValue = localFunction.evaluate(localPoint); // evaluate test gradient const size_t rows = testBase.size(); std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0)); testBase.jacobian(localPoint, testGradients); // evaluate ansatz gradient const size_t cols = ansatzBase.size(); std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0)); ansatzBase.jacobian(localPoint, ansatzGradients); // compute products assert(ret.rows() >= rows); assert(ret.cols() >= cols); FieldVector< D, d > product(0.0); for (size_t ii = 0; ii < rows; ++ii) { auto& retRow = ret[ii]; for (size_t jj = 0; jj < cols; ++jj) { functionValue.mv(ansatzGradients[jj][0], product); retRow[jj] = product * testGradients[ii][0]; } } } // ... evaluate_matrix_valued_(...) const LocalizableFunctionType& inducingFunction_; }; // class LocalElliptic } // namespace Evaluation } // namespace GDT } // namespace Dune #endif // DUNE_GDT_EVALUATION_ELLIPTIC_HH <commit_msg>[localevaluation.elliptic] updated order() computation<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_GDT_EVALUATION_ELLIPTIC_HH #define DUNE_GDT_EVALUATION_ELLIPTIC_HH #include <tuple> #include <type_traits> #include <dune/common/dynmatrix.hh> #include <dune/common/typetraits.hh> #include <dune/common/static_assert.hh> #include <dune/stuff/functions/interfaces.hh> #include "interface.hh" namespace Dune { namespace GDT { namespace LocalEvaluation { // forward, to be used in the traits template< class LocalizableFunctionImp > class Elliptic; /** * \brief Traits for the Elliptic evaluation. */ template< class LocalizableFunctionImp > class EllipticTraits { public: typedef Elliptic< LocalizableFunctionImp > derived_type; typedef LocalizableFunctionImp LocalizableFunctionType; static_assert(std::is_base_of< Dune::Stuff::IsLocalizableFunction, LocalizableFunctionImp >::value, "LocalizableFunctionImp has to be derived from Stuff::IsLocalizableFunction."); }; /** * \brief Computes an elliptic evaluation. */ template< class LocalizableFunctionImp > class Elliptic : public LocalEvaluation::Codim0Interface< EllipticTraits< LocalizableFunctionImp >, 2 > { public: typedef EllipticTraits< LocalizableFunctionImp > Traits; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; Elliptic(const LocalizableFunctionType& inducingFunction) : inducingFunction_(inducingFunction) {} template< class EntityType > class LocalfunctionTuple { typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType; public: typedef std::tuple< std::shared_ptr< LocalfunctionType > > Type; }; template< class EntityType > typename LocalfunctionTuple< EntityType >::Type localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /** * \brief extracts the local functions and calls the correct order() method */ template< class E, class D, int d, class R, int rT, int rCT, int rA, int rCA > size_t order(const typename LocalfunctionTuple< E >::Type& localFuncs, const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& ansatzBase) const { const auto localFunction = std::get< 0 >(localFuncs); return order(*localFunction, testBase, ansatzBase); } /** * \todo add copydoc * \return localFunction.order() + (testBase.order() - 1) + (ansatzBase.order() - 1) */ template< class E, class D, int d, class R, int rL, int rCL, int rT, int rCT, int rA, int rCA > size_t order(const Stuff::LocalfunctionInterface< E, D, d, R, rL, rCL >& localFunction, const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& ansatzBase) const { return localFunction.order() + std::max(int(testBase.order() - 1), 0) + std::max(int(ansatzBase.order() - 1), 0); } /** * \brief extracts the local functions and calls the correct evaluate() method */ template< class E, class D, int d, class R, int rT, int rCT, int rA, int rCA > static void evaluate(const typename LocalfunctionTuple< E >::Type& localFuncs, const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& ansatzBase, const Dune::FieldVector< D, d >& localPoint, Dune::DynamicMatrix< R >& ret) { const auto localFunction = std::get< 0 >(localFuncs); evaluate(*localFunction, testBase, ansatzBase, localPoint, ret); } template< class E, class D, int d, class R, int rL, int rCL, int rT, int rCT, int rA, int rCA > static void evaluate(const Stuff::LocalfunctionInterface< E, D, d, R, rL, rCL >& /*localFunction*/, const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& /*testBase*/, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& /*ansatzBase*/, const Dune::FieldVector< D, d >& /*localPoint*/, Dune::DynamicMatrix< R >& /*ret*/) { static_assert(Dune::AlwaysFalse< R >::value, "Not implemented for these dimensions!"); } /** * \brief Computes an elliptic evaluation for a scalar local function and scalar or vector valued basefunctionsets. * \tparam E EntityType * \tparam D DomainFieldType * \tparam d dimDomain * \tparam R RangeFieldType */ template< class E, class D, int d, class R, int r > static void evaluate(const Stuff::LocalfunctionInterface< E, D, d, R, 1, 1 >& localFunction, const Stuff::LocalfunctionSetInterface< E, D, d, R, r, 1 >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, r, 1 >& ansatzBase, const Dune::FieldVector< D, d >& localPoint, Dune::DynamicMatrix< R >& ret) { typedef typename Stuff::LocalfunctionSetInterface< E, D, d, R, r, 1 >::JacobianRangeType JacobianRangeType; // evaluate local function const auto functionValue = localFunction.evaluate(localPoint); // evaluate test gradient const size_t rows = testBase.size(); std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0)); testBase.jacobian(localPoint, testGradients); // evaluate ansatz gradient const size_t cols = ansatzBase.size(); std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0)); ansatzBase.jacobian(localPoint, ansatzGradients); // compute products assert(ret.rows() >= rows); assert(ret.cols() >= cols); for (size_t ii = 0; ii < rows; ++ii) { auto& retRow = ret[ii]; for (size_t jj = 0; jj < cols; ++jj) { retRow[jj] = functionValue * (ansatzGradients[jj][0] * testGradients[ii][0]); } } } // ... evaluate< ..., 1, 1 >(...) /** * \brief Computes an elliptic evaluation for a 2x2 matrix-valued local function and matrix-valued basefunctionsets. * \tparam E EntityType * \tparam D DomainFieldType * \tparam d dimDomain * \tparam R RangeFieldType * \note Unfortunately we need this explicit specialization, otherwise the compiler will complain for 1d grids. */ template< class E, class D, int d, class R > static void evaluate(const Stuff::LocalfunctionInterface< E, D, d, R, 2, 2 >& localFunction, const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& ansatzBase, const Dune::FieldVector< D, d >& localPoint, Dune::DynamicMatrix< R >& ret) { evaluate_matrix_valued_(localFunction, testBase, ansatzBase, localPoint, ret); } /** * \brief Computes an elliptic evaluation for a 3x3 matrix-valued local function and matrix-valued basefunctionsets. * \tparam E EntityType * \tparam D DomainFieldType * \tparam d dimDomain * \tparam R RangeFieldType * \note Unfortunately we need this explicit specialization, otherwise the compiler will complain for 1d grids. */ template< class E, class D, int d, class R > static void evaluate(const Stuff::LocalfunctionInterface< E, D, d, R, 3, 3 >& localFunction, const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& ansatzBase, const Dune::FieldVector< D, d >& localPoint, Dune::DynamicMatrix< R >& ret) { evaluate_matrix_valued_(localFunction, testBase, ansatzBase, localPoint, ret); } private: template< class E, class D, int d, class R > static void evaluate_matrix_valued_(const Stuff::LocalfunctionInterface< E, D, d, R, d, d >& localFunction, const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >& ansatzBase, const Dune::FieldVector< D, d >& localPoint, Dune::DynamicMatrix< R >& ret) { typedef typename Stuff::LocalfunctionInterface< E, D, d, R, d, d >::RangeType DiffusionRangeType; typedef typename Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >::JacobianRangeType JacobianRangeType; typedef typename Stuff::LocalfunctionSetInterface< E, D, d, R, 1, 1 >::RangeType RangeType; // evaluate local function const DiffusionRangeType functionValue = localFunction.evaluate(localPoint); // evaluate test gradient const size_t rows = testBase.size(); std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0)); testBase.jacobian(localPoint, testGradients); // evaluate ansatz gradient const size_t cols = ansatzBase.size(); std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0)); ansatzBase.jacobian(localPoint, ansatzGradients); // compute products assert(ret.rows() >= rows); assert(ret.cols() >= cols); FieldVector< D, d > product(0.0); for (size_t ii = 0; ii < rows; ++ii) { auto& retRow = ret[ii]; for (size_t jj = 0; jj < cols; ++jj) { functionValue.mv(ansatzGradients[jj][0], product); retRow[jj] = product * testGradients[ii][0]; } } } // ... evaluate_matrix_valued_(...) const LocalizableFunctionType& inducingFunction_; }; // class LocalElliptic } // namespace Evaluation } // namespace GDT } // namespace Dune #endif // DUNE_GDT_EVALUATION_ELLIPTIC_HH <|endoftext|>
<commit_before>// AboutBox.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "AboutBox.h" #include "HeeksFrame.h" BEGIN_EVENT_TABLE( CAboutBox, wxDialog ) EVT_BUTTON( wxID_OK, CAboutBox::OnButtonOK ) END_EVENT_TABLE() CAboutBox::CAboutBox(wxWindow *parent):wxDialog(parent, wxID_ANY, _(""), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE) { wxPanel *panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxButton *ok_button = new wxButton(panel, wxID_OK, _("OK")); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); wxTextCtrl* text_ctrl = new wxTextCtrl( this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(800,600), wxTE_READONLY | wxTE_MULTILINE); wxString str = wxString(_T("HeeksCAD http://code.google.com/p/heekscad/\n\nusing Open CASCADE solid modeller - http://www.opencascade.org")) + wxString(_T("\n\nwindows made with wxWidgets 2.8.9 - http://wxwidgets.org")) + wxString(_T("\n\ntext uses glFont Copyright (c) 1998 Brad Fish E-mail: [email protected] Web: http://students.cs.byu.edu/~bfish/")) + wxString(_T("\n\nWith contributions from:\n Hirutso Enni")) + wxString(_T("\n\nThis is free, open source software.")); wxString version_str = wxGetApp().m_version_number; version_str.Replace(_T(" "), _T(".")); this->SetTitle(version_str); text_ctrl->WriteText(str + wxGetApp().m_frame->m_extra_about_box_str); //mainsizer->Add( text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() ); //mainsizer->Add( ok_button, wxSizerFlags().Align(wxALIGN_CENTER) ); mainsizer->Add( text_ctrl ); mainsizer->Add( ok_button ); mainsizer->RecalcSizes(); // tell frame to make use of sizer (or constraints, if any) panel->SetAutoLayout( true ); panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void CAboutBox::OnButtonOK(wxCommandEvent& event) { EndModal(wxID_OK); } <commit_msg>added #include <wx/dc.h> after reading http://code.google.com/p/heekscad/issues/detail?id=153<commit_after>// AboutBox.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include <wx/dc.h> #include "AboutBox.h" #include "HeeksFrame.h" BEGIN_EVENT_TABLE( CAboutBox, wxDialog ) EVT_BUTTON( wxID_OK, CAboutBox::OnButtonOK ) END_EVENT_TABLE() CAboutBox::CAboutBox(wxWindow *parent):wxDialog(parent, wxID_ANY, _(""), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE) { wxPanel *panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxButton *ok_button = new wxButton(panel, wxID_OK, _("OK")); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); wxTextCtrl* text_ctrl = new wxTextCtrl( this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(800,600), wxTE_READONLY | wxTE_MULTILINE); wxString str = wxString(_T("HeeksCAD http://code.google.com/p/heekscad/\n\nusing Open CASCADE solid modeller - http://www.opencascade.org")) + wxString(_T("\n\nwindows made with wxWidgets 2.8.9 - http://wxwidgets.org")) + wxString(_T("\n\ntext uses glFont Copyright (c) 1998 Brad Fish E-mail: [email protected] Web: http://students.cs.byu.edu/~bfish/")) + wxString(_T("\n\nWith contributions from:\n Hirutso Enni")) + wxString(_T("\n\nThis is free, open source software.")); wxString version_str = wxGetApp().m_version_number; version_str.Replace(_T(" "), _T(".")); this->SetTitle(version_str); text_ctrl->WriteText(str + wxGetApp().m_frame->m_extra_about_box_str); //mainsizer->Add( text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() ); //mainsizer->Add( ok_button, wxSizerFlags().Align(wxALIGN_CENTER) ); mainsizer->Add( text_ctrl ); mainsizer->Add( ok_button ); mainsizer->RecalcSizes(); // tell frame to make use of sizer (or constraints, if any) panel->SetAutoLayout( true ); panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void CAboutBox::OnButtonOK(wxCommandEvent& event) { EndModal(wxID_OK); } <|endoftext|>
<commit_before>// Copyright 2015 Cutehacks AS. All rights reserved. // License can be found in the LICENSE file. #include <QtCore/QRegExp> #include <QtCore/QTextCodec> #include <QtNetwork/QNetworkReply> #include <QtQml/QQmlEngine> #include "response.h" #include "serialization.h" namespace com { namespace cutehacks { namespace duperagent { ResponsePrototype::ResponsePrototype(QQmlEngine *engine, QNetworkReply *reply) : QObject(0), m_engine(engine), m_reply(reply) { QString type = m_reply->header(QNetworkRequest::ContentTypeHeader).toString(); QRegExp charsetRegexp(".*charset=(.*)[\\s]*", Qt::CaseInsensitive, QRegExp::RegExp2); if (charsetRegexp.exactMatch(type)) { m_charset = charsetRegexp.capturedTexts().at(1); } if (m_reply->isReadable()) { QByteArray data = m_reply->readAll(); QTextCodec *text = QTextCodec::codecForName(m_charset.toLatin1()); m_text = text ? text->makeDecoder()->toUnicode(data) : QString::fromUtf8(data); if (type.contains("application/json")) { // TODO: add error handling JsonCodec json(m_engine); m_body = json.parse(data); } else if (type.contains("application/x-www-form-urlencoded")) { // TODO: Implement parsing of form-urlencoded } else if (type.contains("multipart/form-data")) { // TODO: Implement parsing of form-data } } m_header = m_engine->newObject(); QList<QNetworkReply::RawHeaderPair>::const_iterator it = m_reply->rawHeaderPairs().cbegin(); for(; it != m_reply->rawHeaderPairs().cend(); it++) { m_header.setProperty( QString::fromUtf8((*it).first), QString::fromUtf8((*it).second)); } m_engine->setObjectOwnership(this, QQmlEngine::JavaScriptOwnership); } ResponsePrototype::~ResponsePrototype() { delete m_reply; } int ResponsePrototype::statusType() const { return statusCode() / 100; } int ResponsePrototype::statusCode() const { QVariant var = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); bool ok; int i = var.toInt(&ok); return ok ? i : 0; } bool ResponsePrototype::typeEquals(int type) const { return statusType() == type; } bool ResponsePrototype::statusEquals(int code) const { QVariant var = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); bool ok; int i = var.toInt(&ok); return ok && i == code; } bool ResponsePrototype::info() const { return typeEquals(1); } bool ResponsePrototype::ok() const { return typeEquals(2); } bool ResponsePrototype::clientError() const { return typeEquals(4); } bool ResponsePrototype::serverError() const { return typeEquals(5); } bool ResponsePrototype::error() const { return typeEquals(4) || typeEquals(5); } bool ResponsePrototype::accepted() const { return statusEquals(202); } bool ResponsePrototype::noContent() const { return statusEquals(204); } bool ResponsePrototype::badRequest() const { return statusEquals(400); } bool ResponsePrototype::unauthorized() const { return statusEquals(401); } bool ResponsePrototype::notAcceptable() const { return statusEquals(406); } bool ResponsePrototype::notFound() const { return statusEquals(404); } bool ResponsePrototype::forbidden() const { return statusEquals(403); } bool ResponsePrototype::fromCache() const { return m_reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); } QString ResponsePrototype::text() const { return m_text; } QString ResponsePrototype::charset() const { return m_charset; } QJSValue ResponsePrototype::body() const { return m_body; } QJSValue ResponsePrototype::header() const { return m_header; } } } } <commit_msg>Force headers to be stored as lower case<commit_after>// Copyright 2015 Cutehacks AS. All rights reserved. // License can be found in the LICENSE file. #include <QtCore/QRegExp> #include <QtCore/QTextCodec> #include <QtNetwork/QNetworkReply> #include <QtQml/QQmlEngine> #include "response.h" #include "serialization.h" namespace com { namespace cutehacks { namespace duperagent { ResponsePrototype::ResponsePrototype(QQmlEngine *engine, QNetworkReply *reply) : QObject(0), m_engine(engine), m_reply(reply) { QString type = m_reply->header(QNetworkRequest::ContentTypeHeader).toString(); QRegExp charsetRegexp(".*charset=(.*)[\\s]*", Qt::CaseInsensitive, QRegExp::RegExp2); if (charsetRegexp.exactMatch(type)) { m_charset = charsetRegexp.capturedTexts().at(1); } if (m_reply->isReadable()) { QByteArray data = m_reply->readAll(); QTextCodec *text = QTextCodec::codecForName(m_charset.toLatin1()); m_text = text ? text->makeDecoder()->toUnicode(data) : QString::fromUtf8(data); if (type.contains("application/json")) { // TODO: add error handling JsonCodec json(m_engine); m_body = json.parse(data); } else if (type.contains("application/x-www-form-urlencoded")) { // TODO: Implement parsing of form-urlencoded } else if (type.contains("multipart/form-data")) { // TODO: Implement parsing of form-data } } m_header = m_engine->newObject(); QList<QNetworkReply::RawHeaderPair>::const_iterator it = m_reply->rawHeaderPairs().cbegin(); for(; it != m_reply->rawHeaderPairs().cend(); it++) { m_header.setProperty( QString::fromUtf8((*it).first).toLower(), QString::fromUtf8((*it).second)); } m_engine->setObjectOwnership(this, QQmlEngine::JavaScriptOwnership); } ResponsePrototype::~ResponsePrototype() { delete m_reply; } int ResponsePrototype::statusType() const { return statusCode() / 100; } int ResponsePrototype::statusCode() const { QVariant var = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); bool ok; int i = var.toInt(&ok); return ok ? i : 0; } bool ResponsePrototype::typeEquals(int type) const { return statusType() == type; } bool ResponsePrototype::statusEquals(int code) const { QVariant var = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); bool ok; int i = var.toInt(&ok); return ok && i == code; } bool ResponsePrototype::info() const { return typeEquals(1); } bool ResponsePrototype::ok() const { return typeEquals(2); } bool ResponsePrototype::clientError() const { return typeEquals(4); } bool ResponsePrototype::serverError() const { return typeEquals(5); } bool ResponsePrototype::error() const { return typeEquals(4) || typeEquals(5); } bool ResponsePrototype::accepted() const { return statusEquals(202); } bool ResponsePrototype::noContent() const { return statusEquals(204); } bool ResponsePrototype::badRequest() const { return statusEquals(400); } bool ResponsePrototype::unauthorized() const { return statusEquals(401); } bool ResponsePrototype::notAcceptable() const { return statusEquals(406); } bool ResponsePrototype::notFound() const { return statusEquals(404); } bool ResponsePrototype::forbidden() const { return statusEquals(403); } bool ResponsePrototype::fromCache() const { return m_reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); } QString ResponsePrototype::text() const { return m_text; } QString ResponsePrototype::charset() const { return m_charset; } QJSValue ResponsePrototype::body() const { return m_body; } QJSValue ResponsePrototype::header() const { return m_header; } } } } <|endoftext|>
<commit_before>//---------------------------- fe_collection_01a.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2004, 2005 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- fe_collection_01a.cc --------------------------- // FECollection would throw an exception when its destructor is called. Check // that this is fixed #include "../tests.h" #include <base/logstream.h> #include <grid/tria.h> #include <grid/tria_iterator.h> #include <grid/grid_generator.h> #include <dofs/dof_accessor.h> #include <dofs/dof_handler.h> #include <hp/fe_collection.h> #include <fe/fe_q.h> #include <fstream> #include <iomanip> template <int dim> void check () { { const FE_Q<dim> fe_1(1); const FE_Q<dim> fe_2(2); FECollection<dim> fc; fc.add_fe (fe_1); fc.add_fe (fe_2); } deallog << dim << "d: OK" << std::endl; } int main() { std::ofstream logfile("fe_collection_01/output"); deallog << std::setprecision(4); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); check<1> (); check<2> (); check<3> (); } <commit_msg>Remove a test that appears no longer useful.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2014 Ross Kinder. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ringfile_internal.h" #include <gtest/gtest.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> std::string TempDir() { char * temp_path = getenv("TEMP"); if (!temp_path) { temp_path = getenv("TMP"); } if (!temp_path) { temp_path = getenv("TMPDIR"); } if (!temp_path) { temp_path = "."; } std::string path(temp_path); path += "/ringfile_test_XXXXXX"; if (mkdtemp(const_cast<char *>(path.c_str())) == NULL) { return ""; } return path; } std::string GetFileContents(const std::string & path) { struct stat buf; if (stat(path.c_str(), &buf) == -1) { return ""; } int fd = open(path.c_str(), O_RDONLY); if (fd == -1) { return ""; } std::string contents; contents.resize(buf.st_size); if (read(fd, const_cast<char *>(contents.c_str()), contents.size()) != contents.size()) { return ""; } close(fd); return contents; } TEST(RingfileTest, CannotOpenBogusPath) { std::string path = TempDir() + "/does not exist/ring"; Ringfile ringfile; ASSERT_FALSE(ringfile.Create(path, 1024)); ASSERT_EQ(ENOENT, ringfile.error()); } TEST(RingfileTest, CanReadAndWriteBasics) { std::string path = TempDir() + "/ring"; { Ringfile ringfile; ASSERT_TRUE(ringfile.Create(path, 1024)); std::string message("Hello, World!"); ringfile.Write(message.c_str(), message.size()); ringfile.Close(); } EXPECT_EQ(std::string( "RING" // magic number "\x00\x00\x00\x00" // flags "\x18\x00\x00\x00\x00\x00\x00\x00" // start offset "\x29\x00\x00\x00\x00\x00\x00\x00" // end offset "\x0d\x00\x00\x00" // record length "Hello, World!", 41), GetFileContents(path).substr(0, 41)); { Ringfile ringfile; ASSERT_TRUE(ringfile.Open(path, Ringfile::kRead)) << strerror(ringfile.error()); int next_record_size = ringfile.NextRecordSize(); EXPECT_EQ(13, next_record_size) << strerror(ringfile.error()); std::string buffer; buffer.resize(next_record_size); EXPECT_TRUE(ringfile.Read(const_cast<char *>(buffer.c_str()), next_record_size)); EXPECT_EQ("Hello, World!", buffer); next_record_size = ringfile.NextRecordSize(); EXPECT_EQ(-1, next_record_size); } } <commit_msg>add missing header for gcc build<commit_after>// Copyright (c) 2014 Ross Kinder. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ringfile_internal.h" #include <gtest/gtest.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> std::string TempDir() { char * temp_path = getenv("TEMP"); if (!temp_path) { temp_path = getenv("TMP"); } if (!temp_path) { temp_path = getenv("TMPDIR"); } if (!temp_path) { temp_path = "."; } std::string path(temp_path); path += "/ringfile_test_XXXXXX"; if (mkdtemp(const_cast<char *>(path.c_str())) == NULL) { return ""; } return path; } std::string GetFileContents(const std::string & path) { struct stat buf; if (stat(path.c_str(), &buf) == -1) { return ""; } int fd = open(path.c_str(), O_RDONLY); if (fd == -1) { return ""; } std::string contents; contents.resize(buf.st_size); if (read(fd, const_cast<char *>(contents.c_str()), contents.size()) != contents.size()) { return ""; } close(fd); return contents; } TEST(RingfileTest, CannotOpenBogusPath) { std::string path = TempDir() + "/does not exist/ring"; Ringfile ringfile; ASSERT_FALSE(ringfile.Create(path, 1024)); ASSERT_EQ(ENOENT, ringfile.error()); } TEST(RingfileTest, CanReadAndWriteBasics) { std::string path = TempDir() + "/ring"; { Ringfile ringfile; ASSERT_TRUE(ringfile.Create(path, 1024)); std::string message("Hello, World!"); ringfile.Write(message.c_str(), message.size()); ringfile.Close(); } EXPECT_EQ(std::string( "RING" // magic number "\x00\x00\x00\x00" // flags "\x18\x00\x00\x00\x00\x00\x00\x00" // start offset "\x29\x00\x00\x00\x00\x00\x00\x00" // end offset "\x0d\x00\x00\x00" // record length "Hello, World!", 41), GetFileContents(path).substr(0, 41)); { Ringfile ringfile; ASSERT_TRUE(ringfile.Open(path, Ringfile::kRead)) << strerror(ringfile.error()); int next_record_size = ringfile.NextRecordSize(); EXPECT_EQ(13, next_record_size) << strerror(ringfile.error()); std::string buffer; buffer.resize(next_record_size); EXPECT_TRUE(ringfile.Read(const_cast<char *>(buffer.c_str()), next_record_size)); EXPECT_EQ("Hello, World!", buffer); next_record_size = ringfile.NextRecordSize(); EXPECT_EQ(-1, next_record_size); } } <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief RX56N ファースト・サンプル @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/renesas.hpp" namespace { typedef device::system_io<12000000> SYSTEM_IO; typedef device::PORT<device::PORT7, device::bitpos::B0> LED; } int main(int argc, char** argv); int main(int argc, char** argv) { SYSTEM_IO::setup_system_clock(); LED::DIR = 1; while(1) { // utils::delay::milli_second(250); utils::delay::micro_second(2); LED::P = 0; // utils::delay::milli_second(250); utils::delay::micro_second(2); LED::P = 1; } } <commit_msg>update: blink delay<commit_after>//=====================================================================// /*! @file @brief RX56N ファースト・サンプル @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/renesas.hpp" namespace { typedef device::system_io<12000000> SYSTEM_IO; typedef device::PORT<device::PORT7, device::bitpos::B0> LED; } int main(int argc, char** argv); int main(int argc, char** argv) { SYSTEM_IO::setup_system_clock(); LED::DIR = 1; while(1) { utils::delay::milli_second(250); LED::P = 0; utils::delay::milli_second(250); LED::P = 1; } } <|endoftext|>
<commit_before>#include <unistd.h> #include <sys/socket.h> #include <wiringPi.h> #include <softPwm.h> #include "robotManager.hpp" #include "logger.hpp" #include "server.hpp" int RobotManager::lrFD[2], RobotManager::udFD[2]; std::thread RobotManager::lrThread, RobotManager::udThread; bool RobotManager::lrMoving, RobotManager::udMoving, RobotManager::blocked; unsigned int RobotManager::lCnt, RobotManager::rCnt; float RobotManager::lSpeed, RobotManager::rSpeed, RobotManager::speed; std::chrono::time_point<std::chrono::system_clock> RobotManager::codTime, RobotManager::distTime; void RobotManager::init() { wiringPiSetup(); reset(); lrMoving = udMoving = false; codTime = distTime = std::chrono::system_clock::now(); speed = lSpeed = rSpeed = 0; } void RobotManager::initServo() { pipe(lrFD); pipe(udFD); lrThread = std::thread(RobotManager::setCameraPosition, lrFD[0], LR_SERVO); udThread = std::thread(RobotManager::setCameraPosition, udFD[0], UD_SERVO); lrThread.detach(); udThread.detach(); } void RobotManager::closeServo() { close(lrFD[1]); close(udFD[1]); } void RobotManager::incLeftEncoder() { checkTime(); ++lCnt; } void RobotManager::incRightEncoder() { checkTime(); ++rCnt; } void RobotManager::checkTime() { auto now = std::chrono::system_clock::now(); if (std::chrono::duration_cast<std::chrono::milliseconds>(now-codTime).count() > 1000) { lSpeed = lCnt*0.01; rSpeed = rCnt*0.01; speed = (lSpeed+rSpeed)/2.f; lCnt = 0; rCnt = 0; codTime = now; } } void RobotManager::setCameraPosition(int fd, int servo) { while (1) { char buffer[4]; int err = read(fd, buffer, 4); if (err <= 0) { Logger::log("pipe error on " + getName(servo)); close(fd); break; } int delay = std::atoi(buffer); Logger::log("Setting camera position on " + getName(servo) + " with a " + std::to_string(delay) + "ms delay"); digitalWrite(servo, HIGH); delayMicroseconds(delay); digitalWrite(servo, LOW); delayMicroseconds(20000-delay); servo == LR_SERVO ? lrMoving = false : udMoving = false; } } void RobotManager::getDistance() { auto time = std::chrono::system_clock::now(); unsigned int echo = 0; while (1) { int current = digitalRead(ECHO); if (current) { auto now = std::chrono::system_clock::now(); echo += std::chrono::duration_cast<std::chrono::microseconds>(now-time).count(); time = now; } else { echo /= 58; if (echo > 0) { Logger::log("Obstacle distance: " + std::to_string(echo)); if (echo < 10) { blocked = true; setSpeeds(LEFT, 0); setSpeeds(RIGHT, 0); } } break; } } } void RobotManager::checkDistance() { auto now = std::chrono::system_clock::now(); if (std::chrono::duration_cast<std::chrono::milliseconds>(now-distTime).count() > 100) { digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW); distTime = now; } } std::string RobotManager::handle(std::string str) { Logger::log(str); std::string target, angleStr, powerStr; std::size_t first, second, third; first = str.find(';', 0); if (first != std::string::npos) target = str.substr(0, first); if (target == "M" || target == "C") { second = str.find(';', first+1); if (second != std::string::npos) angleStr = str.substr(first+1, second-first-1); third = str.find(';', second+1); if (third != std::string::npos) powerStr = str.substr(second+1, third-second-1); } if (target == "E") { return std::to_string(speed); } else if (target == "M") { // MOTOR int angle = std::stoi(angleStr); int power = std::stoi(powerStr); if (angle > -80 && angle <= 80) { blocked = false; setDirections(LEFT, FRONTWARDS); setDirections(RIGHT, FRONTWARDS); if (angle <= 0) { setSpeeds(LEFT, power*(1.f-(angle/(-80.f)))); setSpeeds(RIGHT, power); } else { setSpeeds(LEFT, power); setSpeeds(RIGHT, power*(1.f-(angle/80.f))); } } else if (!blocked && (angle <= -100 || angle > 100)) { checkDistance(); setDirections(LEFT, BACKWARDS); setDirections(RIGHT, BACKWARDS); if (angle <= 0) { setSpeeds(LEFT, power); setSpeeds(RIGHT, power*(1.f-(angle/100.f))); } else { setSpeeds(LEFT, power*(1.f-(angle/(-100.f)))); setSpeeds(RIGHT, power); } } else if (angle <= -80 && angle > -100) { setDirections(LEFT, BACKWARDS); setDirections(RIGHT, FRONTWARDS); setSpeeds(LEFT, power); setSpeeds(RIGHT, power); } else if (angle > 80 && angle <= 100) { setDirections(LEFT, FRONTWARDS); setDirections(RIGHT, BACKWARDS); setSpeeds(LEFT, power); setSpeeds(RIGHT, power); } } else if(target == "C") //CAMERA { if (angleStr != "-1" && !lrMoving) { lrMoving = true; write(lrFD[1], angleStr.data(), angleStr.size()); } if (powerStr != "-1" && !udMoving) { udMoving = true; write(udFD[1], powerStr.data(), powerStr.size()); } } return ""; } std::string RobotManager::getName(int pin) { switch(pin) { case FRONT_LEFT_WHEEL: return "Front Left Wheel"; case FRONT_RIGHT_WHEEL: return "Front Right Wheel"; case REAR_LEFT_WHEEL: return "Rear Left Wheel"; case REAR_RIGHT_WHEEL: return "Rear Right Wheel"; case LR_SERVO: return "Left-Right Servo"; case UD_SERVO: return "Up-Down Servo"; } return "Undefined Wheel"; } void RobotManager::handleSignal(int signal) { closeServo(); reset(); Server::stop(); Logger::stop(); exit(0); } void RobotManager::reset() { Logger::log("Setting pins..."); softPwmCreate(FRONT_LEFT_WHEEL, 0, 100); softPwmCreate(FRONT_RIGHT_WHEEL, 0, 100); softPwmCreate(REAR_LEFT_WHEEL, 0, 100); softPwmCreate(REAR_RIGHT_WHEEL, 0, 100); pinMode(FL_FRONTWARDS, OUTPUT); digitalWrite(FL_FRONTWARDS, LOW); pinMode(FL_BACKWARDS, OUTPUT); digitalWrite(FL_BACKWARDS, LOW); pinMode(FR_FRONTWARDS, OUTPUT); digitalWrite(FR_FRONTWARDS, LOW); pinMode(FR_BACKWARDS, OUTPUT); digitalWrite(FR_BACKWARDS, LOW); pinMode(RL_FRONTWARDS, OUTPUT); digitalWrite(RL_FRONTWARDS, LOW); pinMode(RL_BACKWARDS, OUTPUT); digitalWrite(RL_BACKWARDS, LOW); pinMode(RR_FRONTWARDS, OUTPUT); digitalWrite(RR_FRONTWARDS, LOW); pinMode(RR_BACKWARDS, OUTPUT); digitalWrite(RR_BACKWARDS, LOW); pinMode(COD1, INPUT); wiringPiISR(COD1, INT_EDGE_RISING, RobotManager::incLeftEncoder); pinMode(COD2, INPUT); wiringPiISR(COD2, INT_EDGE_RISING, RobotManager::incRightEncoder); pinMode(TRIG, OUTPUT); digitalWrite(TRIG, LOW); pinMode(ECHO, INPUT); wiringPiISR(ECHO, INT_EDGE_RISING, RobotManager::getDistance); pinMode(LR_SERVO, OUTPUT); pinMode(UD_SERVO, OUTPUT); } void RobotManager::setDirection(int wheel, int frontwards) { int w_front = -1, w_back = -1; switch(wheel) { case FRONT_LEFT_WHEEL: w_front = FL_FRONTWARDS; w_back = FL_BACKWARDS; break; case FRONT_RIGHT_WHEEL: w_front = FR_FRONTWARDS; w_back = FR_BACKWARDS; break; case REAR_LEFT_WHEEL: w_front = RL_FRONTWARDS; w_back = RL_BACKWARDS; break; case REAR_RIGHT_WHEEL: w_front = RR_FRONTWARDS; w_back = RR_BACKWARDS; break; } std::string msg = "Setting "; msg += (frontwards ? "frontwards" : "backwards"); msg += " direction for "; msg += getName(wheel); msg += "..."; //Logger::log(msg); if (w_front != -1) digitalWrite(w_front, frontwards); if (w_back != -1) digitalWrite(w_back, !frontwards); } void RobotManager::setSpeed(int wheel, int speed) { if (speed < 0) speed = 0; if (speed > 100) speed = 100; std::string msg = "Setting speed of "; msg += std::to_string(speed); msg += " for "; msg += getName(wheel); msg += "..."; //Logger::log(msg); softPwmWrite(wheel, speed); } void RobotManager::setDirections(int side, int direction) { if (side == 0) { setDirection(FRONT_LEFT_WHEEL, direction); setDirection(REAR_LEFT_WHEEL, direction); } else { setDirection(FRONT_RIGHT_WHEEL, direction); setDirection(REAR_RIGHT_WHEEL, direction); } } void RobotManager::setSpeeds(int side, int speed) { if (side == 0) { setSpeed(FRONT_LEFT_WHEEL, speed); setSpeed(REAR_LEFT_WHEEL, speed); } else { setSpeed(FRONT_RIGHT_WHEEL, speed); setSpeed(REAR_RIGHT_WHEEL, speed); } } <commit_msg>fix backwards<commit_after>#include <unistd.h> #include <sys/socket.h> #include <wiringPi.h> #include <softPwm.h> #include "robotManager.hpp" #include "logger.hpp" #include "server.hpp" int RobotManager::lrFD[2], RobotManager::udFD[2]; std::thread RobotManager::lrThread, RobotManager::udThread; bool RobotManager::lrMoving, RobotManager::udMoving, RobotManager::blocked; unsigned int RobotManager::lCnt, RobotManager::rCnt; float RobotManager::lSpeed, RobotManager::rSpeed, RobotManager::speed; std::chrono::time_point<std::chrono::system_clock> RobotManager::codTime, RobotManager::distTime; void RobotManager::init() { wiringPiSetup(); reset(); lrMoving = udMoving = false; codTime = distTime = std::chrono::system_clock::now(); speed = lSpeed = rSpeed = 0; } void RobotManager::initServo() { pipe(lrFD); pipe(udFD); lrThread = std::thread(RobotManager::setCameraPosition, lrFD[0], LR_SERVO); udThread = std::thread(RobotManager::setCameraPosition, udFD[0], UD_SERVO); lrThread.detach(); udThread.detach(); } void RobotManager::closeServo() { close(lrFD[1]); close(udFD[1]); } void RobotManager::incLeftEncoder() { checkTime(); ++lCnt; } void RobotManager::incRightEncoder() { checkTime(); ++rCnt; } void RobotManager::checkTime() { auto now = std::chrono::system_clock::now(); if (std::chrono::duration_cast<std::chrono::milliseconds>(now-codTime).count() > 1000) { lSpeed = lCnt*0.01; rSpeed = rCnt*0.01; speed = (lSpeed+rSpeed)/2.f; lCnt = 0; rCnt = 0; codTime = now; } } void RobotManager::setCameraPosition(int fd, int servo) { while (1) { char buffer[4]; int err = read(fd, buffer, 4); if (err <= 0) { Logger::log("pipe error on " + getName(servo)); close(fd); break; } int delay = std::atoi(buffer); Logger::log("Setting camera position on " + getName(servo) + " with a " + std::to_string(delay) + "ms delay"); digitalWrite(servo, HIGH); delayMicroseconds(delay); digitalWrite(servo, LOW); delayMicroseconds(20000-delay); servo == LR_SERVO ? lrMoving = false : udMoving = false; } } void RobotManager::getDistance() { auto time = std::chrono::system_clock::now(); unsigned int echo = 0; while (1) { int current = digitalRead(ECHO); if (current) { auto now = std::chrono::system_clock::now(); echo += std::chrono::duration_cast<std::chrono::microseconds>(now-time).count(); time = now; } else { echo /= 58; if (echo > 0) { Logger::log("Obstacle distance: " + std::to_string(echo)); if (echo < 10) { blocked = true; setSpeeds(LEFT, 0); setSpeeds(RIGHT, 0); } } break; } } } void RobotManager::checkDistance() { auto now = std::chrono::system_clock::now(); if (std::chrono::duration_cast<std::chrono::milliseconds>(now-distTime).count() > 100) { digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW); distTime = now; } } std::string RobotManager::handle(std::string str) { Logger::log(str); std::string target, angleStr, powerStr; std::size_t first, second, third; first = str.find(';', 0); if (first != std::string::npos) target = str.substr(0, first); if (target == "M" || target == "C") { second = str.find(';', first+1); if (second != std::string::npos) angleStr = str.substr(first+1, second-first-1); third = str.find(';', second+1); if (third != std::string::npos) powerStr = str.substr(second+1, third-second-1); } if (target == "E") { return std::to_string(speed); } else if (target == "M") { // MOTOR int angle = std::stoi(angleStr); int power = std::stoi(powerStr); if (angle > -80 && angle <= 80) { blocked = false; setDirections(LEFT, FRONTWARDS); setDirections(RIGHT, FRONTWARDS); if (angle <= 0) { setSpeeds(LEFT, power*(1.f-(angle/(-80.f)))); setSpeeds(RIGHT, power); } else { setSpeeds(LEFT, power); setSpeeds(RIGHT, power*(1.f-(angle/80.f))); } } else if (!blocked && (angle <= -100 || angle > 100)) { checkDistance(); setDirections(LEFT, BACKWARDS); setDirections(RIGHT, BACKWARDS); if (angle < 0) { setSpeeds(LEFT, power); setSpeeds(RIGHT, power*(angle/(-180.f))); } else { setSpeeds(LEFT, power*(angle/180.f)); setSpeeds(RIGHT, power); } } else if (angle <= -80 && angle > -100) { setDirections(LEFT, BACKWARDS); setDirections(RIGHT, FRONTWARDS); setSpeeds(LEFT, power); setSpeeds(RIGHT, power); } else if (angle > 80 && angle <= 100) { setDirections(LEFT, FRONTWARDS); setDirections(RIGHT, BACKWARDS); setSpeeds(LEFT, power); setSpeeds(RIGHT, power); } } else if(target == "C") //CAMERA { if (angleStr != "-1" && !lrMoving) { lrMoving = true; write(lrFD[1], angleStr.data(), angleStr.size()); } if (powerStr != "-1" && !udMoving) { udMoving = true; write(udFD[1], powerStr.data(), powerStr.size()); } } return ""; } std::string RobotManager::getName(int pin) { switch(pin) { case FRONT_LEFT_WHEEL: return "Front Left Wheel"; case FRONT_RIGHT_WHEEL: return "Front Right Wheel"; case REAR_LEFT_WHEEL: return "Rear Left Wheel"; case REAR_RIGHT_WHEEL: return "Rear Right Wheel"; case LR_SERVO: return "Left-Right Servo"; case UD_SERVO: return "Up-Down Servo"; } return "Undefined Wheel"; } void RobotManager::handleSignal(int signal) { closeServo(); reset(); Server::stop(); Logger::stop(); exit(0); } void RobotManager::reset() { Logger::log("Setting pins..."); softPwmCreate(FRONT_LEFT_WHEEL, 0, 100); softPwmCreate(FRONT_RIGHT_WHEEL, 0, 100); softPwmCreate(REAR_LEFT_WHEEL, 0, 100); softPwmCreate(REAR_RIGHT_WHEEL, 0, 100); pinMode(FL_FRONTWARDS, OUTPUT); digitalWrite(FL_FRONTWARDS, LOW); pinMode(FL_BACKWARDS, OUTPUT); digitalWrite(FL_BACKWARDS, LOW); pinMode(FR_FRONTWARDS, OUTPUT); digitalWrite(FR_FRONTWARDS, LOW); pinMode(FR_BACKWARDS, OUTPUT); digitalWrite(FR_BACKWARDS, LOW); pinMode(RL_FRONTWARDS, OUTPUT); digitalWrite(RL_FRONTWARDS, LOW); pinMode(RL_BACKWARDS, OUTPUT); digitalWrite(RL_BACKWARDS, LOW); pinMode(RR_FRONTWARDS, OUTPUT); digitalWrite(RR_FRONTWARDS, LOW); pinMode(RR_BACKWARDS, OUTPUT); digitalWrite(RR_BACKWARDS, LOW); pinMode(COD1, INPUT); wiringPiISR(COD1, INT_EDGE_RISING, RobotManager::incLeftEncoder); pinMode(COD2, INPUT); wiringPiISR(COD2, INT_EDGE_RISING, RobotManager::incRightEncoder); pinMode(TRIG, OUTPUT); digitalWrite(TRIG, LOW); pinMode(ECHO, INPUT); wiringPiISR(ECHO, INT_EDGE_RISING, RobotManager::getDistance); pinMode(LR_SERVO, OUTPUT); pinMode(UD_SERVO, OUTPUT); } void RobotManager::setDirection(int wheel, int frontwards) { int w_front = -1, w_back = -1; switch(wheel) { case FRONT_LEFT_WHEEL: w_front = FL_FRONTWARDS; w_back = FL_BACKWARDS; break; case FRONT_RIGHT_WHEEL: w_front = FR_FRONTWARDS; w_back = FR_BACKWARDS; break; case REAR_LEFT_WHEEL: w_front = RL_FRONTWARDS; w_back = RL_BACKWARDS; break; case REAR_RIGHT_WHEEL: w_front = RR_FRONTWARDS; w_back = RR_BACKWARDS; break; } std::string msg = "Setting "; msg += (frontwards ? "frontwards" : "backwards"); msg += " direction for "; msg += getName(wheel); msg += "..."; //Logger::log(msg); if (w_front != -1) digitalWrite(w_front, frontwards); if (w_back != -1) digitalWrite(w_back, !frontwards); } void RobotManager::setSpeed(int wheel, int speed) { if (speed < 0) speed = 0; if (speed > 100) speed = 100; std::string msg = "Setting speed of "; msg += std::to_string(speed); msg += " for "; msg += getName(wheel); msg += "..."; //Logger::log(msg); softPwmWrite(wheel, speed); } void RobotManager::setDirections(int side, int direction) { if (side == 0) { setDirection(FRONT_LEFT_WHEEL, direction); setDirection(REAR_LEFT_WHEEL, direction); } else { setDirection(FRONT_RIGHT_WHEEL, direction); setDirection(REAR_RIGHT_WHEEL, direction); } } void RobotManager::setSpeeds(int side, int speed) { if (side == 0) { setSpeed(FRONT_LEFT_WHEEL, speed); setSpeed(REAR_LEFT_WHEEL, speed); } else { setSpeed(FRONT_RIGHT_WHEEL, speed); setSpeed(REAR_RIGHT_WHEEL, speed); } } <|endoftext|>
<commit_before>/******************************************************************************* * tests/data/block_pool_test.cpp * * Part of Project Thrill. * * Copyright (C) 2015 Tobias Sturm <[email protected]> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <gtest/gtest.h> #include <thrill/data/block_pool.hpp> #include <string> using namespace thrill; struct BlockPoolTest : public::testing::Test { BlockPoolTest() : mem_manager_(nullptr), block_pool_(&mem_manager_) { } mem::Manager mem_manager_; data::BlockPool block_pool_; }; TEST_F(BlockPoolTest, AllocateAccountsSizeInManager) { auto block = block_pool_.AllocateBlock(8); ASSERT_EQ(8u, mem_manager_.total()); auto block2 = block_pool_.AllocateBlock(2); ASSERT_EQ(10u, mem_manager_.total()); } TEST_F(BlockPoolTest, AllocateIncreasesBlockCountByOne) { auto block = block_pool_.AllocateBlock(8); ASSERT_EQ(1u, block_pool_.block_count()); } TEST_F(BlockPoolTest, BlocksOutOfScopeReduceBlockCount) { { auto block = block_pool_.AllocateBlock(8); } ASSERT_EQ(0u, block_pool_.block_count()); } TEST_F(BlockPoolTest, BlocksOutOfScopeAreAccountetInMemManager) { { auto block = block_pool_.AllocateBlock(8); } ASSERT_EQ(0u, mem_manager_.total()); } TEST_F(BlockPoolTest, AllocatedBlocksHaveRefCountOne) { auto block = block_pool_.AllocateBlock(8); ASSERT_EQ(1u, block->reference_count()); } /******************************************************************************/ <commit_msg>adapt to new ctor of mem::Manager<commit_after>/******************************************************************************* * tests/data/block_pool_test.cpp * * Part of Project Thrill. * * Copyright (C) 2015 Tobias Sturm <[email protected]> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <gtest/gtest.h> #include <thrill/data/block_pool.hpp> #include <string> using namespace thrill; struct BlockPoolTest : public::testing::Test { BlockPoolTest() : mem_manager_(nullptr, "mem"), block_pool_(&mem_manager_) { } mem::Manager mem_manager_; data::BlockPool block_pool_; }; TEST_F(BlockPoolTest, AllocateAccountsSizeInManager) { auto block = block_pool_.AllocateBlock(8); ASSERT_EQ(8u, mem_manager_.total()); auto block2 = block_pool_.AllocateBlock(2); ASSERT_EQ(10u, mem_manager_.total()); } TEST_F(BlockPoolTest, AllocateIncreasesBlockCountByOne) { auto block = block_pool_.AllocateBlock(8); ASSERT_EQ(1u, block_pool_.block_count()); } TEST_F(BlockPoolTest, BlocksOutOfScopeReduceBlockCount) { { auto block = block_pool_.AllocateBlock(8); } ASSERT_EQ(0u, block_pool_.block_count()); } TEST_F(BlockPoolTest, BlocksOutOfScopeAreAccountetInMemManager) { { auto block = block_pool_.AllocateBlock(8); } ASSERT_EQ(0u, mem_manager_.total()); } TEST_F(BlockPoolTest, AllocatedBlocksHaveRefCountOne) { auto block = block_pool_.AllocateBlock(8); ASSERT_EQ(1u, block->reference_count()); } /******************************************************************************/ <|endoftext|>
<commit_before>#ifndef DUNE_STUFF_LA_ALGORITHM_NORMALIZE_HH #define DUNE_STUFF_LA_ALGORITHM_NORMALIZE_HH #include <dune/common/typetraits.hh> #include <dune/common/static_assert.hh> #include <dune/stuff/la/container/interface.hh> #include <dune/stuff/la/container/eigen.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/color.hh> namespace Dune { namespace Stuff { namespace LA { namespace Algorithm { template< class ContainerType > void normalize(ContainerType& /*_vector*/) { dune_static_assert((Dune::AlwaysFalse< ContainerType >::value), "ERROR: not implemeneted for this ContainerType!"); } //#if HAVE_EIGEN template< class ElementType > void normalize(Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& _vector) { // if this is an empty vector report and do nothing if (_vector.size() == 0) { if (!Dune::Stuff::Common::Logger().created()) Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_CONSOLE | Dune::Stuff::Common::LOG_DEBUG); Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug(); debug << "\n" << Dune::Stuff::Common::colorString("WARNING:") << " Dune::Stuff::LA::Algorithm::normalize() called with an empty '_vector'!" << std::endl; } else { // compute L2-norm const ElementType norm = std::sqrt(_vector.backend().transpose() * _vector.backend()); // normalize _vector.backend() /= norm; } } // void normalize(Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& _vector) template< class ElementType > void normalize(Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType >& _matrix) { // if this is an empty matrix report and do nothing if (_matrix.rows() == 0 || _matrix.cols() == 0) { if (!Dune::Stuff::Common::Logger().created()) Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_CONSOLE | Dune::Stuff::Common::LOG_DEBUG); Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug(); debug << "\n" << Dune::Stuff::Common::colorString("WARNING:") << " Dune::Stuff::LA::Algorithm::normalize() called with an empty '_matrix'!" << std::endl; } else { // this is a matrix, check how to interpret it if (_matrix.rows() == 1) { // this is a row-vector, proceed // compute L2-norm const ElementType norm = std::sqrt(_matrix.backend().row(0) * _matrix.backend().row(0).transpose()); // normalize _matrix.backend() /= norm; } else if (_matrix.cols() == 1) { // this i a column-vector, proceed // compute L2-norm const ElementType norm = std::sqrt(_matrix.backend().col(0).transpose() * _matrix.backend().col(0)); // normalize _matrix.backend() /= norm; } else DUNE_THROW(Dune::RangeError, "\nERROR: not implemented for matrices!"); } } // void normalize(Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType >& _matrix) template< class ElementType > void normalize(Dune::Stuff::LA::Container::EigenRowMajorSparseMatrix< ElementType >& /*_vector*/) { dune_static_assert((Dune::AlwaysFalse< ElementType >::value), "ERROR: not implemeneted for EigenRowMajorSparseMatrix!"); } //#endif // HAVE_EIGEN template< class ScalarProductType, class ContainerType > void normalize(const ScalarProductType& /*scalarProduct*/, ContainerType& /*_columnVectors*/) { dune_static_assert((Dune::AlwaysFalse< ScalarProductType >::value || Dune::AlwaysFalse< ContainerType >::value), "ERROR: not implemeneted for this ContainerType!"); } //#if HAVE_EIGEN template< class ElementType > void normalize(const Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType >& /*_scalarProduct*/, Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& /*_columnVectors*/) { dune_static_assert((Dune::AlwaysFalse< ElementType >::value), "ERROR: not implemeneted yet!"); } // void normalize(Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& _vector) template< class ElementType > void normalize(const Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType >& _scalarProduct, Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType >& _matrix) { // if this is an empty matrix report and do nothing if (_matrix.rows() == 0 || _matrix.cols() == 0) { if (!Dune::Stuff::Common::Logger().created()) Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_CONSOLE | Dune::Stuff::Common::LOG_DEBUG); Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug(); debug << "\n" << Dune::Stuff::Common::colorString("WARNING:") << " Dune::Stuff::LA::Algorithm::normalize() called with an empty '_matrix'!" << std::endl; } else { // this is a matrix, check how to interpret it if (_matrix.rows() == 1) { // this is a row-vector, check sizes assert(_matrix.cols() == _scalarProduct.rows()); assert(_matrix.cols() == _scalarProduct.cols()); // compute L2-norm const ElementType norm = std::sqrt(_matrix.backend().row(0) * _scalarProduct.backend() * _matrix.backend().row(0).transpose()); // normalize _matrix.backend() /= norm; } else if (_matrix.cols() == 1) { // this i a column-vector, check sizes assert(_matrix.rows() == _scalarProduct.rows()); assert(_matrix.rows() == _scalarProduct.cols()); // compute L2-norm const ElementType norm = std::sqrt(_matrix.backend().col(0).transpose() * _scalarProduct.backend() * _matrix.backend().col(0)); // normalize _matrix.backend() /= norm; } else DUNE_THROW(Dune::RangeError, "\nERROR: not implemented for matrices!"); } } // void normalize(Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& _vector) template< class ElementType > void normalize(const Dune::Stuff::LA::Container::EigenRowMajorSparseMatrix< ElementType >& /*_scalarProduct*/, Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& /*_columnVectors*/) { dune_static_assert((Dune::AlwaysFalse< ElementType >::value), "ERROR: not implemeneted yet!"); } // void normalize(Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& _vector) template< class ElementType > void normalize(const Dune::Stuff::LA::Container::EigenRowMajorSparseMatrix< ElementType >& /*_scalarProduct*/, Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType >& /*_columnVectors*/) { dune_static_assert((Dune::AlwaysFalse< ElementType >::value), "ERROR: not implemeneted yet!"); } // void normalize(Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& _vector) //#endif // HAVE_EIGEN } // namespace Algorithm } // namespace LA } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_LA_ALGORITHM_NORMALIZE_HH <commit_msg>[la.algorithm.normalize]<commit_after>#ifndef DUNE_STUFF_LA_ALGORITHM_NORMALIZE_HH #define DUNE_STUFF_LA_ALGORITHM_NORMALIZE_HH #include <dune/common/typetraits.hh> #include <dune/common/static_assert.hh> #include <dune/stuff/la/container/interface.hh> #include <dune/stuff/la/container/eigen.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/color.hh> namespace Dune { namespace Stuff { namespace LA { namespace Algorithm { template< class ContainerType > void normalize(ContainerType& /*_vector*/) { dune_static_assert((Dune::AlwaysFalse< ContainerType >::value), "ERROR: not implemeneted for this ContainerType!"); } //#if HAVE_EIGEN template< class ElementType > void normalize(Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& _vector) { // if this is an empty vector report and do nothing if (_vector.size() == 0) { if (!Dune::Stuff::Common::Logger().created()) Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_CONSOLE | Dune::Stuff::Common::LOG_DEBUG); Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug(); debug << "\n" << Dune::Stuff::Common::colorString("WARNING:") << " Dune::Stuff::LA::Algorithm::normalize() called with an empty '_vector'!" << std::endl; } else { // compute L2-norm const ElementType norm = std::sqrt(_vector.backend().transpose() * _vector.backend()); // normalize _vector.backend() /= norm; } } // void normalize(Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& _vector) template< class ElementType > void normalize(Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType >& _matrix) { // if this is an empty matrix report and do nothing if (_matrix.rows() == 0 || _matrix.cols() == 0) { if (!Dune::Stuff::Common::Logger().created()) Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_CONSOLE | Dune::Stuff::Common::LOG_DEBUG); Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug(); debug << "\n" << Dune::Stuff::Common::colorString("WARNING:") << " Dune::Stuff::LA::Algorithm::normalize() called with an empty '_matrix'!" << std::endl; } else { // this is a matrix, check how to interpret it if (_matrix.rows() == 1) { // this is a row-vector, proceed // compute L2-norm const ElementType norm = std::sqrt(_matrix.backend().row(0) * _matrix.backend().row(0).transpose()); // normalize _matrix.backend() /= norm; } else if (_matrix.cols() == 1) { // this i a column-vector, proceed // compute L2-norm const ElementType norm = std::sqrt(_matrix.backend().col(0).transpose() * _matrix.backend().col(0)); // normalize _matrix.backend() /= norm; } else DUNE_THROW(Dune::RangeError, "\nERROR: not implemented for matrices!"); } } // void normalize(Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType >& _matrix) template< class ElementType > void normalize(Dune::Stuff::LA::Container::EigenRowMajorSparseMatrix< ElementType >& /*_vector*/) { dune_static_assert((Dune::AlwaysFalse< ElementType >::value), "ERROR: not implemeneted for EigenRowMajorSparseMatrix!"); } //#endif // HAVE_EIGEN template< class ScalarProductType, class ContainerType > void normalize(const ScalarProductType& /*scalarProduct*/, ContainerType& /*_columnVectors*/) { dune_static_assert((Dune::AlwaysFalse< ScalarProductType >::value || Dune::AlwaysFalse< ContainerType >::value), "ERROR: not implemeneted for this ContainerType!"); } //#if HAVE_EIGEN template< class ElementType > void normalize(const Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType >& /*_scalarProduct*/, Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& /*_columnVectors*/) { dune_static_assert((Dune::AlwaysFalse< ElementType >::value), "ERROR: not implemeneted yet!"); } // void normalize(Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& _vector) template< class ElementType > void normalize(const Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType >& _scalarProduct, Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType >& _matrix) { // if this is an empty matrix, report and do nothing if (_matrix.rows() == 0 || _matrix.cols() == 0) { if (!Dune::Stuff::Common::Logger().created()) Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_CONSOLE | Dune::Stuff::Common::LOG_DEBUG); Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug(); debug << "\n" << Dune::Stuff::Common::colorString("WARNING:") << " Dune::Stuff::LA::Algorithm::normalize() called with an empty '_matrix'!" << std::endl; } else { // this is a matrix, check how to interpret it if (_matrix.rows() == 1) { // this is a row-vector, check sizes assert(_matrix.cols() == _scalarProduct.rows()); assert(_matrix.cols() == _scalarProduct.cols()); // compute L2-norm const ElementType norm = std::sqrt(_matrix.backend().row(0) * _scalarProduct.backend() * _matrix.backend().row(0).transpose()); // normalize _matrix.backend() /= norm; } else if (_matrix.cols() == 1) { // this i a column-vector, check sizes assert(_matrix.rows() == _scalarProduct.rows()); assert(_matrix.rows() == _scalarProduct.cols()); // compute L2-norm const ElementType norm = std::sqrt(_matrix.backend().col(0).transpose() * _scalarProduct.backend() * _matrix.backend().col(0)); // normalize _matrix.backend() /= norm; } else DUNE_THROW(Dune::RangeError, "\nERROR: not implemented for matrices!"); } } // void normalize(Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& _vector) template< class ElementType > bool normalize(const Dune::Stuff::LA::Container::EigenRowMajorSparseMatrix< ElementType >& _scalarProduct, Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& _vector, const ElementType& epsilon = 1e-10) { // if this is an empty vector, report and do nothing if (_vector.size() == 0) { if (!Dune::Stuff::Common::Logger().created()) Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_CONSOLE | Dune::Stuff::Common::LOG_DEBUG); Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug(); debug << "\n" << Dune::Stuff::Common::colorString("WARNING:") << " Dune::Stuff::LA::Algorithm::normalize() called with an empty '_vector'!" << std::endl; } else { // this is a vector, noramlize it // therefore, check sizes, assert(_vector.size() == _scalarProduct.rows()); assert(_vector.size() == _scalarProduct.cols()); // compute the L2-norm and const ElementType norm = std::sqrt(_vector.backend().transpose() * _scalarProduct.backend() * _vector.backend()); if (norm < epsilon) return false; else { // normalize _vector.backend() /= norm; return true; } } } // void normalize(Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& _vector) template< class ElementType > void normalize(const Dune::Stuff::LA::Container::EigenRowMajorSparseMatrix< ElementType >& /*_scalarProduct*/, Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType >& /*_columnVectors*/) { dune_static_assert((Dune::AlwaysFalse< ElementType >::value), "ERROR: not implemeneted yet!"); } // void normalize(Dune::Stuff::LA::Container::EigenDenseVector< ElementType >& _vector) //#endif // HAVE_EIGEN } // namespace Algorithm } // namespace LA } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_LA_ALGORITHM_NORMALIZE_HH <|endoftext|>
<commit_before>#include "robot_editor.h" #include "robot_preview.h" #include <cstdlib> RobotEditor::RobotEditor() { main_window_ui_.setupUi(&main_window_); robot_preview_ = new RobotPreview(main_window_ui_.rvizFrame); QObject::connect(main_window_ui_.actionExit, SIGNAL(triggered()), this, SLOT(exitTrigger())); QObject::connect(main_window_ui_.actionOpen, SIGNAL(triggered()), this, SLOT(openTrigger())); QObject::connect(main_window_ui_.actionSave, SIGNAL(triggered()), this, SLOT(saveTrigger())); QObject::connect(main_window_ui_.actionSave_As, SIGNAL(triggered()), this, SLOT(saveAsTrigger())); } RobotEditor::~RobotEditor() { delete robot_preview_; } void RobotEditor::show() { main_window_.show(); } void RobotEditor::openTrigger() { printf("Open selected\n"); } void RobotEditor::saveTrigger() { printf("Save selected\n"); } void RobotEditor::saveAsTrigger() { printf("Save as selected\n"); } void RobotEditor::exitTrigger() { printf("Exit selected\n"); } <commit_msg>Exit menu action now works.<commit_after>#include "robot_editor.h" #include "robot_preview.h" #include <cstdlib> RobotEditor::RobotEditor() { main_window_ui_.setupUi(&main_window_); robot_preview_ = new RobotPreview(main_window_ui_.rvizFrame); QObject::connect(main_window_ui_.actionExit, SIGNAL(triggered()), this, SLOT(exitTrigger())); QObject::connect(main_window_ui_.actionOpen, SIGNAL(triggered()), this, SLOT(openTrigger())); QObject::connect(main_window_ui_.actionSave, SIGNAL(triggered()), this, SLOT(saveTrigger())); QObject::connect(main_window_ui_.actionSave_As, SIGNAL(triggered()), this, SLOT(saveAsTrigger())); } RobotEditor::~RobotEditor() { delete robot_preview_; } void RobotEditor::show() { main_window_.show(); } void RobotEditor::openTrigger() { printf("Open selected\n"); } void RobotEditor::saveTrigger() { printf("Save selected\n"); } void RobotEditor::saveAsTrigger() { printf("Save as selected\n"); } void RobotEditor::exitTrigger() { // quit the application exit(0); } <|endoftext|>
<commit_before>#include <tests/lib/test.h> #include <tests/lib/glib-helpers/test-conn-helper.h> #include <tests/lib/glib/echo/chan.h> #include <tests/lib/glib/echo/conn.h> #include <tests/lib/glib/future/conference/chan.h> #include <TelepathyQt4/Connection> #include <TelepathyQt4/PendingReady> #include <telepathy-glib/debug.h> using namespace Tp; class TestConferenceChan : public Test { Q_OBJECT public: TestConferenceChan(QObject *parent = 0) : Test(parent), mConn(0), mContactRepo(0), mTextChan1Service(0), mTextChan2Service(0), mConferenceChanService(0) { } protected Q_SLOTS: void onConferenceChannelMerged(const Tp::ChannelPtr &); void onConferenceChannelRemoved(const Tp::ChannelPtr &channel, const Tp::Channel::GroupMemberChangeDetails &details); private Q_SLOTS: void initTestCase(); void init(); void testConference(); void cleanup(); void cleanupTestCase(); private: TestConnHelper *mConn; TpHandleRepoIface *mContactRepo; ChannelPtr mChan; QString mTextChan1Path; ExampleEchoChannel *mTextChan1Service; QString mTextChan2Path; ExampleEchoChannel *mTextChan2Service; QString mTextChan3Path; ExampleEchoChannel *mTextChan3Service; QString mConferenceChanPath; TpTestsConferenceChannel *mConferenceChanService; ChannelPtr mChannelMerged; ChannelPtr mChannelRemovedDetailed; Channel::GroupMemberChangeDetails mChannelRemovedDetailedDetails; }; void TestConferenceChan::onConferenceChannelMerged(const Tp::ChannelPtr &channel) { mChannelMerged = channel; mLoop->exit(0); } void TestConferenceChan::onConferenceChannelRemoved(const Tp::ChannelPtr &channel, const Tp::Channel::GroupMemberChangeDetails &details) { mChannelRemovedDetailed = channel; mChannelRemovedDetailedDetails = details; mLoop->exit(0); } void TestConferenceChan::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("chan-conference"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); mConn = new TestConnHelper(this, EXAMPLE_TYPE_ECHO_CONNECTION, "account", "[email protected]", "protocol", "example", NULL); QCOMPARE(mConn->connect(), true); // create a Channel by magic, rather than doing D-Bus round-trips for it mContactRepo = tp_base_connection_get_handles(TP_BASE_CONNECTION(mConn->service()), TP_HANDLE_TYPE_CONTACT); guint handle1 = tp_handle_ensure(mContactRepo, "someone1@localhost", 0, 0); guint handle2 = tp_handle_ensure(mContactRepo, "someone2@localhost", 0, 0); guint handle3 = tp_handle_ensure(mContactRepo, "someone3@localhost", 0, 0); QByteArray chanPath; GPtrArray *initialChannels = g_ptr_array_new(); mTextChan1Path = mConn->objectPath() + QLatin1String("/TextChannel/1"); chanPath = mTextChan1Path.toAscii(); mTextChan1Service = EXAMPLE_ECHO_CHANNEL(g_object_new( EXAMPLE_TYPE_ECHO_CHANNEL, "connection", mConn->service(), "object-path", chanPath.data(), "handle", handle1, NULL)); g_ptr_array_add(initialChannels, g_strdup(chanPath.data())); mTextChan2Path = mConn->objectPath() + QLatin1String("/TextChannel/2"); chanPath = mTextChan2Path.toAscii(); mTextChan2Service = EXAMPLE_ECHO_CHANNEL(g_object_new( EXAMPLE_TYPE_ECHO_CHANNEL, "connection", mConn->service(), "object-path", chanPath.data(), "handle", handle2, NULL)); g_ptr_array_add(initialChannels, g_strdup(chanPath.data())); // let's not add this one to initial channels mTextChan3Path = mConn->objectPath() + QLatin1String("/TextChannel/3"); chanPath = mTextChan3Path.toAscii(); mTextChan3Service = EXAMPLE_ECHO_CHANNEL(g_object_new( EXAMPLE_TYPE_ECHO_CHANNEL, "connection", mConn->service(), "object-path", chanPath.data(), "handle", handle3, NULL)); mConferenceChanPath = mConn->objectPath() + QLatin1String("/ConferenceChannel"); chanPath = mConferenceChanPath.toAscii(); mConferenceChanService = TP_TESTS_CONFERENCE_CHANNEL(g_object_new( TP_TESTS_TYPE_CONFERENCE_CHANNEL, "connection", mConn->service(), "object-path", chanPath.data(), "initial-channels", initialChannels, NULL)); tp_handle_unref(mContactRepo, handle1); tp_handle_unref(mContactRepo, handle2); tp_handle_unref(mContactRepo, handle3); g_ptr_array_foreach(initialChannels, (GFunc) g_free, NULL); g_ptr_array_free(initialChannels, TRUE); } void TestConferenceChan::init() { initImpl(); } void TestConferenceChan::testConference() { mChan = Channel::create(mConn->client(), mConferenceChanPath, QVariantMap()); QCOMPARE(mChan->isConference(), false); QVERIFY(mChan->conferenceInitialInviteeContacts().isEmpty()); QVERIFY(mChan->conferenceChannels().isEmpty()); QVERIFY(mChan->conferenceInitialChannels().isEmpty()); QVERIFY(mChan->conferenceOriginalChannels().isEmpty()); QCOMPARE(mChan->supportsConferenceMerging(), false); QCOMPARE(mChan->supportsConferenceSplitting(), false); QVERIFY(connect(mChan->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan->isReady(), true); QStringList expectedObjectPaths; expectedObjectPaths << mTextChan1Path << mTextChan2Path; QStringList objectPaths; Q_FOREACH (const ChannelPtr &channel, mChan->conferenceInitialChannels()) { objectPaths << channel->objectPath(); } QCOMPARE(expectedObjectPaths, objectPaths); objectPaths.clear(); Q_FOREACH (const ChannelPtr &channel, mChan->conferenceChannels()) { objectPaths << channel->objectPath(); } QCOMPARE(expectedObjectPaths, objectPaths); QCOMPARE(!mChan->isReady(Channel::FeatureConferenceInitialInviteeContacts), true); QCOMPARE(mChan->conferenceInitialInviteeContacts(), Contacts()); QVERIFY(connect(mChan->becomeReady(Channel::FeatureConferenceInitialInviteeContacts), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan->isReady(Channel::FeatureConferenceInitialInviteeContacts), true); QCOMPARE(mChan->conferenceInitialInviteeContacts(), Contacts()); QCOMPARE(mChan->supportsConferenceMerging(), true); QCOMPARE(mChan->supportsConferenceSplitting(), false); ChannelPtr otherChannel = Channel::create(mConn->client(), mTextChan3Path, QVariantMap()); QVERIFY(connect(mChan.data(), SIGNAL(conferenceChannelMerged(const Tp::ChannelPtr &)), SLOT(onConferenceChannelMerged(const Tp::ChannelPtr &)))); QVERIFY(connect(mChan->conferenceMergeChannel(otherChannel), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan->isReady(), true); while (!mChannelMerged) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mChannelMerged->objectPath(), otherChannel->objectPath()); expectedObjectPaths << mTextChan3Path; objectPaths.clear(); Q_FOREACH (const ChannelPtr &channel, mChan->conferenceChannels()) { objectPaths << channel->objectPath(); } QCOMPARE(expectedObjectPaths, objectPaths); QVERIFY(connect(mChan.data(), SIGNAL(conferenceChannelRemoved(const Tp::ChannelPtr &, const Tp::Channel::GroupMemberChangeDetails &)), SLOT(onConferenceChannelRemoved(const Tp::ChannelPtr &, const Tp::Channel::GroupMemberChangeDetails &)))); tp_tests_conference_channel_remove_channel (mConferenceChanService, mChannelMerged->objectPath().toAscii().data()); while (!mChannelRemovedDetailed) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mChannelRemovedDetailed, mChannelMerged); QCOMPARE(mChannelRemovedDetailedDetails.allDetails().isEmpty(), false); QCOMPARE(qdbus_cast<int>(mChannelRemovedDetailedDetails.allDetails().value( QLatin1String("domain-specific-detail-uint"))), 3); QCOMPARE(mChannelRemovedDetailedDetails.hasActor(), true); QCOMPARE(mChannelRemovedDetailedDetails.actor(), mChan->groupSelfContact()); expectedObjectPaths.clear(); expectedObjectPaths << mTextChan1Path << mTextChan2Path; objectPaths.clear(); Q_FOREACH (const ChannelPtr &channel, mChan->conferenceChannels()) { objectPaths << channel->objectPath(); } QCOMPARE(expectedObjectPaths, objectPaths); mChan.reset(); mChannelMerged.reset(); } void TestConferenceChan::cleanup() { cleanupImpl(); } void TestConferenceChan::cleanupTestCase() { QCOMPARE(mConn->disconnect(), true); delete mConn; if (mTextChan1Service != 0) { g_object_unref(mTextChan1Service); mTextChan1Service = 0; } if (mTextChan2Service != 0) { g_object_unref(mTextChan2Service); mTextChan2Service = 0; } if (mConferenceChanService != 0) { g_object_unref(mConferenceChanService); mConferenceChanService = 0; } cleanupTestCaseImpl(); } QTEST_MAIN(TestConferenceChan) #include "_gen/chan-conference.cpp.moc.hpp" <commit_msg>chan-conference: Test that Channel::conferenceSplitChannel() fails if splitting is not supported.<commit_after>#include <tests/lib/test.h> #include <tests/lib/glib-helpers/test-conn-helper.h> #include <tests/lib/glib/echo/chan.h> #include <tests/lib/glib/echo/conn.h> #include <tests/lib/glib/future/conference/chan.h> #include <TelepathyQt4/Connection> #include <TelepathyQt4/PendingReady> #include <telepathy-glib/debug.h> using namespace Tp; class TestConferenceChan : public Test { Q_OBJECT public: TestConferenceChan(QObject *parent = 0) : Test(parent), mConn(0), mContactRepo(0), mTextChan1Service(0), mTextChan2Service(0), mConferenceChanService(0) { } protected Q_SLOTS: void onConferenceChannelMerged(const Tp::ChannelPtr &); void onConferenceChannelRemoved(const Tp::ChannelPtr &channel, const Tp::Channel::GroupMemberChangeDetails &details); private Q_SLOTS: void initTestCase(); void init(); void testConference(); void cleanup(); void cleanupTestCase(); private: TestConnHelper *mConn; TpHandleRepoIface *mContactRepo; ChannelPtr mChan; QString mTextChan1Path; ExampleEchoChannel *mTextChan1Service; QString mTextChan2Path; ExampleEchoChannel *mTextChan2Service; QString mTextChan3Path; ExampleEchoChannel *mTextChan3Service; QString mConferenceChanPath; TpTestsConferenceChannel *mConferenceChanService; ChannelPtr mChannelMerged; ChannelPtr mChannelRemovedDetailed; Channel::GroupMemberChangeDetails mChannelRemovedDetailedDetails; }; void TestConferenceChan::onConferenceChannelMerged(const Tp::ChannelPtr &channel) { mChannelMerged = channel; mLoop->exit(0); } void TestConferenceChan::onConferenceChannelRemoved(const Tp::ChannelPtr &channel, const Tp::Channel::GroupMemberChangeDetails &details) { mChannelRemovedDetailed = channel; mChannelRemovedDetailedDetails = details; mLoop->exit(0); } void TestConferenceChan::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("chan-conference"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); mConn = new TestConnHelper(this, EXAMPLE_TYPE_ECHO_CONNECTION, "account", "[email protected]", "protocol", "example", NULL); QCOMPARE(mConn->connect(), true); // create a Channel by magic, rather than doing D-Bus round-trips for it mContactRepo = tp_base_connection_get_handles(TP_BASE_CONNECTION(mConn->service()), TP_HANDLE_TYPE_CONTACT); guint handle1 = tp_handle_ensure(mContactRepo, "someone1@localhost", 0, 0); guint handle2 = tp_handle_ensure(mContactRepo, "someone2@localhost", 0, 0); guint handle3 = tp_handle_ensure(mContactRepo, "someone3@localhost", 0, 0); QByteArray chanPath; GPtrArray *initialChannels = g_ptr_array_new(); mTextChan1Path = mConn->objectPath() + QLatin1String("/TextChannel/1"); chanPath = mTextChan1Path.toAscii(); mTextChan1Service = EXAMPLE_ECHO_CHANNEL(g_object_new( EXAMPLE_TYPE_ECHO_CHANNEL, "connection", mConn->service(), "object-path", chanPath.data(), "handle", handle1, NULL)); g_ptr_array_add(initialChannels, g_strdup(chanPath.data())); mTextChan2Path = mConn->objectPath() + QLatin1String("/TextChannel/2"); chanPath = mTextChan2Path.toAscii(); mTextChan2Service = EXAMPLE_ECHO_CHANNEL(g_object_new( EXAMPLE_TYPE_ECHO_CHANNEL, "connection", mConn->service(), "object-path", chanPath.data(), "handle", handle2, NULL)); g_ptr_array_add(initialChannels, g_strdup(chanPath.data())); // let's not add this one to initial channels mTextChan3Path = mConn->objectPath() + QLatin1String("/TextChannel/3"); chanPath = mTextChan3Path.toAscii(); mTextChan3Service = EXAMPLE_ECHO_CHANNEL(g_object_new( EXAMPLE_TYPE_ECHO_CHANNEL, "connection", mConn->service(), "object-path", chanPath.data(), "handle", handle3, NULL)); mConferenceChanPath = mConn->objectPath() + QLatin1String("/ConferenceChannel"); chanPath = mConferenceChanPath.toAscii(); mConferenceChanService = TP_TESTS_CONFERENCE_CHANNEL(g_object_new( TP_TESTS_TYPE_CONFERENCE_CHANNEL, "connection", mConn->service(), "object-path", chanPath.data(), "initial-channels", initialChannels, NULL)); tp_handle_unref(mContactRepo, handle1); tp_handle_unref(mContactRepo, handle2); tp_handle_unref(mContactRepo, handle3); g_ptr_array_foreach(initialChannels, (GFunc) g_free, NULL); g_ptr_array_free(initialChannels, TRUE); } void TestConferenceChan::init() { initImpl(); } void TestConferenceChan::testConference() { mChan = Channel::create(mConn->client(), mConferenceChanPath, QVariantMap()); QCOMPARE(mChan->isConference(), false); QVERIFY(mChan->conferenceInitialInviteeContacts().isEmpty()); QVERIFY(mChan->conferenceChannels().isEmpty()); QVERIFY(mChan->conferenceInitialChannels().isEmpty()); QVERIFY(mChan->conferenceOriginalChannels().isEmpty()); QCOMPARE(mChan->supportsConferenceMerging(), false); QCOMPARE(mChan->supportsConferenceSplitting(), false); QVERIFY(connect(mChan->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan->isReady(), true); QStringList expectedObjectPaths; expectedObjectPaths << mTextChan1Path << mTextChan2Path; QStringList objectPaths; Q_FOREACH (const ChannelPtr &channel, mChan->conferenceInitialChannels()) { objectPaths << channel->objectPath(); } QCOMPARE(expectedObjectPaths, objectPaths); objectPaths.clear(); Q_FOREACH (const ChannelPtr &channel, mChan->conferenceChannels()) { objectPaths << channel->objectPath(); } QCOMPARE(expectedObjectPaths, objectPaths); QCOMPARE(!mChan->isReady(Channel::FeatureConferenceInitialInviteeContacts), true); QCOMPARE(mChan->conferenceInitialInviteeContacts(), Contacts()); QVERIFY(connect(mChan->becomeReady(Channel::FeatureConferenceInitialInviteeContacts), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan->isReady(Channel::FeatureConferenceInitialInviteeContacts), true); QCOMPARE(mChan->conferenceInitialInviteeContacts(), Contacts()); QCOMPARE(mChan->supportsConferenceMerging(), true); QCOMPARE(mChan->supportsConferenceSplitting(), false); QVERIFY(connect(mChan->conferenceSplitChannel(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 1); ChannelPtr otherChannel = Channel::create(mConn->client(), mTextChan3Path, QVariantMap()); QVERIFY(connect(mChan.data(), SIGNAL(conferenceChannelMerged(const Tp::ChannelPtr &)), SLOT(onConferenceChannelMerged(const Tp::ChannelPtr &)))); QVERIFY(connect(mChan->conferenceMergeChannel(otherChannel), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan->isReady(), true); while (!mChannelMerged) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mChannelMerged->objectPath(), otherChannel->objectPath()); expectedObjectPaths << mTextChan3Path; objectPaths.clear(); Q_FOREACH (const ChannelPtr &channel, mChan->conferenceChannels()) { objectPaths << channel->objectPath(); } QCOMPARE(expectedObjectPaths, objectPaths); QVERIFY(connect(mChan.data(), SIGNAL(conferenceChannelRemoved(const Tp::ChannelPtr &, const Tp::Channel::GroupMemberChangeDetails &)), SLOT(onConferenceChannelRemoved(const Tp::ChannelPtr &, const Tp::Channel::GroupMemberChangeDetails &)))); tp_tests_conference_channel_remove_channel (mConferenceChanService, mChannelMerged->objectPath().toAscii().data()); while (!mChannelRemovedDetailed) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mChannelRemovedDetailed, mChannelMerged); QCOMPARE(mChannelRemovedDetailedDetails.allDetails().isEmpty(), false); QCOMPARE(qdbus_cast<int>(mChannelRemovedDetailedDetails.allDetails().value( QLatin1String("domain-specific-detail-uint"))), 3); QCOMPARE(mChannelRemovedDetailedDetails.hasActor(), true); QCOMPARE(mChannelRemovedDetailedDetails.actor(), mChan->groupSelfContact()); expectedObjectPaths.clear(); expectedObjectPaths << mTextChan1Path << mTextChan2Path; objectPaths.clear(); Q_FOREACH (const ChannelPtr &channel, mChan->conferenceChannels()) { objectPaths << channel->objectPath(); } QCOMPARE(expectedObjectPaths, objectPaths); mChan.reset(); mChannelMerged.reset(); } void TestConferenceChan::cleanup() { cleanupImpl(); } void TestConferenceChan::cleanupTestCase() { QCOMPARE(mConn->disconnect(), true); delete mConn; if (mTextChan1Service != 0) { g_object_unref(mTextChan1Service); mTextChan1Service = 0; } if (mTextChan2Service != 0) { g_object_unref(mTextChan2Service); mTextChan2Service = 0; } if (mConferenceChanService != 0) { g_object_unref(mConferenceChanService); mConferenceChanService = 0; } cleanupTestCaseImpl(); } QTEST_MAIN(TestConferenceChan) #include "_gen/chan-conference.cpp.moc.hpp" <|endoftext|>
<commit_before>#include "ExportBodymovin.h" #include "check_params.h" #include "utility.h" #include <ee/SpriteLoader.h> #include <ee/SymbolLoader.h> #include <ee/SymbolFile.h> #include <ee/SymbolFactory.h> #include <ee/SpriteFactory.h> #include <ee/FileHelper.h> #include <ee/SpriteIO.h> #include <easyanim.h> #include <easycomplex.h> #include <easytext.h> #include <sprite2/TextboxSymbol.h> #include <sprite2/ComplexSymbol.h> #include <sprite2/SprSRT.h> #include <gum/FilepathHelper.h> #include <gum/BodymovinAnimLoader.h> #include <gum/BodymovinParser.h> #include <gum/StringHelper.h> #include <fstream> namespace edb { std::string ExportBodymovin::Command() const { return "export-bodymovin"; } std::string ExportBodymovin::Description() const { return "export-bodymovin"; } std::string ExportBodymovin::Usage() const { std::string usage = Command() + " [src file] [dst dir]"; return usage; } int ExportBodymovin::Run(int argc, char *argv[]) { if (!check_number(this, argc, 4)) return -1; if (!check_folder(argv[3])) return -1; int ret = init_gl(); if (ret < 0) { return ret; } Trigger(argv[2], argv[3]); return 0; } void ExportBodymovin::Trigger(const std::string& src_file, const std::string& dst_dir) { Json::Value val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(src_file.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, val); fin.close(); std::string dir = gum::FilepathHelper::Dir(src_file); gum::BodymovinParser parser; parser.Parse(val, dir); ee::SymbolLoader sym_loader; ee::SpriteLoader spr_loader; std::map<std::string, s2::Sprite*> map_assets; const std::vector<gum::BodymovinParser::Asset>& assets = parser.GetAssets(); std::vector<bool> flags(assets.size(), false); while (true) { bool fail = false; for (int i = 0, n = assets.size(); i < n; ++i) { if (flags[i]) { continue; } const gum::BodymovinParser::Asset& a = assets[i]; if (a.layers.empty()) { std::string filepath = gum::FilepathHelper::Absolute(".", a.filepath); s2::Sprite* spr = spr_loader.Create(filepath); map_assets.insert(std::make_pair(a.id, spr)); flags[i] = true; } else { bool skip = false; for (int j = 0, m = a.layers.size(); j < m; ++j) { const gum::BodymovinParser::Layer& layer = a.layers[j]; if (layer.layer_type == gum::BodymovinParser::LAYER_SOLID || layer.layer_type == gum::BodymovinParser::LAYER_NULL) { continue; } const std::string& id = a.layers[j].ref_id; std::map<std::string, s2::Sprite*>::iterator itr = map_assets.find(id); if (itr == map_assets.end()) { skip = true; break; } } flags[i] = !skip; if (skip) { fail = true; continue; } libanim::Symbol* sym = new libanim::Symbol(); gum::BodymovinAnimLoader loader(sym, &sym_loader, &spr_loader); loader.LoadLayers(map_assets, a.layers, parser.GetFrameRate(), parser.GetWidth(), parser.GetHeight()); std::string filepath = dst_dir + "\\" + a.id + "_" + ee::SymbolFile::Instance()->Tag(s2::SYM_ANIMATION) + ".json"; libanim::FileSaver::Store(filepath, *sym); sym->SetFilepath(filepath); libanim::Sprite* spr = new libanim::Sprite(sym); spr->UpdateBounding(); map_assets.insert(std::make_pair(a.id, spr)); sym->RemoveReference(); } } if (!fail) { break; } } libanim::Symbol* sym = new libanim::Symbol(); gum::BodymovinAnimLoader loader(sym, &sym_loader, &spr_loader); loader.LoadLayers(map_assets, parser.GetLayers(), parser.GetFrameRate(), parser.GetWidth(), parser.GetHeight()); std::string filepath = dst_dir + "\\data_" + ee::SymbolFile::Instance()->Tag(s2::SYM_ANIMATION) + ".json"; libanim::FileSaver::Store(filepath, *sym); std::map<std::string, s2::Sprite*>::iterator itr = map_assets.begin(); for ( ; itr != map_assets.end(); ++itr) { itr->second->RemoveReference(); } FixFontLayers(dst_dir); } void ExportBodymovin::FixFontLayers(const std::string& dir) { wxArrayString files; ee::FileHelper::FetchAllFiles(dir, files); for (int i = 0, n = files.size(); i < n; ++i) { wxFileName filename(files[i]); filename.Normalize(); std::string filepath = filename.GetFullPath(); if (ee::SymbolFile::Instance()->Type(filepath) == s2::SYM_ANIMATION) { FixFontLayer(filepath, dir); } } } void ExportBodymovin::FixFontLayer(const std::string& filepath, const std::string& dir) { Json::Value val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(filepath.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, val); fin.close(); Json::Value dst_val; dst_val["fps"] = val["fps"]; dst_val["name"] = val["name"]; int IDX0 = 0; std::string layer_name = gum::FilepathHelper::Filename(filepath); layer_name = layer_name.substr(0, layer_name.size() - 10); bool dirty = false; for (int i = 0, n = val["layer"].size(); i < n; ++i) { const Json::Value& layer_val = val["layer"][i]; assert(layer_val.size() > 0 && layer_val["frame"].size() > 0); const Json::Value& frame_val = layer_val["frame"][IDX0]; assert(frame_val.size() > 0 && frame_val["actor"].size() > 0); const Json::Value& actor_val = frame_val["actor"][IDX0]; std::string filename = actor_val["filepath"].asString(); filename = gum::FilepathHelper::Filename(filename); int sz = dst_val["layer"].size(); dst_val["layer"][sz] = val["layer"][i]; if (filename.size() != 6 || filename[0] != '0' || filename.substr(2) != ".png") { continue; } ee::Symbol* t_sym = ee::SymbolFactory::Create(s2::SYM_TEXTBOX); s2::Textbox tb; tb.width = 200; tb.height = 200; tb.font_size = 40; tb.font_color = s2::Color(0, 0, 0); tb.has_edge = false; tb.align_hori = s2::Textbox::HA_LEFT; tb.align_vert = s2::Textbox::VA_TOP; dynamic_cast<etext::Symbol*>(t_sym)->SetTextbox(tb); s2::Sprite* t_spr = ee::SpriteFactory::Instance()->Create(t_sym); t_spr->UpdateBounding(); ee::Symbol* c_sym = ee::SymbolFactory::Create(s2::SYM_COMPLEX); dynamic_cast<ecomplex::Symbol*>(c_sym)->Add(t_spr); std::string text_path = layer_name + "_" + gum::StringHelper::ToString(i) + "_text_complex.json"; c_sym->SetFilepath(dir + "\\" + text_path); s2::Sprite* c_spr = ee::SpriteFactory::Instance()->Create(c_sym); c_spr->UpdateBounding(); ecomplex::FileStorer::Store(c_sym->GetFilepath(), dynamic_cast<ecomplex::Symbol*>(c_sym), dir); Json::Value new_layer = layer_val; for (int j = 0, m = new_layer["frame"].size(); j < m; ++j) { Json::Value& frame_val = new_layer["frame"][j]; assert(frame_val["actor"].size() == 1); const Json::Value& src_val = frame_val["actor"][IDX0]; ee::SpriteIO spr_io; spr_io.Load(src_val, dir); sm::vec2 anchor = spr_io.m_position + spr_io.m_offset; spr_io.m_position = spr_io.m_position + sm::rotate_vector(-spr_io.m_offset, spr_io.m_angle) + spr_io.m_offset; spr_io.m_angle = 0; float scale = std::min(fabs(spr_io.m_scale.x), fabs(spr_io.m_scale.y)); spr_io.m_scale.x = scale; spr_io.m_scale.y = scale; spr_io.m_offset = anchor - spr_io.m_position; Json::Value dst_val; dst_val["filepath"] = text_path; spr_io.Store(dst_val, dir); frame_val["actor"][IDX0] = dst_val; } dst_val["layer"][sz + 1] = new_layer; dirty = true; } if (dirty) { Json::StyledStreamWriter writer; std::locale::global(std::locale("")); std::ofstream fout(filepath.c_str()); std::locale::global(std::locale("C")); writer.write(fout, dst_val); fout.close(); } } }<commit_msg>[FIXED] export ae<commit_after>#include "ExportBodymovin.h" #include "check_params.h" #include "utility.h" #include <ee/SpriteLoader.h> #include <ee/SymbolLoader.h> #include <ee/SymbolFile.h> #include <ee/SymbolFactory.h> #include <ee/SpriteFactory.h> #include <ee/FileHelper.h> #include <ee/SpriteIO.h> #include <easyanim.h> #include <easycomplex.h> #include <easytext.h> #include <sprite2/TextboxSymbol.h> #include <sprite2/ComplexSymbol.h> #include <sprite2/SprSRT.h> #include <gum/FilepathHelper.h> #include <gum/BodymovinAnimLoader.h> #include <gum/BodymovinParser.h> #include <gum/StringHelper.h> #include <fstream> namespace edb { std::string ExportBodymovin::Command() const { return "export-bodymovin"; } std::string ExportBodymovin::Description() const { return "export-bodymovin"; } std::string ExportBodymovin::Usage() const { std::string usage = Command() + " [src file] [dst dir]"; return usage; } int ExportBodymovin::Run(int argc, char *argv[]) { if (!check_number(this, argc, 4)) return -1; if (!check_folder(argv[3])) return -1; int ret = init_gl(); if (ret < 0) { return ret; } Trigger(argv[2], argv[3]); return 0; } void ExportBodymovin::Trigger(const std::string& src_file, const std::string& dst_dir) { Json::Value val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(src_file.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, val); fin.close(); std::string dir = gum::FilepathHelper::Dir(src_file); gum::BodymovinParser parser; parser.Parse(val, dir); ee::SymbolLoader sym_loader; ee::SpriteLoader spr_loader; std::map<std::string, s2::Sprite*> map_assets; const std::vector<gum::BodymovinParser::Asset>& assets = parser.GetAssets(); std::vector<bool> flags(assets.size(), false); while (true) { bool fail = false; for (int i = 0, n = assets.size(); i < n; ++i) { if (flags[i]) { continue; } const gum::BodymovinParser::Asset& a = assets[i]; if (a.layers.empty()) { std::string filepath = gum::FilepathHelper::Absolute(".", a.filepath); s2::Sprite* spr = spr_loader.Create(filepath); map_assets.insert(std::make_pair(a.id, spr)); flags[i] = true; } else { bool skip = false; for (int j = 0, m = a.layers.size(); j < m; ++j) { const gum::BodymovinParser::Layer& layer = a.layers[j]; if (layer.layer_type == gum::BodymovinParser::LAYER_SOLID || layer.layer_type == gum::BodymovinParser::LAYER_NULL) { continue; } const std::string& id = a.layers[j].ref_id; std::map<std::string, s2::Sprite*>::iterator itr = map_assets.find(id); if (itr == map_assets.end()) { skip = true; break; } } flags[i] = !skip; if (skip) { fail = true; continue; } libanim::Symbol* sym = new libanim::Symbol(); gum::BodymovinAnimLoader loader(sym, &sym_loader, &spr_loader); loader.LoadLayers(map_assets, a.layers, parser.GetFrameRate(), parser.GetWidth(), parser.GetHeight(), parser.GetStartFrame(), parser.GetEndFrame()); std::string filepath = dst_dir + "\\" + a.id + "_" + ee::SymbolFile::Instance()->Tag(s2::SYM_ANIMATION) + ".json"; libanim::FileSaver::Store(filepath, *sym); sym->SetFilepath(filepath); libanim::Sprite* spr = new libanim::Sprite(sym); spr->UpdateBounding(); map_assets.insert(std::make_pair(a.id, spr)); sym->RemoveReference(); } } if (!fail) { break; } } libanim::Symbol* sym = new libanim::Symbol(); gum::BodymovinAnimLoader loader(sym, &sym_loader, &spr_loader); loader.LoadLayers(map_assets, parser.GetLayers(), parser.GetFrameRate(), parser.GetWidth(), parser.GetHeight(), parser.GetStartFrame(), parser.GetEndFrame()); std::string filepath = dst_dir + "\\data_" + ee::SymbolFile::Instance()->Tag(s2::SYM_ANIMATION) + ".json"; libanim::FileSaver::Store(filepath, *sym); std::map<std::string, s2::Sprite*>::iterator itr = map_assets.begin(); for ( ; itr != map_assets.end(); ++itr) { itr->second->RemoveReference(); } FixFontLayers(dst_dir); } void ExportBodymovin::FixFontLayers(const std::string& dir) { wxArrayString files; ee::FileHelper::FetchAllFiles(dir, files); for (int i = 0, n = files.size(); i < n; ++i) { wxFileName filename(files[i]); filename.Normalize(); std::string filepath = filename.GetFullPath(); if (ee::SymbolFile::Instance()->Type(filepath) == s2::SYM_ANIMATION) { FixFontLayer(filepath, dir); } } } void ExportBodymovin::FixFontLayer(const std::string& filepath, const std::string& dir) { Json::Value val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(filepath.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, val); fin.close(); Json::Value dst_val; dst_val["fps"] = val["fps"]; dst_val["name"] = val["name"]; int IDX0 = 0; std::string layer_name = gum::FilepathHelper::Filename(filepath); layer_name = layer_name.substr(0, layer_name.size() - 10); bool dirty = false; for (int i = 0, n = val["layer"].size(); i < n; ++i) { const Json::Value& layer_val = val["layer"][i]; assert(layer_val.size() > 0 && layer_val["frame"].size() > 0); const Json::Value& frame_val = layer_val["frame"][IDX0]; assert(frame_val.size() > 0 && frame_val["actor"].size() > 0); const Json::Value& actor_val = frame_val["actor"][IDX0]; std::string filename = actor_val["filepath"].asString(); filename = gum::FilepathHelper::Filename(filename); int sz = dst_val["layer"].size(); dst_val["layer"][sz] = val["layer"][i]; if (filename.size() != 6 || filename[0] != '0' || filename.substr(2) != ".png") { continue; } ee::Symbol* t_sym = ee::SymbolFactory::Create(s2::SYM_TEXTBOX); s2::Textbox tb; tb.width = 200; tb.height = 200; tb.font_size = 40; tb.font_color = s2::Color(0, 0, 0); tb.has_edge = false; tb.align_hori = s2::Textbox::HA_LEFT; tb.align_vert = s2::Textbox::VA_TOP; dynamic_cast<etext::Symbol*>(t_sym)->SetTextbox(tb); s2::Sprite* t_spr = ee::SpriteFactory::Instance()->Create(t_sym); t_spr->UpdateBounding(); ee::Symbol* c_sym = ee::SymbolFactory::Create(s2::SYM_COMPLEX); dynamic_cast<ecomplex::Symbol*>(c_sym)->Add(t_spr); std::string text_path = layer_name + "_" + gum::StringHelper::ToString(i) + "_text_complex.json"; c_sym->SetFilepath(dir + "\\" + text_path); s2::Sprite* c_spr = ee::SpriteFactory::Instance()->Create(c_sym); c_spr->UpdateBounding(); ecomplex::FileStorer::Store(c_sym->GetFilepath(), dynamic_cast<ecomplex::Symbol*>(c_sym), dir); Json::Value new_layer = layer_val; for (int j = 0, m = new_layer["frame"].size(); j < m; ++j) { Json::Value& frame_val = new_layer["frame"][j]; assert(frame_val["actor"].size() == 1); const Json::Value& src_val = frame_val["actor"][IDX0]; ee::SpriteIO spr_io; spr_io.Load(src_val, dir); sm::vec2 anchor = spr_io.m_position + spr_io.m_offset; spr_io.m_position = spr_io.m_position + sm::rotate_vector(-spr_io.m_offset, spr_io.m_angle) + spr_io.m_offset; spr_io.m_angle = 0; float scale = std::min(fabs(spr_io.m_scale.x), fabs(spr_io.m_scale.y)); spr_io.m_scale.x = scale; spr_io.m_scale.y = scale; spr_io.m_offset = anchor - spr_io.m_position; Json::Value dst_val; dst_val["filepath"] = text_path; spr_io.Store(dst_val, dir); frame_val["actor"][IDX0] = dst_val; } dst_val["layer"][sz + 1] = new_layer; dirty = true; } if (dirty) { Json::StyledStreamWriter writer; std::locale::global(std::locale("")); std::ofstream fout(filepath.c_str()); std::locale::global(std::locale("C")); writer.write(fout, dst_val); fout.close(); } } }<|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Mike Taylor, Radu Serban // ============================================================================= // // Test for revolute joint // // Recall that Irrlicht uses a left-hand frame, so everything is rendered with // left and right flipped. // // ============================================================================= // TO DO: // Create Case 2 where the revolute joint is at say (1,2,3) and axis of // rotation is along the vector (0,1,1) - Is this case a seperate file? // ChQuaternion<> revAxisRot(Q_from_AngX(-CH_C_PI_4)); // Create Unit Test versions of both cases with no animations // "You can advance the simulation directly, by calling // ChSystem::DoStepDynamics()" // Report test run time & test pass/fail (determine what the criteria is) // Determine interface for unit test results // ============================================================================= #include <ostream> #include <fstream> #include "physics/ChSystem.h" #include "physics/ChBody.h" #include "unit_IRRLICHT/ChIrrApp.h" #include "ChronoT_config.h" using namespace chrono; using namespace irr; // ============================================================================= // Settings // ============================================================================= // There are no units in Chrono, so values must be consistant (MKS is used in this example) ChVector<> loc(0, 0, 0); // location of revolute joint (in global frame) // Rotation of the Revolute free DOF(rotation about joint z axis only) // Aligns the revolute z axis with the global y axis in this case ChQuaternion<> revAxisRot(Q_from_AngX(-CH_C_PI_2)); double mass = 1.0; // mass of pendulum double length = 4.0; // length of pendulum ChVector<> inertiaXX(1, 1, 1); // mass moments of inertia of pendulum double g = 9.80665; double timeRecord = 5; double timeStep = 0.001; // ============================================================================= int main(int argc, char* argv[]) { SetChronoDataPath(CHRONO_DATA_DIR); // Create the mechanical system // ---------------------------- // 1- Create a ChronoENGINE physical system: all bodies and constraints // will be handled by this ChSystem object. ChSystem my_system; my_system.Set_G_acc(ChVector<>(0.0, 0.0, -g)); my_system.SetIntegrationType(ChSystem::INT_ANITESCU); my_system.SetIterLCPmaxItersSpeed(100); my_system.SetIterLCPmaxItersStab(100); //Tasora stepper uses this, Anitescu does not my_system.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR); // 2- Create the rigid bodies of the system // ..the ground ChSharedBodyPtr ground(new ChBody); my_system.AddBody(ground); ground->SetBodyFixed(true); // Add some geometry to the ground body for visualizing the revolute joint ChSharedPtr<ChCylinderShape> cyl_g(new ChCylinderShape); cyl_g->GetCylinderGeometry().p1 = loc + revAxisRot.Rotate(ChVector<>(0, 0, -0.2)); cyl_g->GetCylinderGeometry().p2 = loc + revAxisRot.Rotate(ChVector<>(0, 0, 0.2)); cyl_g->GetCylinderGeometry().rad = 0.1; ground->AddAsset(cyl_g); // ..the pendulum (Assumes the pendulum's CG is at half its length) ChSharedBodyPtr pendulum(new ChBody); my_system.AddBody(pendulum); pendulum->SetPos(loc + ChVector<>(length / 2, 0, 0)); // position of COG of pendulum in the Global Reference Frame pendulum->SetMass(mass); pendulum->SetInertiaXX(inertiaXX); // Set the body's inertia about the CG in the Global Reference Frame // Add some geometry to the pendulum for visualization ChSharedPtr<ChCylinderShape> cyl_p(new ChCylinderShape); cyl_p->GetCylinderGeometry().p1 = ChVector<>(-length / 2, 0, 0); cyl_p->GetCylinderGeometry().p2 = ChVector<>(length / 2, 0, 0); cyl_p->GetCylinderGeometry().rad = 0.1; pendulum->AddAsset(cyl_p); // 3- Create constraints: the mechanical joints between the rigid bodies. // .. a revolute joint between pendulum and ground at "loc" in the global reference frame with the applied rotation ChSharedPtr<ChLinkLockRevolute> revoluteJoint(new ChLinkLockRevolute); revoluteJoint->Initialize(pendulum, ground, ChCoordsys<>(loc, revAxisRot)); my_system.AddLink(revoluteJoint); // Create the Irrlicht application for visualization // ------------------------------------------------- ChIrrApp application(&my_system, L"ChLinkRevolute demo", core::dimension2d<u32>(800, 600), false, true); application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); core::vector3df lookat((f32)loc.x, (f32)loc.y, (f32)loc.z); application.AddTypicalCamera(lookat + core::vector3df(0, 3, -6), lookat); application.AssetBindAll(); application.AssetUpdateAll(); // Simulation loop // --------------- // Create output file for results & add in column headers (tab deliminated) std::ofstream outf("RevoluteJointData.txt"); if (outf) { outf << "timeElapsed(s)\t"; outf << "X_Pos(m)\tY_Pos(m)\tZ_Pos\tLength_Pos(m)\t"; outf << "X_Vel(m/s)\tY_Vel(m/s)\tZ_Vel(m/s)\tLength_Vel(m/s)\t"; outf << "X_Accel(m/s^2)\tY_Accel(m/s^2)\tZ_Accell(m/s^2)\tLength_Accel(m/s^2)\t"; outf << "e0_quaternion\te1_quaternion\te2_quaternion\te3_quaternion\t"; outf << "X_AngVel(rad/s)\tY_AngVel(rad/s)\tZ_AngVel(rad/s)\tLength_AngVel(rad/s)\t"; outf << "X_AngAccel(rad/s^2)\tY_AngAccel(rad/s^2)\tZ_AngAccell(rad/s^2)\tLength_AngAccel(rad/s^2)\t"; outf << "X_Glb_ReactionFrc(N)\tY_Glb_ReactionFrc(N)\tZ_Glb_ReactionFrc(N)\tLength_Glb_ReactionFrc(N)\t"; outf << "X_Glb_ReactionTrq(Nm)\tY_Glb_ReactionTrq(Nm)\tZ_Glb_ReactionTrq(Nm)\tLength_Glb_ReactionTrq(Nm)\t"; outf << "Total_Kinetic_Energy(J)\tTranslational_Kinetic_Energy(J)\tAngular_Kinetic_Energy(J)\tDelta_Potential_Energy(J)\t"; outf << std::endl; } else { std::cout << "Output file is invalid" << std::endl; } application.SetTimestep(timeStep); double timeElapsed = 0; while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); // Draw an XZ grid at the global origin to add in visualization ChIrrTools::drawGrid( application.GetVideoDriver(), 1, 1, 20, 20, ChCoordsys<>(ChVector<>(0, 0, 0), Q_from_AngX(CH_C_PI_2)), video::SColor(255, 80, 100, 100), true); // Write current translational and rotational position, velocity, acceleration, // reaction force, and reaction torque of pendulum to output file //Add a little error tolerance on the end time to ensure that the final data point is recorded if (outf && timeElapsed <= timeRecord+timeStep/2) { // Time elapsed outf << timeElapsed << "\t"; // Position of the Pendulum's CG in the Global Reference Frame ChVector<double> position = pendulum->GetPos(); outf << position.x << "\t" << position.y << "\t" << position.z << "\t" << (position - loc).Length() << "\t"; // Velocity of the Pendulum's CG in the Global Reference Frame ChVector<double> velocity = pendulum->GetPos_dt(); outf << velocity.x << "\t" << velocity.y << "\t" << velocity.z << "\t" << velocity.Length() << "\t"; // Acceleration of the Pendulum's CG in the Global Reference Frame ChVector<double> acceleration = pendulum->GetPos_dtdt(); outf << acceleration.x << "\t" << acceleration.y << "\t" << acceleration.z << "\t" << acceleration.Length() << "\t"; // Angular Position quaternion of the Pendulum with respect to the Global Reference Frame ChQuaternion<double> rot = pendulum->GetRot(); outf << rot.e0 << "\t" << rot.e1 << "\t" << rot.e2 << "\t" << rot.e3 << "\t"; // Angular Velocity of the Pendulum with respect to the Global Reference Frame ChVector<double> angVel = pendulum->GetWvel_par(); outf << angVel.x << "\t" << angVel.y << "\t" << angVel.z << "\t" << angVel.Length() << "\t"; // Angular Acceleration of the Pendulum with respect to the Global Reference Frame ChVector<double> angAccel = pendulum->GetWacc_par(); outf << angAccel.x << "\t" << angAccel.y << "\t" << angAccel.z << "\t" << angAccel.Length() << "\t"; // Reaction Force and Torque // These are expressed in the link coordinate system. We convert them to // the coordinate system of Body2 (in our case this is the ground). ChCoordsys<> linkCoordsys = revoluteJoint->GetLinkRelativeCoords(); ChVector<double> reactForce = revoluteJoint->Get_react_force(); ChVector<double> reactForceGlobal = linkCoordsys.TransformDirectionLocalToParent(reactForce); outf << reactForceGlobal.x << "\t" << reactForceGlobal.y << "\t" << reactForceGlobal.z << "\t" << reactForceGlobal.Length() << "\t"; ChVector<double> reactTorque = revoluteJoint->Get_react_torque(); ChVector<double> reactTorqueGlobal = linkCoordsys.TransformDirectionLocalToParent(reactTorque); outf << reactTorqueGlobal.x << "\t" << reactTorqueGlobal.y << "\t" << reactTorqueGlobal.z << "\t" << reactTorqueGlobal.Length() << "\t"; // Conservation of Energy //Translational Kinetic Energy (1/2*m*||v||^2) //Rotational Kinetic Energy (1/2 w'*I*w) ChMatrix33*vector is valid since [3x3]*[3x1] = [3x1] //Delta Potential Energy (m*g*dz) ChMatrix33<> inertia = pendulum->GetInertia(); //3x3 Inertia Tensor in the local coordinate frame ChVector<> angVelLoc = pendulum->GetWvel_loc(); double transKE = 0.5*mass*velocity.Length2(); double rotKE = 0.5*Vdot(angVelLoc, inertia * angVelLoc); double deltaPE = mass*g*(position.z-loc.z); double totalKE = transKE + rotKE; outf << totalKE << "\t" << transKE << "\t" << rotKE << "\t" << deltaPE << "\t" << std::endl;; } // Output a message to the command window once timeRecord has been reached // Add a little error tolerance to make sure this event is captured if ((timeElapsed >= timeRecord-timeStep/2) && (timeElapsed <= timeRecord+timeStep/2)) { std::cout << "All Simulation Results have been recorded. Continuing to solve and animate." << std::endl; } // Advance simulation by one step application.DoStep(); timeElapsed += timeStep; application.EndScene(); } // Close output file outf.close(); return 0; } <commit_msg>Updated test_Revolute for Parameter Studies and added file print interval<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Mike Taylor, Radu Serban // ============================================================================= // // Test for revolute joint // // Recall that Irrlicht uses a left-hand frame, so everything is rendered with // left and right flipped. // // ============================================================================= // TO DO: // Report test run time & test pass/fail (determine what the criteria is) // ============================================================================= #include <ostream> #include <fstream> #include "physics/ChSystem.h" #include "physics/ChBody.h" #include "unit_IRRLICHT/ChIrrApp.h" #include "ChronoT_config.h" using namespace chrono; using namespace irr; // ============================================================================= void TestRevolute(ChVector<> loc, ChQuaternion<> revAxisRot, double simTimeStep, std::string outputFilename, bool Animate) { //Settings //---------------------------------------------------------------------------- // There are no units in Chrono, so values must be consistant (MKS is used in this example) double mass = 1.0; // mass of pendulum double length = 4.0; // length of pendulum ChVector<> inertiaXX(1, 1, 1); // mass moments of inertia of pendulum double g = 9.80665; double timeRecord = 5; // Stop recording to the file after this much simulated time double printTimeStep = 0.001; // Write the output file at this simulation time step SetChronoDataPath(CHRONO_DATA_DIR); // Create the mechanical system // ---------------------------- // 1- Create a ChronoENGINE physical system: all bodies and constraints // will be handled by this ChSystem object. ChSystem my_system; my_system.Set_G_acc(ChVector<>(0.0, 0.0, -g)); my_system.SetIntegrationType(ChSystem::INT_ANITESCU); my_system.SetIterLCPmaxItersSpeed(100); my_system.SetIterLCPmaxItersStab(100); //Tasora stepper uses this, Anitescu does not my_system.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR); // 2- Create the rigid bodies of the system // ..the ground ChSharedBodyPtr ground(new ChBody); my_system.AddBody(ground); ground->SetBodyFixed(true); // Add some geometry to the ground body for visualizing the revolute joint ChSharedPtr<ChCylinderShape> cyl_g(new ChCylinderShape); cyl_g->GetCylinderGeometry().p1 = loc + revAxisRot.Rotate(ChVector<>(0, 0, -0.2)); cyl_g->GetCylinderGeometry().p2 = loc + revAxisRot.Rotate(ChVector<>(0, 0, 0.2)); cyl_g->GetCylinderGeometry().rad = 0.1; ground->AddAsset(cyl_g); // ..the pendulum (Assumes the pendulum's CG is at half its length) ChSharedBodyPtr pendulum(new ChBody); my_system.AddBody(pendulum); pendulum->SetPos(loc + ChVector<>(length / 2, 0, 0)); // position of COG of pendulum in the Global Reference Frame pendulum->SetMass(mass); pendulum->SetInertiaXX(inertiaXX); // Set the body's inertia about the CG in the Global Reference Frame // Add some geometry to the pendulum for visualization ChSharedPtr<ChCylinderShape> cyl_p(new ChCylinderShape); cyl_p->GetCylinderGeometry().p1 = ChVector<>(-length / 2, 0, 0); cyl_p->GetCylinderGeometry().p2 = ChVector<>(length / 2, 0, 0); cyl_p->GetCylinderGeometry().rad = 0.1; pendulum->AddAsset(cyl_p); // 3- Create constraints: the mechanical joints between the rigid bodies. // .. a revolute joint between pendulum and ground at "loc" in the global reference frame with the applied rotation ChSharedPtr<ChLinkLockRevolute> revoluteJoint(new ChLinkLockRevolute); revoluteJoint->Initialize(pendulum, ground, ChCoordsys<>(loc, revAxisRot)); my_system.AddLink(revoluteJoint); // Create the Irrlicht application for visualization // ------------------------------------------------- ChIrrApp * application; if(Animate){ application = new ChIrrApp(&my_system, L"ChLinkRevolute demo", core::dimension2d<u32>(800, 600), false, true); application->AddTypicalLogo(); application->AddTypicalSky(); application->AddTypicalLights(); core::vector3df lookat((f32)loc.x, (f32)loc.y, (f32)loc.z); application->AddTypicalCamera(lookat + core::vector3df(0, 3, -6), lookat); application->AssetBindAll(); //Now have the visulization tool (Irrlicht) create its geometry from the assets defined above application->AssetUpdateAll(); application->SetTimestep(simTimeStep); } // Create output file for results & add in column headers (tab deliminated) // ------------------------------------------------------------------------ std::ofstream outf(outputFilename); if (outf) { outf << "timeElapsed(s)\t"; outf << "X_Pos(m)\tY_Pos(m)\tZ_Pos\tLength_Pos(m)\t"; outf << "X_Vel(m/s)\tY_Vel(m/s)\tZ_Vel(m/s)\tLength_Vel(m/s)\t"; outf << "X_Accel(m/s^2)\tY_Accel(m/s^2)\tZ_Accell(m/s^2)\tLength_Accel(m/s^2)\t"; outf << "e0_quaternion\te1_quaternion\te2_quaternion\te3_quaternion\t"; outf << "X_AngVel(rad/s)\tY_AngVel(rad/s)\tZ_AngVel(rad/s)\tLength_AngVel(rad/s)\t"; outf << "X_AngAccel(rad/s^2)\tY_AngAccel(rad/s^2)\tZ_AngAccell(rad/s^2)\tLength_AngAccel(rad/s^2)\t"; outf << "X_Glb_ReactionFrc(N)\tY_Glb_ReactionFrc(N)\tZ_Glb_ReactionFrc(N)\tLength_Glb_ReactionFrc(N)\t"; outf << "X_Glb_ReactionTrq(Nm)\tY_Glb_ReactionTrq(Nm)\tZ_Glb_ReactionTrq(Nm)\tLength_Glb_ReactionTrq(Nm)\t"; outf << "Total_Kinetic_Energy(J)\tTranslational_Kinetic_Energy(J)\tAngular_Kinetic_Energy(J)\tDelta_Potential_Energy(J)\t"; outf << std::endl; } else { std::cout << "Output file is invalid" << std::endl; } // Simulation loop // --------------- double timeElapsed = 0; double lastPrint = -printTimeStep; bool continueSimulation = true; while (continueSimulation) { // Write current translational and rotational position, velocity, acceleration, // reaction force, and reaction torque of pendulum to output file //Add a little error tolerance on the end time to ensure that the final data point is recorded if (outf && (timeElapsed <= timeRecord+simTimeStep/2) && (timeElapsed+simTimeStep/2>=lastPrint+printTimeStep)) { lastPrint = lastPrint + printTimeStep; // Time elapsed outf << timeElapsed << "\t"; // Position of the Pendulum's CG in the Global Reference Frame ChVector<double> position = pendulum->GetPos(); outf << position.x << "\t" << position.y << "\t" << position.z << "\t" << (position - loc).Length() << "\t"; // Velocity of the Pendulum's CG in the Global Reference Frame ChVector<double> velocity = pendulum->GetPos_dt(); outf << velocity.x << "\t" << velocity.y << "\t" << velocity.z << "\t" << velocity.Length() << "\t"; // Acceleration of the Pendulum's CG in the Global Reference Frame ChVector<double> acceleration = pendulum->GetPos_dtdt(); outf << acceleration.x << "\t" << acceleration.y << "\t" << acceleration.z << "\t" << acceleration.Length() << "\t"; // Angular Position quaternion of the Pendulum with respect to the Global Reference Frame ChQuaternion<double> rot = pendulum->GetRot(); outf << rot.e0 << "\t" << rot.e1 << "\t" << rot.e2 << "\t" << rot.e3 << "\t"; // Angular Velocity of the Pendulum with respect to the Global Reference Frame ChVector<double> angVel = pendulum->GetWvel_par(); outf << angVel.x << "\t" << angVel.y << "\t" << angVel.z << "\t" << angVel.Length() << "\t"; // Angular Acceleration of the Pendulum with respect to the Global Reference Frame ChVector<double> angAccel = pendulum->GetWacc_par(); outf << angAccel.x << "\t" << angAccel.y << "\t" << angAccel.z << "\t" << angAccel.Length() << "\t"; // Reaction Force and Torque // These are expressed in the link coordinate system. We convert them to // the coordinate system of Body2 (in our case this is the ground). ChCoordsys<> linkCoordsys = revoluteJoint->GetLinkRelativeCoords(); ChVector<double> reactForce = revoluteJoint->Get_react_force(); ChVector<double> reactForceGlobal = linkCoordsys.TransformDirectionLocalToParent(reactForce); outf << reactForceGlobal.x << "\t" << reactForceGlobal.y << "\t" << reactForceGlobal.z << "\t" << reactForceGlobal.Length() << "\t"; ChVector<double> reactTorque = revoluteJoint->Get_react_torque(); ChVector<double> reactTorqueGlobal = linkCoordsys.TransformDirectionLocalToParent(reactTorque); outf << reactTorqueGlobal.x << "\t" << reactTorqueGlobal.y << "\t" << reactTorqueGlobal.z << "\t" << reactTorqueGlobal.Length() << "\t"; // Conservation of Energy //Translational Kinetic Energy (1/2*m*||v||^2) //Rotational Kinetic Energy (1/2 w'*I*w) ChMatrix33*vector is valid since [3x3]*[3x1] = [3x1] //Delta Potential Energy (m*g*dz) ChMatrix33<> inertia = pendulum->GetInertia(); //3x3 Inertia Tensor in the local coordinate frame ChVector<> angVelLoc = pendulum->GetWvel_loc(); double transKE = 0.5*mass*velocity.Length2(); double rotKE = 0.5*Vdot(angVelLoc, inertia * angVelLoc); double deltaPE = mass*g*(position.z-loc.z); double totalKE = transKE + rotKE; outf << totalKE << "\t" << transKE << "\t" << rotKE << "\t" << deltaPE << "\t" << std::endl;; } // Output a message to the command window once timeRecord has been reached // Add a little error tolerance to make sure this event is captured if ((timeElapsed >= timeRecord-simTimeStep/2) && (timeElapsed <= timeRecord+simTimeStep/2)) { std::cout << "All Simulation Results have been recorded to file." << std::endl; } // Advance simulation by one step timeElapsed += simTimeStep; if(Animate) { application->BeginScene(); application->DrawAll(); // Draw an XZ grid at the global origin to add in visualization ChIrrTools::drawGrid( application->GetVideoDriver(), 1, 1, 20, 20, ChCoordsys<>(ChVector<>(0, 0, 0), Q_from_AngX(CH_C_PI_2)), video::SColor(255, 80, 100, 100), true); application->DoStep(); //Take one step in time application->EndScene(); continueSimulation = application->GetDevice()->run(); } else{ my_system.DoStepDynamics(simTimeStep); //Take one step in time continueSimulation = (timeElapsed <= timeRecord+simTimeStep/2); } } // Close output file outf.close(); } // ============================================================================= int main(int argc, char* argv[]) { std::cout << "\nStarting Revolute Test Case 01\n\n"; //Case 1 - Revolute Joint at the origin, and aligned with the global Y axis // Note the revolute joint only allows 1 DOF(rotation about joint z axis) // Therefore, the joint must be rotated -pi/2 about the global x-axis TestRevolute(ChVector<> (0, 0, 0), ChQuaternion<> (Q_from_AngX(-CH_C_PI_2)), .001, "RevoluteJointData_Case01.txt",true); std::cout << "\nStarting Revolute Test Case 02\n\n"; //Case 2 - Revolute Joint at (1,2,3), and aligned with the global axis along Y = Z // Note the revolute joint only allows 1 DOF(rotation about joint z axis) // Therefore, the joint must be rotated -pi/4 about the global x-axis TestRevolute(ChVector<> (1, 2, 3), ChQuaternion<> (Q_from_AngX(-CH_C_PI_4)), .001, "RevoluteJointData_Case02.txt",false); return 0; } <|endoftext|>
<commit_before>// AboutBox.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "AboutBox.h" #include "HeeksFrame.h" BEGIN_EVENT_TABLE( CAboutBox, wxDialog ) EVT_BUTTON( wxID_OK, CAboutBox::OnButtonOK ) END_EVENT_TABLE() CAboutBox::CAboutBox(wxWindow *parent):wxDialog(parent, wxID_ANY, _T(""), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE) { wxPanel *panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxButton *ok_button = new wxButton(panel, wxID_OK, _("OK")); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); wxTextCtrl* text_ctrl = new wxTextCtrl( this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(800,600), wxTE_READONLY | wxTE_MULTILINE); wxString str = wxString(_T("HeeksCAD\n see http://heeks.net, or for source code: http://code.google.com/p/heekscad/\n\nusing Open CASCADE solid modeller - http://www.opencascade.org")) + wxString(_T("\n\nwindows made with wxWidgets 2.8.9 - http://wxwidgets.org")) + wxString(_T("\n\ntext uses glFont Copyright (c) 1998 Brad Fish E-mail: [email protected] Web: http://students.cs.byu.edu/~bfish/")) + wxString(_T("\n\nWritten by:\n Dan Heeks\n Jon Pry\n Jonathan George\n David Nicholls")) + wxString(_T("\n\nWith contributions from:\n Hirutso Enni\n Perttu Ahola\n Dave ( the archivist )\n mpictor\n fenn\n fungunner2\n andrea ( openSUSE )\n g_code")) + wxString(_T("\n\nThis is free, open source software.")); wxString version_str = wxGetApp().m_version_number; version_str.Replace(_T(" "), _T(".")); this->SetTitle(version_str); text_ctrl->WriteText(str + wxGetApp().m_frame->m_extra_about_box_str); //mainsizer->Add( text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() ); //mainsizer->Add( ok_button, wxSizerFlags().Align(wxALIGN_CENTER) ); mainsizer->Add( text_ctrl ); mainsizer->Add( ok_button ); mainsizer->RecalcSizes(); // tell frame to make use of sizer (or constraints, if any) panel->SetAutoLayout( true ); panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void CAboutBox::OnButtonOK(wxCommandEvent& event) { EndModal(wxID_OK); } <commit_msg>updating<commit_after>// AboutBox.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "AboutBox.h" #include "HeeksFrame.h" BEGIN_EVENT_TABLE( CAboutBox, wxDialog ) EVT_BUTTON( wxID_OK, CAboutBox::OnButtonOK ) END_EVENT_TABLE() CAboutBox::CAboutBox(wxWindow *parent):wxDialog(parent, wxID_ANY, _T(""), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE) { wxPanel *panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxButton *ok_button = new wxButton(panel, wxID_OK, _("OK")); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); wxTextCtrl* text_ctrl = new wxTextCtrl( this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(800,600), wxTE_READONLY | wxTE_MULTILINE); wxString str = wxString(_T("HeeksCAD\n see http://heeks.net, or for source code: http://code.google.com/p/heekscad/\n\nusing Open CASCADE solid modeller - http://www.opencascade.org")) + wxString(_T("\n\nwindows made with wxWidgets 2.8.9 - http://wxwidgets.org")) + wxString(_T("\n\ntext uses glFont Copyright (c) 1998 Brad Fish E-mail: [email protected] Web: http://students.cs.byu.edu/~bfish/")) + wxString(_T("\n\nWritten by:\n Dan Heeks\n Jon Pry\n Jonathan George\n David Nicholls")) + wxString(_T("\n\nWith contributions from:\n Hirutso Enni\n Perttu Ahola\n Dave ( the archivist )\n mpictor\n fenn\n fungunner2\n andrea ( openSUSE )\n g_code luigi barbati")) + wxString(_T("\n\nThis is free, open source software.")); wxString version_str = wxGetApp().m_version_number; version_str.Replace(_T(" "), _T(".")); this->SetTitle(version_str); text_ctrl->WriteText(str + wxGetApp().m_frame->m_extra_about_box_str); //mainsizer->Add( text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() ); //mainsizer->Add( ok_button, wxSizerFlags().Align(wxALIGN_CENTER) ); mainsizer->Add( text_ctrl ); mainsizer->Add( ok_button ); mainsizer->RecalcSizes(); // tell frame to make use of sizer (or constraints, if any) panel->SetAutoLayout( true ); panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void CAboutBox::OnButtonOK(wxCommandEvent& event) { EndModal(wxID_OK); } <|endoftext|>
<commit_before>#include "main.h" #include "Calculus.h" #include "Geometry.h" #include "Arithmetic.h" #include "Stack.h" #include "Convolve.h" #include "Filter.h" #include "File.h" #include "Display.h" #include "LAHBPCG.h" #include "header.h" void Gradient::help() { printf("\n-gradient takes the backward differences in the dimension specified by the\n" "argument. Values outside the image are assumed to be zero, so the first row,\n" "or column, or frame, will not change, effectively storing the initial value\n" "to make later integration easy. Multiple arguments can be given to differentiate\n" "with respect to multiple dimensions in order (although the order does not matter).\n\n" "Warning: Don't expect to differentiate more than twice and be able to get back\n" "the image by integrating. Numerical errors will dominate.\n\n" "Usage: ImageStack -load a.tga -gradient x y -save out.tga\n\n"); } void Gradient::parse(vector<string> args) { assert(args.size() > 0, "-gradient requires at least one argument\n"); for (size_t i = 0; i < args.size(); i++) { apply(stack(0), args[i]); } } // gradient can be called as gradient('t') or gradient("xyt") void Gradient::apply(Window im, string dimensions) { for (size_t i = 0; i < dimensions.size(); i++) { apply(im, dimensions[i]); } } void Gradient::apply(Window im, char dimension) { int mint = 0, minx = 0, miny = 0; int dt = 0, dx = 0, dy = 0; if (dimension == 'x') { dx = 1; minx = 1; } else if (dimension == 'y') { dy = 1; miny = 1; } else if (dimension == 't') { dt = 1; mint = 1; } else { panic("Must differentiate with respect to x, y, or t\n"); } // walk backwards through the data, looking at the untouched data for the differences for (int t = im.frames - 1; t >= mint; t--) { for (int y = im.height - 1; y >= miny; y--) { for (int x = im.width - 1; x >= minx; x--) { for (int c = 0; c < im.channels; c++) { im(x, y, t)[c] -= im(x - dx, y - dy, t - dt)[c]; } } } } } void Integrate::help() { printf("\n-integrate computes partial sums along the given dimension. It is the\n" "of the -gradient operator. Multiply dimensions can be given as arguments,\n" "for example -integrate x y will produce a summed area table of an image.\n" "Allowed dimensions are x, y, or t.\n\n" "Warning: Don't expect to integrate more than twice and be able to get back\n" "the image by differentiating. Numerical errors will dominate.\n\n" "Usage: ImageStack -load a.tga -gradient x y -integrate y x -save a.tga\n\n"); } void Integrate::parse(vector<string> args) { assert(args.size() > 0, "-integrate requires at least one argument\n"); for (size_t i = 0; i < args.size(); i++) { apply(stack(0), args[i]); } } // integrate can be called as integrate('t') or integrate("xyt") void Integrate::apply(Window im, string dimensions) { for (size_t i = 0; i < dimensions.size(); i++) { apply(im, dimensions[i]); } } void Integrate::apply(Window im, char dimension) { int minx = 0, miny = 0, mint = 0; int dx = 0, dy = 0, dt = 0; if (dimension == 'x') { dx = 1; minx = 1; } else if (dimension == 'y') { dy = 1; miny = 1; } else if (dimension == 't') { dt = 1; mint = 1; } else { panic("Must integrate with respect to x, y, or t\n"); } // walk forwards through the data, adding up as we go for (int t = mint; t < im.frames; t++) { for (int y = miny; y < im.height; y++) { for (int x = minx; x < im.width; x++) { for (int c = 0; c < im.channels; c++) { im(x, y, t)[c] += im(x - dx, y - dy, t - dt)[c]; } } } } } void GradMag::help() { printf("-gradmag computes the square gradient magnitude at each pixel in x and\n" "y. Temporal gradients are ignored. The gradient is estimated using\n" "backward differences, and the image is assumed to be zero outside its\n" "bounds.\n\n" "Usage: ImageStack -load input.jpg -gradmag -save out.jpg\n"); } void GradMag::parse(vector<string> args) { assert(args.size() == 0, "-laplacian takes no arguments\n"); Image im = apply(stack(0)); pop(); push(im); } Image GradMag::apply(Window im) { Image out(im); Gradient::apply(im, 'x'); Gradient::apply(out, 'y'); for (int t = 0; t < im.frames; t++) { for (int y = 0; y < im.height; y++) { for (int x = 0; x < im.width; x++) { for (int c = 0; c < im.channels; c++) { out(x, y, t)[c] = im(x, y, t)[c] * im(x, y, t)[c] + out(x, y, t)[c] * out(x, y, t)[c]; } } } } return out; } void Poisson::help() { pprintf("-poisson assumes the stack contains gradients images in x and y, and" " attempts to find the image which fits those gradients best in a least" " squares sense. It uses a preconditioned conjugate gradient descent" " method. It takes one argument, which is required RMS error of the" " result. This defaults to 0.01 if not given.\n" "\n" "Usage: ImageStack -load dx.tmp -load dy.tmp \n" " -poisson 0.0001 -save out.tga\n\n"); } void Poisson::parse(vector<string> args) { assert(args.size() < 2, "-poisson requires one or fewer arguments\n"); float rms = 0.01; if (args.size() > 0) { rms = readFloat(args[0]); } push(apply(stack(1), stack(0), rms)); } Image Poisson::apply(Window dx, Window dy, float rms) { assert(dx.width == dy.width && dx.height == dy.height && dx.frames == dy.frames && dx.channels == dy.channels, "derivatives must be matching size and number of channels\n"); Image zerosc(dx.width, dx.height, dx.frames, dx.channels); Image zeros1(dx.width, dx.height, dx.frames, 1); Image ones1(dx.width, dx.height, dx.frames, 1); Offset::apply(ones1, 1.0f); return LAHBPCG::apply(zerosc, dx, dy, zeros1, ones1, ones1, 999999, rms); } #include "footer.h" <commit_msg>Fixed a bug in gradmag<commit_after>#include "main.h" #include "Calculus.h" #include "Geometry.h" #include "Arithmetic.h" #include "Stack.h" #include "Convolve.h" #include "Filter.h" #include "File.h" #include "Display.h" #include "LAHBPCG.h" #include "header.h" void Gradient::help() { printf("\n-gradient takes the backward differences in the dimension specified by the\n" "argument. Values outside the image are assumed to be zero, so the first row,\n" "or column, or frame, will not change, effectively storing the initial value\n" "to make later integration easy. Multiple arguments can be given to differentiate\n" "with respect to multiple dimensions in order (although the order does not matter).\n\n" "Warning: Don't expect to differentiate more than twice and be able to get back\n" "the image by integrating. Numerical errors will dominate.\n\n" "Usage: ImageStack -load a.tga -gradient x y -save out.tga\n\n"); } void Gradient::parse(vector<string> args) { assert(args.size() > 0, "-gradient requires at least one argument\n"); for (size_t i = 0; i < args.size(); i++) { apply(stack(0), args[i]); } } // gradient can be called as gradient('t') or gradient("xyt") void Gradient::apply(Window im, string dimensions) { for (size_t i = 0; i < dimensions.size(); i++) { apply(im, dimensions[i]); } } void Gradient::apply(Window im, char dimension) { int mint = 0, minx = 0, miny = 0; int dt = 0, dx = 0, dy = 0; if (dimension == 'x') { dx = 1; minx = 1; } else if (dimension == 'y') { dy = 1; miny = 1; } else if (dimension == 't') { dt = 1; mint = 1; } else { panic("Must differentiate with respect to x, y, or t\n"); } // walk backwards through the data, looking at the untouched data for the differences for (int t = im.frames - 1; t >= mint; t--) { for (int y = im.height - 1; y >= miny; y--) { for (int x = im.width - 1; x >= minx; x--) { for (int c = 0; c < im.channels; c++) { im(x, y, t)[c] -= im(x - dx, y - dy, t - dt)[c]; } } } } } void Integrate::help() { printf("\n-integrate computes partial sums along the given dimension. It is the\n" "of the -gradient operator. Multiply dimensions can be given as arguments,\n" "for example -integrate x y will produce a summed area table of an image.\n" "Allowed dimensions are x, y, or t.\n\n" "Warning: Don't expect to integrate more than twice and be able to get back\n" "the image by differentiating. Numerical errors will dominate.\n\n" "Usage: ImageStack -load a.tga -gradient x y -integrate y x -save a.tga\n\n"); } void Integrate::parse(vector<string> args) { assert(args.size() > 0, "-integrate requires at least one argument\n"); for (size_t i = 0; i < args.size(); i++) { apply(stack(0), args[i]); } } // integrate can be called as integrate('t') or integrate("xyt") void Integrate::apply(Window im, string dimensions) { for (size_t i = 0; i < dimensions.size(); i++) { apply(im, dimensions[i]); } } void Integrate::apply(Window im, char dimension) { int minx = 0, miny = 0, mint = 0; int dx = 0, dy = 0, dt = 0; if (dimension == 'x') { dx = 1; minx = 1; } else if (dimension == 'y') { dy = 1; miny = 1; } else if (dimension == 't') { dt = 1; mint = 1; } else { panic("Must integrate with respect to x, y, or t\n"); } // walk forwards through the data, adding up as we go for (int t = mint; t < im.frames; t++) { for (int y = miny; y < im.height; y++) { for (int x = minx; x < im.width; x++) { for (int c = 0; c < im.channels; c++) { im(x, y, t)[c] += im(x - dx, y - dy, t - dt)[c]; } } } } } void GradMag::help() { printf("-gradmag computes the square gradient magnitude at each pixel in x and\n" "y. Temporal gradients are ignored. The gradient is estimated using\n" "backward differences, and the image is assumed to be zero outside its\n" "bounds.\n\n" "Usage: ImageStack -load input.jpg -gradmag -save out.jpg\n"); } void GradMag::parse(vector<string> args) { assert(args.size() == 0, "-laplacian takes no arguments\n"); Image im = apply(stack(0)); pop(); push(im); } Image GradMag::apply(Window im) { Image out(im.width, im.height, im.frames, im.channels); for (int t = 0; t < im.frames; t++) { for (int y = 0; y < im.height; y++) { for (int x = 0; x < im.width; x++) { for (int c = 0; c < im.channels; c++) { float dx = im(x, y, t)[c] - (x > 0 ? im(x-1, y, t)[c] : 0); float dy = im(x, y, t)[c] - (y > 0 ? im(x, y-1, t)[c] : 0); out(x, y, t)[c] = dx*dx + dy*dy; } } } } return out; } void Poisson::help() { pprintf("-poisson assumes the stack contains gradients images in x and y, and" " attempts to find the image which fits those gradients best in a least" " squares sense. It uses a preconditioned conjugate gradient descent" " method. It takes one argument, which is required RMS error of the" " result. This defaults to 0.01 if not given.\n" "\n" "Usage: ImageStack -load dx.tmp -load dy.tmp \n" " -poisson 0.0001 -save out.tga\n\n"); } void Poisson::parse(vector<string> args) { assert(args.size() < 2, "-poisson requires one or fewer arguments\n"); float rms = 0.01; if (args.size() > 0) { rms = readFloat(args[0]); } push(apply(stack(1), stack(0), rms)); } Image Poisson::apply(Window dx, Window dy, float rms) { assert(dx.width == dy.width && dx.height == dy.height && dx.frames == dy.frames && dx.channels == dy.channels, "derivatives must be matching size and number of channels\n"); Image zerosc(dx.width, dx.height, dx.frames, dx.channels); Image zeros1(dx.width, dx.height, dx.frames, 1); Image ones1(dx.width, dx.height, dx.frames, 1); Offset::apply(ones1, 1.0f); return LAHBPCG::apply(zerosc, dx, dy, zeros1, ones1, ones1, 999999, rms); } #include "footer.h" <|endoftext|>
<commit_before>#include "Animator.h" #include "Graphics.h" #include "Rect.h" #define ANIMATOR WalrusRPG::Animator #define FRAME WalrusRPG::Frame #define UTILS WalrusRPG::Utils namespace { unsigned find_frame(const tinystl::vector<WalrusRPG::Frame> &anim, signed frame_time) { unsigned index = 0; do { frame_time -= anim[index].duration; index = (index + 1) % anim.size(); } while (frame_time > 0); return index; } } ANIMATOR::Animator() { } void ANIMATOR::add_animation(int index, Animation anim) { animations[index] = anim; } unsigned ANIMATOR::get_animation_frame(unsigned id) { if (animations[id].stripe.empty()) return id; return find_frame(animations[id].stripe, elapsed_time); } void ANIMATOR::update(unsigned dt) { elapsed_time += dt; } <commit_msg>Added the not looping back feature to Animator.<commit_after>#include "Animator.h" #include "Graphics.h" #include "Rect.h" #define ANIMATOR WalrusRPG::Animator #define FRAME WalrusRPG::Frame #define UTILS WalrusRPG::Utils namespace { unsigned find_frame(const WalrusRPG::Animation &anim, signed frame_time) { unsigned index = 0; do { frame_time -= anim.stripe[index].duration; index++; if (index >= anim.stripe.size() && anim.looping) index -= anim.stripe.size(); else return anim.stripe.size() - 1; } while (frame_time > 0); return index; } } ANIMATOR::Animator() { } void ANIMATOR::add_animation(int index, Animation anim) { animations[index] = anim; } unsigned ANIMATOR::get_animation_frame(unsigned id) { if (animations[id].stripe.empty()) return id; return find_frame(animations[id], elapsed_time); } void ANIMATOR::update(unsigned dt) { elapsed_time += dt; } <|endoftext|>
<commit_before>// Ignore unused parameter warnings coming from cppunit headers #include <libmesh/ignore_warnings.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <libmesh/restore_warnings.h> #include <libmesh/parallel.h> #include "test_comm.h" // THE CPPUNIT_TEST_SUITE_END macro expands to code that involves // std::auto_ptr, which in turn produces -Wdeprecated-declarations // warnings. These can be ignored in GCC as long as we wrap the // offending code in appropriate pragmas. We can't get away with a // single ignore_warnings.h inclusion at the beginning of this file, // since the libmesh headers pull in a restore_warnings.h at some // point. We also don't bother restoring warnings at the end of this // file since it's not a header. #include <libmesh/ignore_warnings.h> using namespace libMesh; class ParallelTest : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE( ParallelTest ); CPPUNIT_TEST( testGather ); CPPUNIT_TEST( testAllGather ); CPPUNIT_TEST( testBroadcast ); CPPUNIT_TEST( testScatter ); CPPUNIT_TEST( testBarrier ); CPPUNIT_TEST( testMin ); CPPUNIT_TEST( testMax ); CPPUNIT_TEST( testInfinityMin ); CPPUNIT_TEST( testInfinityMax ); CPPUNIT_TEST( testIsendRecv ); CPPUNIT_TEST( testIrecvSend ); CPPUNIT_TEST( testSemiVerify ); CPPUNIT_TEST( testSplit ); CPPUNIT_TEST_SUITE_END(); private: public: void setUp() {} void tearDown() {} void testGather() { std::vector<processor_id_type> vals; TestCommWorld->gather(0,cast_int<processor_id_type>(TestCommWorld->rank()),vals); if (TestCommWorld->rank() == 0) for (processor_id_type i=0; i<vals.size(); i++) CPPUNIT_ASSERT_EQUAL( i , vals[i] ); } void testAllGather() { std::vector<processor_id_type> vals; TestCommWorld->allgather(cast_int<processor_id_type>(TestCommWorld->rank()),vals); for (processor_id_type i=0; i<vals.size(); i++) CPPUNIT_ASSERT_EQUAL( i , vals[i] ); } void testBroadcast() { std::vector<unsigned int> src(3), dest(3); src[0]=0; src[1]=1; src[2]=2; if (TestCommWorld->rank() == 0) dest = src; TestCommWorld->broadcast(dest); for (unsigned int i=0; i<src.size(); i++) CPPUNIT_ASSERT_EQUAL( src[i] , dest[i] ); } void testScatter() { // Test Scalar scatter { std::vector<unsigned int> src; unsigned int dest; if (TestCommWorld->rank() == 0) { src.resize(TestCommWorld->size()); for (unsigned int i=0; i<src.size(); i++) src[i] = i; } TestCommWorld->scatter(src, dest); CPPUNIT_ASSERT_EQUAL( TestCommWorld->rank(), dest ); } // Test Vector Scatter (equal-sized chunks) { std::vector<unsigned int> src; std::vector<unsigned int> dest; static const unsigned int CHUNK_SIZE = 3; if (TestCommWorld->rank() == 0) { src.resize(TestCommWorld->size() * CHUNK_SIZE); for (unsigned int i=0; i<src.size(); i++) src[i] = i; } TestCommWorld->scatter(src, dest); for (unsigned int i=0; i<CHUNK_SIZE; i++) CPPUNIT_ASSERT_EQUAL( TestCommWorld->rank() * CHUNK_SIZE + i, dest[i] ); } // Test Vector Scatter (jagged chunks) { std::vector<unsigned int> src; std::vector<unsigned int> dest; std::vector<int> counts; if (TestCommWorld->rank() == 0) { // Give each processor "rank" number of items ( Sum i=1..n == (n * (n + 1))/2 ) src.resize((TestCommWorld->size() * (TestCommWorld->size() + 1)) / 2); counts.resize(TestCommWorld->size()); for (unsigned int i=0; i<src.size(); i++) src[i] = i; for (unsigned int i=0; i<TestCommWorld->size(); i++) counts[i] = static_cast<int>(i+1); } TestCommWorld->scatter(src, counts, dest); unsigned int start_value = (TestCommWorld->rank() * (TestCommWorld->rank() + 1)) / 2; for (unsigned int i=0; i<=TestCommWorld->rank(); i++) CPPUNIT_ASSERT_EQUAL( start_value + i, dest[i] ); } // Test Vector of Vector Scatter { std::vector<std::vector<unsigned int> > src; std::vector<unsigned int> dest; if (TestCommWorld->rank() == 0) { // Give each processor "rank" number of items ( Sum i=1..n == (n * (n + 1))/2 ) src.resize(TestCommWorld->size()); for (unsigned int i=0; i<src.size(); ++i) src[i].resize(i+1); unsigned int global_counter = 0; for (unsigned int i=0; i<src.size(); i++) for (unsigned int j=0; j<src[i].size(); j++) src[i][j] = global_counter++; } TestCommWorld->scatter(src, dest); unsigned int start_value = (TestCommWorld->rank() * (TestCommWorld->rank() + 1)) / 2; for (unsigned int i=0; i<=TestCommWorld->rank(); i++) CPPUNIT_ASSERT_EQUAL( start_value + i, dest[i] ); } } void testBarrier() { TestCommWorld->barrier(); } void testMin () { unsigned int min = TestCommWorld->rank(); TestCommWorld->min(min); CPPUNIT_ASSERT_EQUAL (min, static_cast<unsigned int>(0)); } void testMax () { processor_id_type max = TestCommWorld->rank(); TestCommWorld->max(max); CPPUNIT_ASSERT_EQUAL (cast_int<processor_id_type>(max+1), cast_int<processor_id_type>(TestCommWorld->size())); } void testInfinityMin () { double min = std::numeric_limits<double>::infinity(); TestCommWorld->min(min); CPPUNIT_ASSERT_EQUAL (min, std::numeric_limits<double>::infinity()); min = -std::numeric_limits<double>::infinity(); TestCommWorld->min(min); CPPUNIT_ASSERT_EQUAL (min, -std::numeric_limits<double>::infinity()); } void testInfinityMax () { double max = std::numeric_limits<double>::infinity(); TestCommWorld->max(max); CPPUNIT_ASSERT_EQUAL (max, std::numeric_limits<double>::infinity()); max = -std::numeric_limits<double>::infinity(); TestCommWorld->max(max); CPPUNIT_ASSERT_EQUAL (max, -std::numeric_limits<double>::infinity()); } void testIsendRecv () { unsigned int procup = (TestCommWorld->rank() + 1) % TestCommWorld->size(); unsigned int procdown = (TestCommWorld->size() + TestCommWorld->rank() - 1) % TestCommWorld->size(); std::vector<unsigned int> src_val(3), recv_val(3); src_val[0] = 0; src_val[1] = 1; src_val[2] = 2; Parallel::Request request; if (TestCommWorld->size() > 1) { // Default communication TestCommWorld->send_mode(Parallel::Communicator::DEFAULT); TestCommWorld->send (procup, src_val, request); TestCommWorld->receive (procdown, recv_val); Parallel::wait (request); CPPUNIT_ASSERT_EQUAL ( src_val.size() , recv_val.size() ); for (unsigned int i=0; i<src_val.size(); i++) CPPUNIT_ASSERT_EQUAL( src_val[i] , recv_val[i] ); // Synchronous communication TestCommWorld->send_mode(Parallel::Communicator::SYNCHRONOUS); std::fill (recv_val.begin(), recv_val.end(), 0); TestCommWorld->send (procup, src_val, request); TestCommWorld->receive (procdown, recv_val); Parallel::wait (request); CPPUNIT_ASSERT_EQUAL ( src_val.size() , recv_val.size() ); for (unsigned int i=0; i<src_val.size(); i++) CPPUNIT_ASSERT_EQUAL( src_val[i] , recv_val[i] ); // Restore default communication TestCommWorld->send_mode(Parallel::Communicator::DEFAULT); } } void testIrecvSend () { unsigned int procup = (TestCommWorld->rank() + 1) % TestCommWorld->size(); unsigned int procdown = (TestCommWorld->size() + TestCommWorld->rank() - 1) % TestCommWorld->size(); std::vector<unsigned int> src_val(3), recv_val(3); src_val[0] = 0; src_val[1] = 1; src_val[2] = 2; Parallel::Request request; if (TestCommWorld->size() > 1) { // Default communication TestCommWorld->send_mode(Parallel::Communicator::DEFAULT); TestCommWorld->receive (procdown, recv_val, request); TestCommWorld->send (procup, src_val); Parallel::wait (request); CPPUNIT_ASSERT_EQUAL ( src_val.size() , recv_val.size() ); for (unsigned int i=0; i<src_val.size(); i++) CPPUNIT_ASSERT_EQUAL( src_val[i] , recv_val[i] ); // Synchronous communication TestCommWorld->send_mode(Parallel::Communicator::SYNCHRONOUS); std::fill (recv_val.begin(), recv_val.end(), 0); TestCommWorld->receive (procdown, recv_val, request); TestCommWorld->send (procup, src_val); Parallel::wait (request); CPPUNIT_ASSERT_EQUAL ( src_val.size() , recv_val.size() ); for (unsigned int i=0; i<src_val.size(); i++) CPPUNIT_ASSERT_EQUAL( src_val[i] , recv_val[i] ); // Restore default communication TestCommWorld->send_mode(Parallel::Communicator::DEFAULT); } } void testSemiVerify () { double inf = std::numeric_limits<double>::infinity(); double *infptr = TestCommWorld->rank()%2 ? NULL : &inf; CPPUNIT_ASSERT (TestCommWorld->semiverify(infptr)); inf = -std::numeric_limits<double>::infinity(); CPPUNIT_ASSERT (TestCommWorld->semiverify(infptr)); } void testSplit () { Parallel::Communicator subcomm; unsigned int rank = TestCommWorld->rank(); unsigned int color = rank % 2; TestCommWorld->split(color, rank, subcomm); } }; CPPUNIT_TEST_SUITE_REGISTRATION( ParallelTest ); <commit_msg>Add unit tests for gather/allgather string overloads<commit_after>// Ignore unused parameter warnings coming from cppunit headers #include <libmesh/ignore_warnings.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <libmesh/restore_warnings.h> #include <libmesh/parallel.h> #include "test_comm.h" // THE CPPUNIT_TEST_SUITE_END macro expands to code that involves // std::auto_ptr, which in turn produces -Wdeprecated-declarations // warnings. These can be ignored in GCC as long as we wrap the // offending code in appropriate pragmas. We can't get away with a // single ignore_warnings.h inclusion at the beginning of this file, // since the libmesh headers pull in a restore_warnings.h at some // point. We also don't bother restoring warnings at the end of this // file since it's not a header. #include <libmesh/ignore_warnings.h> using namespace libMesh; class ParallelTest : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE( ParallelTest ); CPPUNIT_TEST( testGather ); CPPUNIT_TEST( testAllGather ); CPPUNIT_TEST( testGatherString ); CPPUNIT_TEST( testAllGatherString ); CPPUNIT_TEST( testBroadcast ); CPPUNIT_TEST( testScatter ); CPPUNIT_TEST( testBarrier ); CPPUNIT_TEST( testMin ); CPPUNIT_TEST( testMax ); CPPUNIT_TEST( testInfinityMin ); CPPUNIT_TEST( testInfinityMax ); CPPUNIT_TEST( testIsendRecv ); CPPUNIT_TEST( testIrecvSend ); CPPUNIT_TEST( testSemiVerify ); CPPUNIT_TEST( testSplit ); CPPUNIT_TEST_SUITE_END(); private: std::vector<std::string> _number; public: void setUp() { _number.resize(10); _number[0] = "Zero"; _number[1] = "One"; _number[2] = "Two"; _number[3] = "Three"; _number[4] = "Four"; _number[5] = "Five"; _number[6] = "Six"; _number[7] = "Seven"; _number[8] = "Eight"; _number[9] = "Nine"; } void tearDown() {} void testGather() { std::vector<processor_id_type> vals; TestCommWorld->gather(0,cast_int<processor_id_type>(TestCommWorld->rank()),vals); if (TestCommWorld->rank() == 0) for (processor_id_type i=0; i<vals.size(); i++) CPPUNIT_ASSERT_EQUAL( i , vals[i] ); } void testGatherString() { std::vector<std::string> vals; TestCommWorld->gather(0, "Processor" + _number[TestCommWorld->rank() % 10], vals); if (TestCommWorld->rank() == 0) for (processor_id_type i=0; i<vals.size(); i++) CPPUNIT_ASSERT_EQUAL( "Processor" + _number[i % 10] , vals[i] ); } void testAllGather() { std::vector<processor_id_type> vals; TestCommWorld->allgather(cast_int<processor_id_type>(TestCommWorld->rank()),vals); for (processor_id_type i=0; i<vals.size(); i++) CPPUNIT_ASSERT_EQUAL( i , vals[i] ); } void testAllGatherString() { std::vector<std::string> vals; TestCommWorld->gather(0, "Processor" + _number[TestCommWorld->rank() % 10], vals); for (processor_id_type i=0; i<vals.size(); i++) CPPUNIT_ASSERT_EQUAL( "Processor" + _number[i % 10] , vals[i] ); } void testBroadcast() { std::vector<unsigned int> src(3), dest(3); src[0]=0; src[1]=1; src[2]=2; if (TestCommWorld->rank() == 0) dest = src; TestCommWorld->broadcast(dest); for (unsigned int i=0; i<src.size(); i++) CPPUNIT_ASSERT_EQUAL( src[i] , dest[i] ); } void testScatter() { // Test Scalar scatter { std::vector<unsigned int> src; unsigned int dest; if (TestCommWorld->rank() == 0) { src.resize(TestCommWorld->size()); for (unsigned int i=0; i<src.size(); i++) src[i] = i; } TestCommWorld->scatter(src, dest); CPPUNIT_ASSERT_EQUAL( TestCommWorld->rank(), dest ); } // Test Vector Scatter (equal-sized chunks) { std::vector<unsigned int> src; std::vector<unsigned int> dest; static const unsigned int CHUNK_SIZE = 3; if (TestCommWorld->rank() == 0) { src.resize(TestCommWorld->size() * CHUNK_SIZE); for (unsigned int i=0; i<src.size(); i++) src[i] = i; } TestCommWorld->scatter(src, dest); for (unsigned int i=0; i<CHUNK_SIZE; i++) CPPUNIT_ASSERT_EQUAL( TestCommWorld->rank() * CHUNK_SIZE + i, dest[i] ); } // Test Vector Scatter (jagged chunks) { std::vector<unsigned int> src; std::vector<unsigned int> dest; std::vector<int> counts; if (TestCommWorld->rank() == 0) { // Give each processor "rank" number of items ( Sum i=1..n == (n * (n + 1))/2 ) src.resize((TestCommWorld->size() * (TestCommWorld->size() + 1)) / 2); counts.resize(TestCommWorld->size()); for (unsigned int i=0; i<src.size(); i++) src[i] = i; for (unsigned int i=0; i<TestCommWorld->size(); i++) counts[i] = static_cast<int>(i+1); } TestCommWorld->scatter(src, counts, dest); unsigned int start_value = (TestCommWorld->rank() * (TestCommWorld->rank() + 1)) / 2; for (unsigned int i=0; i<=TestCommWorld->rank(); i++) CPPUNIT_ASSERT_EQUAL( start_value + i, dest[i] ); } // Test Vector of Vector Scatter { std::vector<std::vector<unsigned int> > src; std::vector<unsigned int> dest; if (TestCommWorld->rank() == 0) { // Give each processor "rank" number of items ( Sum i=1..n == (n * (n + 1))/2 ) src.resize(TestCommWorld->size()); for (unsigned int i=0; i<src.size(); ++i) src[i].resize(i+1); unsigned int global_counter = 0; for (unsigned int i=0; i<src.size(); i++) for (unsigned int j=0; j<src[i].size(); j++) src[i][j] = global_counter++; } TestCommWorld->scatter(src, dest); unsigned int start_value = (TestCommWorld->rank() * (TestCommWorld->rank() + 1)) / 2; for (unsigned int i=0; i<=TestCommWorld->rank(); i++) CPPUNIT_ASSERT_EQUAL( start_value + i, dest[i] ); } } void testBarrier() { TestCommWorld->barrier(); } void testMin () { unsigned int min = TestCommWorld->rank(); TestCommWorld->min(min); CPPUNIT_ASSERT_EQUAL (min, static_cast<unsigned int>(0)); } void testMax () { processor_id_type max = TestCommWorld->rank(); TestCommWorld->max(max); CPPUNIT_ASSERT_EQUAL (cast_int<processor_id_type>(max+1), cast_int<processor_id_type>(TestCommWorld->size())); } void testInfinityMin () { double min = std::numeric_limits<double>::infinity(); TestCommWorld->min(min); CPPUNIT_ASSERT_EQUAL (min, std::numeric_limits<double>::infinity()); min = -std::numeric_limits<double>::infinity(); TestCommWorld->min(min); CPPUNIT_ASSERT_EQUAL (min, -std::numeric_limits<double>::infinity()); } void testInfinityMax () { double max = std::numeric_limits<double>::infinity(); TestCommWorld->max(max); CPPUNIT_ASSERT_EQUAL (max, std::numeric_limits<double>::infinity()); max = -std::numeric_limits<double>::infinity(); TestCommWorld->max(max); CPPUNIT_ASSERT_EQUAL (max, -std::numeric_limits<double>::infinity()); } void testIsendRecv () { unsigned int procup = (TestCommWorld->rank() + 1) % TestCommWorld->size(); unsigned int procdown = (TestCommWorld->size() + TestCommWorld->rank() - 1) % TestCommWorld->size(); std::vector<unsigned int> src_val(3), recv_val(3); src_val[0] = 0; src_val[1] = 1; src_val[2] = 2; Parallel::Request request; if (TestCommWorld->size() > 1) { // Default communication TestCommWorld->send_mode(Parallel::Communicator::DEFAULT); TestCommWorld->send (procup, src_val, request); TestCommWorld->receive (procdown, recv_val); Parallel::wait (request); CPPUNIT_ASSERT_EQUAL ( src_val.size() , recv_val.size() ); for (unsigned int i=0; i<src_val.size(); i++) CPPUNIT_ASSERT_EQUAL( src_val[i] , recv_val[i] ); // Synchronous communication TestCommWorld->send_mode(Parallel::Communicator::SYNCHRONOUS); std::fill (recv_val.begin(), recv_val.end(), 0); TestCommWorld->send (procup, src_val, request); TestCommWorld->receive (procdown, recv_val); Parallel::wait (request); CPPUNIT_ASSERT_EQUAL ( src_val.size() , recv_val.size() ); for (unsigned int i=0; i<src_val.size(); i++) CPPUNIT_ASSERT_EQUAL( src_val[i] , recv_val[i] ); // Restore default communication TestCommWorld->send_mode(Parallel::Communicator::DEFAULT); } } void testIrecvSend () { unsigned int procup = (TestCommWorld->rank() + 1) % TestCommWorld->size(); unsigned int procdown = (TestCommWorld->size() + TestCommWorld->rank() - 1) % TestCommWorld->size(); std::vector<unsigned int> src_val(3), recv_val(3); src_val[0] = 0; src_val[1] = 1; src_val[2] = 2; Parallel::Request request; if (TestCommWorld->size() > 1) { // Default communication TestCommWorld->send_mode(Parallel::Communicator::DEFAULT); TestCommWorld->receive (procdown, recv_val, request); TestCommWorld->send (procup, src_val); Parallel::wait (request); CPPUNIT_ASSERT_EQUAL ( src_val.size() , recv_val.size() ); for (unsigned int i=0; i<src_val.size(); i++) CPPUNIT_ASSERT_EQUAL( src_val[i] , recv_val[i] ); // Synchronous communication TestCommWorld->send_mode(Parallel::Communicator::SYNCHRONOUS); std::fill (recv_val.begin(), recv_val.end(), 0); TestCommWorld->receive (procdown, recv_val, request); TestCommWorld->send (procup, src_val); Parallel::wait (request); CPPUNIT_ASSERT_EQUAL ( src_val.size() , recv_val.size() ); for (unsigned int i=0; i<src_val.size(); i++) CPPUNIT_ASSERT_EQUAL( src_val[i] , recv_val[i] ); // Restore default communication TestCommWorld->send_mode(Parallel::Communicator::DEFAULT); } } void testSemiVerify () { double inf = std::numeric_limits<double>::infinity(); double *infptr = TestCommWorld->rank()%2 ? NULL : &inf; CPPUNIT_ASSERT (TestCommWorld->semiverify(infptr)); inf = -std::numeric_limits<double>::infinity(); CPPUNIT_ASSERT (TestCommWorld->semiverify(infptr)); } void testSplit () { Parallel::Communicator subcomm; unsigned int rank = TestCommWorld->rank(); unsigned int color = rank % 2; TestCommWorld->split(color, rank, subcomm); } }; CPPUNIT_TEST_SUITE_REGISTRATION( ParallelTest ); <|endoftext|>
<commit_before>/** * @file Database.cpp * @ingroup SQLiteCpp * @brief Management of a SQLite Database Connection. * * Copyright (c) 2012-2013 Sebastien Rombauts ([email protected]) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include <SQLiteCpp/Database.h> #include <SQLiteCpp/Statement.h> #include <SQLiteCpp/Assertion.h> #include <SQLiteCpp/Exception.h> #include <string> #ifndef SQLITE_DETERMINISTIC #define SQLITE_DETERMINISTIC 0x800 #endif // SQLITE_DETERMINISTIC namespace SQLite { // Open the provided database UTF-8 filename with SQLITE_OPEN_xxx provided flags. Database::Database(const char* apFilename, const int aFlags /* = SQLITE_OPEN_READONLY*/, const int aBusyTimeoutMs /* = 0 */, const char* apVfs /* = NULL*/) : mpSQLite(NULL), mFilename(apFilename) { const int ret = sqlite3_open_v2(apFilename, &mpSQLite, aFlags, apVfs); if (SQLITE_OK != ret) { std::string strerr = sqlite3_errmsg(mpSQLite); sqlite3_close(mpSQLite); // close is required even in case of error on opening throw SQLite::Exception(strerr); } if (aBusyTimeoutMs > 0) { setBusyTimeout(aBusyTimeoutMs); } } // Open the provided database UTF-8 filename with SQLITE_OPEN_xxx provided flags. Database::Database(const std::string& aFilename, const int aFlags /* = SQLITE_OPEN_READONLY*/, const int aBusyTimeoutMs /* = 0 */, const std::string& aVfs /* = "" */) : mpSQLite(NULL), mFilename(aFilename) { const int ret = sqlite3_open_v2(aFilename.c_str(), &mpSQLite, aFlags, aVfs.empty() ? NULL : aVfs.c_str()); if (SQLITE_OK != ret) { std::string strerr = sqlite3_errmsg(mpSQLite); sqlite3_close(mpSQLite); // close is required even in case of error on opening throw SQLite::Exception(strerr); } if (aBusyTimeoutMs > 0) { setBusyTimeout(aBusyTimeoutMs); } } // Close the SQLite database connection. Database::~Database() noexcept // nothrow { const int ret = sqlite3_close(mpSQLite); // Only case of error is SQLITE_BUSY: "database is locked" (some statements are not finalized) // Never throw an exception in a destructor : SQLITECPP_ASSERT(SQLITE_OK == ret, "database is locked"); // See SQLITECPP_ENABLE_ASSERT_HANDLER } /** * @brief Set a busy handler that sleeps for a specified amount of time when a table is locked. * * This is usefull in multithreaded program to handle case where a table is locked for writting by a thread. * Any other thread cannot access the table and will receive a SQLITE_BUSY error: * setting a timeout will wait and retry up to the time specified before returning this SQLITE_BUSY error. * Reading the value of timeout for current connection can be done with SQL query "PRAGMA busy_timeout;". * Default busy timeout is 0ms. * * @param[in] aBusyTimeoutMs Amount of milliseconds to wait before returning SQLITE_BUSY * * @throw SQLite::Exception in case of error */ void Database::setBusyTimeout(const int aBusyTimeoutMs) noexcept // nothrow { const int ret = sqlite3_busy_timeout(mpSQLite, aBusyTimeoutMs); check(ret); } // Shortcut to execute one or multiple SQL statements without results (UPDATE, INSERT, ALTER, COMMIT, CREATE...). int Database::exec(const char* apQueries) { const int ret = sqlite3_exec(mpSQLite, apQueries, NULL, NULL, NULL); check(ret); // Return the number of rows modified by those SQL statements (INSERT, UPDATE or DELETE only) return sqlite3_changes(mpSQLite); } // Shortcut to execute a one step query and fetch the first column of the result. // WARNING: Be very careful with this dangerous method: you have to // make a COPY OF THE result, else it will be destroy before the next line // (when the underlying temporary Statement and Column objects are destroyed) // this is an issue only for pointer type result (ie. char* and blob) // (use the Column copy-constructor) Column Database::execAndGet(const char* apQuery) { Statement query(*this, apQuery); (void)query.executeStep(); // Can return false if no result, which will throw next line in getColumn() return query.getColumn(0); } // Shortcut to test if a table exists. bool Database::tableExists(const char* apTableName) { Statement query(*this, "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?"); query.bind(1, apTableName); (void)query.executeStep(); // Cannot return false, as the above query always return a result const int Nb = query.getColumn(0); return (1 == Nb); } // Attach a custom function to your sqlite database. Assumes UTF8 text representation. // Parameter details can be found here: http://www.sqlite.org/c3ref/create_function.html void Database::createFunction(const char* apFuncName, int aNbArg, bool abDeterministic, void* apApp, void (*apFunc)(sqlite3_context *, int, sqlite3_value **), void (*apStep)(sqlite3_context *, int, sqlite3_value **), void (*apFinal)(sqlite3_context *), // NOLINT(readability/casting) void (*apDestroy)(void *)) { int TextRep = SQLITE_UTF8; // optimization if deterministic function (e.g. of nondeterministic function random()) if (abDeterministic) { TextRep = TextRep|SQLITE_DETERMINISTIC; } const int ret = sqlite3_create_function_v2(mpSQLite, apFuncName, aNbArg, TextRep, apApp, apFunc, apStep, apFinal, apDestroy); check(ret); } // Load an extension into the sqlite database. Only affects the current connection. // Parameter details can be found here: http://www.sqlite.org/c3ref/load_extension.html void Database::loadExtension(const char* apExtensionName, const char *apEntryPointName) { int ret = sqlite3_enable_load_extension(mpSQLite, 1); check(ret); ret = sqlite3_load_extension(mpSQLite, apExtensionName, apEntryPointName, 0); check(ret); } } // namespace SQLite <commit_msg>Added conditional support for extension loading<commit_after>/** * @file Database.cpp * @ingroup SQLiteCpp * @brief Management of a SQLite Database Connection. * * Copyright (c) 2012-2013 Sebastien Rombauts ([email protected]) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include <SQLiteCpp/Database.h> #include <SQLiteCpp/Statement.h> #include <SQLiteCpp/Assertion.h> #include <SQLiteCpp/Exception.h> #include <string> #ifndef SQLITE_DETERMINISTIC #define SQLITE_DETERMINISTIC 0x800 #endif // SQLITE_DETERMINISTIC namespace SQLite { // Open the provided database UTF-8 filename with SQLITE_OPEN_xxx provided flags. Database::Database(const char* apFilename, const int aFlags /* = SQLITE_OPEN_READONLY*/, const int aBusyTimeoutMs /* = 0 */, const char* apVfs /* = NULL*/) : mpSQLite(NULL), mFilename(apFilename) { const int ret = sqlite3_open_v2(apFilename, &mpSQLite, aFlags, apVfs); if (SQLITE_OK != ret) { std::string strerr = sqlite3_errmsg(mpSQLite); sqlite3_close(mpSQLite); // close is required even in case of error on opening throw SQLite::Exception(strerr); } if (aBusyTimeoutMs > 0) { setBusyTimeout(aBusyTimeoutMs); } } // Open the provided database UTF-8 filename with SQLITE_OPEN_xxx provided flags. Database::Database(const std::string& aFilename, const int aFlags /* = SQLITE_OPEN_READONLY*/, const int aBusyTimeoutMs /* = 0 */, const std::string& aVfs /* = "" */) : mpSQLite(NULL), mFilename(aFilename) { const int ret = sqlite3_open_v2(aFilename.c_str(), &mpSQLite, aFlags, aVfs.empty() ? NULL : aVfs.c_str()); if (SQLITE_OK != ret) { std::string strerr = sqlite3_errmsg(mpSQLite); sqlite3_close(mpSQLite); // close is required even in case of error on opening throw SQLite::Exception(strerr); } if (aBusyTimeoutMs > 0) { setBusyTimeout(aBusyTimeoutMs); } } // Close the SQLite database connection. Database::~Database() noexcept // nothrow { const int ret = sqlite3_close(mpSQLite); // Only case of error is SQLITE_BUSY: "database is locked" (some statements are not finalized) // Never throw an exception in a destructor : SQLITECPP_ASSERT(SQLITE_OK == ret, "database is locked"); // See SQLITECPP_ENABLE_ASSERT_HANDLER } /** * @brief Set a busy handler that sleeps for a specified amount of time when a table is locked. * * This is usefull in multithreaded program to handle case where a table is locked for writting by a thread. * Any other thread cannot access the table and will receive a SQLITE_BUSY error: * setting a timeout will wait and retry up to the time specified before returning this SQLITE_BUSY error. * Reading the value of timeout for current connection can be done with SQL query "PRAGMA busy_timeout;". * Default busy timeout is 0ms. * * @param[in] aBusyTimeoutMs Amount of milliseconds to wait before returning SQLITE_BUSY * * @throw SQLite::Exception in case of error */ void Database::setBusyTimeout(const int aBusyTimeoutMs) noexcept // nothrow { const int ret = sqlite3_busy_timeout(mpSQLite, aBusyTimeoutMs); check(ret); } // Shortcut to execute one or multiple SQL statements without results (UPDATE, INSERT, ALTER, COMMIT, CREATE...). int Database::exec(const char* apQueries) { const int ret = sqlite3_exec(mpSQLite, apQueries, NULL, NULL, NULL); check(ret); // Return the number of rows modified by those SQL statements (INSERT, UPDATE or DELETE only) return sqlite3_changes(mpSQLite); } // Shortcut to execute a one step query and fetch the first column of the result. // WARNING: Be very careful with this dangerous method: you have to // make a COPY OF THE result, else it will be destroy before the next line // (when the underlying temporary Statement and Column objects are destroyed) // this is an issue only for pointer type result (ie. char* and blob) // (use the Column copy-constructor) Column Database::execAndGet(const char* apQuery) { Statement query(*this, apQuery); (void)query.executeStep(); // Can return false if no result, which will throw next line in getColumn() return query.getColumn(0); } // Shortcut to test if a table exists. bool Database::tableExists(const char* apTableName) { Statement query(*this, "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?"); query.bind(1, apTableName); (void)query.executeStep(); // Cannot return false, as the above query always return a result const int Nb = query.getColumn(0); return (1 == Nb); } // Attach a custom function to your sqlite database. Assumes UTF8 text representation. // Parameter details can be found here: http://www.sqlite.org/c3ref/create_function.html void Database::createFunction(const char* apFuncName, int aNbArg, bool abDeterministic, void* apApp, void (*apFunc)(sqlite3_context *, int, sqlite3_value **), void (*apStep)(sqlite3_context *, int, sqlite3_value **), void (*apFinal)(sqlite3_context *), // NOLINT(readability/casting) void (*apDestroy)(void *)) { int TextRep = SQLITE_UTF8; // optimization if deterministic function (e.g. of nondeterministic function random()) if (abDeterministic) { TextRep = TextRep|SQLITE_DETERMINISTIC; } const int ret = sqlite3_create_function_v2(mpSQLite, apFuncName, aNbArg, TextRep, apApp, apFunc, apStep, apFinal, apDestroy); check(ret); } // Load an extension into the sqlite database. Only affects the current connection. // Parameter details can be found here: http://www.sqlite.org/c3ref/load_extension.html void Database::loadExtension(const char* apExtensionName, const char *apEntryPointName) { #ifdef SQLITE_OMIT_LOAD_EXTENSION # throw std::runtime_error("sqlite extensions are disabled"); # #else # int ret = sqlite3_enable_load_extension(mpSQLite, 1); check(ret); ret = sqlite3_load_extension(mpSQLite, apExtensionName, apEntryPointName, 0); check(ret); # #endif } } // namespace SQLite <|endoftext|>
<commit_before>#include "main.h" #include "CNetwork.h" #include "CServer.h" #include "CUtils.h" #include "CCallback.h" #include <istream> #include <boost/date_time/posix_time/posix_time.hpp> #include "format.h" void CNetwork::NetAlive(const boost::system::error_code &error_code, bool from_write) { if (from_write == true) return; if (error_code.value() != 0) return; if (m_Socket.is_open()) { static string empty_data("\n"); m_Socket.async_send(asio::buffer(empty_data), boost::bind(&CNetwork::NetAlive, this, boost::asio::placeholders::error, true)); } m_AliveTimer.expires_from_now(boost::posix_time::seconds(60)); m_AliveTimer.async_wait( boost::bind(&CNetwork::NetAlive, this, boost::asio::placeholders::error, false)); } bool CNetwork::Connect(string hostname, unsigned short port, unsigned short query_port) { if (IsConnected()) return false; boost::system::error_code error; tcp::resolver resolver(m_IoService); tcp::resolver::query query(tcp::v4(), hostname, string()); tcp::resolver::iterator i = resolver.resolve(query, error); if (error) { CCallbackHandler::Get()->ForwardError( EErrorType::CONNECTION_ERROR, error.value(), fmt::format("error while resolving hostname \"{}\": {}", hostname, error.message())); return false; } m_SocketDest = *i; m_SocketDest.port(query_port); m_ServerPort = port; AsyncConnect(); m_IoThread = new thread(boost::bind(&asio::io_service::run, boost::ref(m_IoService))); return true; } bool CNetwork::Disconnect() { if (m_Socket.is_open() == false || m_Connected == false) return false; m_Connected = false; m_Socket.close(); m_AliveTimer.cancel(); m_IoService.stop(); if (m_IoThread != nullptr) { if (m_IoThread->get_id() != boost::this_thread::get_id()) m_IoThread->join(); delete m_IoThread; m_IoThread = nullptr; } return true; } void CNetwork::AsyncRead() { asio::async_read_until(m_Socket, m_ReadStreamBuf, '\r', boost::bind(&CNetwork::OnRead, this, _1)); } void CNetwork::AsyncWrite(string &data) { m_CmdWriteBuffer = data; if (data.at(data.length()-1) != '\n') m_CmdWriteBuffer.push_back('\n'); m_Socket.async_send(asio::buffer(m_CmdWriteBuffer), boost::bind(&CNetwork::OnWrite, this, _1)); } void CNetwork::AsyncConnect() { if (m_Socket.is_open()) m_Socket.close(); m_Connected = false; m_Socket.async_connect(m_SocketDest, boost::bind(&CNetwork::OnConnect, this, _1)); } void CNetwork::OnConnect(const boost::system::error_code &error_code) { if (error_code.value() == 0) { m_Connected = true; Execute(fmt::format("use port={}", m_ServerPort)); AsyncRead(); //start heartbeat check NetAlive(boost::system::error_code(), false); } else { CCallbackHandler::Get()->ForwardError( EErrorType::CONNECTION_ERROR, error_code.value(), fmt::format("error while connecting to server: {}", error_code.message())); Disconnect(); } } /* - result data is sent as a string which ends with "\n\r" - the Teamspeak3 server can send multiple strings - the end of a result set is always an error result string */ void CNetwork::OnRead(const boost::system::error_code &error_code) { if (error_code.value() == 0) { static vector<string> captured_data; std::istream tmp_stream(&m_ReadStreamBuf); string read_data; std::getline(tmp_stream, read_data, '\r'); #ifdef _DEBUG if (read_data.length() < 512) logprintf(">>>> %s", read_data.c_str()); else { string shortened_data(read_data); shortened_data.resize(256); logprintf(">>>> %s", shortened_data.c_str()); } #endif //regex: parse error //if this is an error message, it means that no other result data will come static const boost::regex error_rx("error id=([0-9]+) msg=([^ \n]+)"); boost::smatch error_rx_result; if (boost::regex_search(read_data, error_rx_result, error_rx)) { if (error_rx_result[1].str() == "0") { for (auto i = captured_data.begin(); i != captured_data.end(); ++i) { string &data = *i; if (data.find('|') == string::npos) continue; //we have multiple data rows with '|' as delimiter here, //split them up and re-insert every single row vector<string> result_set; size_t delim_pos = 0; do { size_t old_delim_pos = delim_pos; delim_pos = data.find('|', delim_pos); string row = data.substr(old_delim_pos, delim_pos - old_delim_pos); result_set.push_back(row); } while (delim_pos != string::npos && ++delim_pos); i = captured_data.erase(i); for (auto j = result_set.begin(), jend = result_set.end(); j != jend; ++j) i = captured_data.insert(i, *j); } //call callback and send next command m_CmdQueueMutex.lock(); if (m_CmdQueue.empty() == false) { ReadCallback_t &callback = m_CmdQueue.front().get<1>(); if (callback) { m_CmdQueueMutex.unlock(); callback(captured_data); //calls the callback m_CmdQueueMutex.lock(); } m_CmdQueue.pop(); if (m_CmdQueue.empty() == false) AsyncWrite(m_CmdQueue.front().get<0>()); } m_CmdQueueMutex.unlock(); } else { string error_str(error_rx_result[2].str()); unsigned int error_id = 0; CUtils::Get()->UnEscapeString(error_str); CUtils::Get()->ConvertStringToInt(error_rx_result[1].str(), error_id); m_CmdQueueMutex.lock(); CCallbackHandler::Get()->ForwardError( EErrorType::TEAMSPEAK_ERROR, error_id, fmt::format("error while executing \"{}\": {}", m_CmdQueue.front().get<0>(), error_str)); m_CmdQueue.pop(); if (m_CmdQueue.empty() == false) AsyncWrite(m_CmdQueue.front().get<0>()); m_CmdQueueMutex.unlock(); } captured_data.clear(); } else if (read_data.find("notify") == 0) { //check if notify is duplicate static string last_notify_data; static const vector<string> duplicate_notifies{ "notifyclientmoved", "notifycliententerview", "notifyclientleftview" }; bool is_duplicate = false; for (auto &s : duplicate_notifies) { if (read_data.find(s) == 0) { if (last_notify_data == read_data) is_duplicate = true; break; } } if (is_duplicate == false) { //notify event boost::smatch event_result; for (auto &event : m_EventList) { if (boost::regex_search(read_data, event_result, event.get<0>())) { event.get<1>()(event_result); break; } } } last_notify_data = read_data; } else { //stack the result data if it is not an error or notification message captured_data.push_back(read_data); } AsyncRead(); } else { CCallbackHandler::Get()->ForwardError( EErrorType::CONNECTION_ERROR, error_code.value(), fmt::format("error while reading: {}", error_code.message())); } } void CNetwork::OnWrite(const boost::system::error_code &error_code) { #ifdef _DEBUG logprintf("<<<< %s", m_CmdWriteBuffer.c_str()); #endif m_CmdWriteBuffer.clear(); if (error_code.value() != 0) { CCallbackHandler::Get()->ForwardError( EErrorType::CONNECTION_ERROR, error_code.value(), fmt::format("error while writing: {}", error_code.message())); } } void CNetwork::Execute(string cmd, ReadCallback_t callback) { boost::lock_guard<boost::mutex> queue_lock_guard(m_CmdQueueMutex); m_CmdQueue.push(boost::make_tuple(boost::move(cmd), boost::move(callback))); if (m_CmdQueue.size() == 1) AsyncWrite(m_CmdQueue.front().get<0>()); } <commit_msg>improve disconnecting mechanism<commit_after>#include "main.h" #include "CNetwork.h" #include "CServer.h" #include "CUtils.h" #include "CCallback.h" #include <istream> #include <boost/date_time/posix_time/posix_time.hpp> #include "format.h" void CNetwork::NetAlive(const boost::system::error_code &error_code, bool from_write) { if (from_write == true) return; if (error_code.value() != 0) return; if (m_Socket.is_open()) { static string empty_data("\n"); m_Socket.async_send(asio::buffer(empty_data), boost::bind(&CNetwork::NetAlive, this, boost::asio::placeholders::error, true)); } m_AliveTimer.expires_from_now(boost::posix_time::seconds(60)); m_AliveTimer.async_wait( boost::bind(&CNetwork::NetAlive, this, boost::asio::placeholders::error, false)); } bool CNetwork::Connect(string hostname, unsigned short port, unsigned short query_port) { if (IsConnected()) return false; boost::system::error_code error; tcp::resolver resolver(m_IoService); tcp::resolver::query query(tcp::v4(), hostname, string()); tcp::resolver::iterator i = resolver.resolve(query, error); if (error) { CCallbackHandler::Get()->ForwardError( EErrorType::CONNECTION_ERROR, error.value(), fmt::format("error while resolving hostname \"{}\": {}", hostname, error.message())); return false; } m_SocketDest = *i; m_SocketDest.port(query_port); m_ServerPort = port; AsyncConnect(); m_IoThread = new thread(boost::bind(&asio::io_service::run, boost::ref(m_IoService))); return true; } bool CNetwork::Disconnect() { if (IsConnected() == false) return false; Execute("quit", [this](ResultSet_t &res) { m_Connected = false; }); while (m_Connected == true) boost::this_thread::sleep_for(boost::chrono::milliseconds(20)); m_Socket.close(); m_AliveTimer.cancel(); m_IoService.stop(); if (m_IoThread != nullptr) { if (m_IoThread->get_id() != boost::this_thread::get_id()) m_IoThread->join(); delete m_IoThread; m_IoThread = nullptr; } return true; } void CNetwork::AsyncRead() { asio::async_read_until(m_Socket, m_ReadStreamBuf, '\r', boost::bind(&CNetwork::OnRead, this, _1)); } void CNetwork::AsyncWrite(string &data) { m_CmdWriteBuffer = data; if (data.at(data.length()-1) != '\n') m_CmdWriteBuffer.push_back('\n'); m_Socket.async_send(asio::buffer(m_CmdWriteBuffer), boost::bind(&CNetwork::OnWrite, this, _1)); } void CNetwork::AsyncConnect() { m_Connected = false; m_Socket.async_connect(m_SocketDest, boost::bind(&CNetwork::OnConnect, this, _1)); } void CNetwork::OnConnect(const boost::system::error_code &error_code) { if (error_code.value() == 0) { m_Connected = true; Execute(fmt::format("use port={}", m_ServerPort)); AsyncRead(); //start heartbeat check NetAlive(boost::system::error_code(), false); } else { CCallbackHandler::Get()->ForwardError( EErrorType::CONNECTION_ERROR, error_code.value(), fmt::format("error while connecting to server: {}", error_code.message())); Disconnect(); } } /* - result data is sent as a string which ends with "\n\r" - the Teamspeak3 server can send multiple strings - the end of a result set is always an error result string */ void CNetwork::OnRead(const boost::system::error_code &error_code) { if (error_code.value() == 0) { static vector<string> captured_data; std::istream tmp_stream(&m_ReadStreamBuf); string read_data; std::getline(tmp_stream, read_data, '\r'); #ifdef _DEBUG if (read_data.length() < 512) logprintf(">>>> %s", read_data.c_str()); else { string shortened_data(read_data); shortened_data.resize(256); logprintf(">>>> %s", shortened_data.c_str()); } #endif //regex: parse error //if this is an error message, it means that no other result data will come static const boost::regex error_rx("error id=([0-9]+) msg=([^ \n]+)"); boost::smatch error_rx_result; if (boost::regex_search(read_data, error_rx_result, error_rx)) { if (error_rx_result[1].str() == "0") { for (auto i = captured_data.begin(); i != captured_data.end(); ++i) { string &data = *i; if (data.find('|') == string::npos) continue; //we have multiple data rows with '|' as delimiter here, //split them up and re-insert every single row vector<string> result_set; size_t delim_pos = 0; do { size_t old_delim_pos = delim_pos; delim_pos = data.find('|', delim_pos); string row = data.substr(old_delim_pos, delim_pos - old_delim_pos); result_set.push_back(row); } while (delim_pos != string::npos && ++delim_pos); i = captured_data.erase(i); for (auto j = result_set.begin(), jend = result_set.end(); j != jend; ++j) i = captured_data.insert(i, *j); } //call callback and send next command m_CmdQueueMutex.lock(); if (m_CmdQueue.empty() == false) { ReadCallback_t &callback = m_CmdQueue.front().get<1>(); if (callback) { m_CmdQueueMutex.unlock(); callback(captured_data); //calls the callback m_CmdQueueMutex.lock(); } m_CmdQueue.pop(); if (m_CmdQueue.empty() == false) AsyncWrite(m_CmdQueue.front().get<0>()); } m_CmdQueueMutex.unlock(); } else { string error_str(error_rx_result[2].str()); unsigned int error_id = 0; CUtils::Get()->UnEscapeString(error_str); CUtils::Get()->ConvertStringToInt(error_rx_result[1].str(), error_id); m_CmdQueueMutex.lock(); CCallbackHandler::Get()->ForwardError( EErrorType::TEAMSPEAK_ERROR, error_id, fmt::format("error while executing \"{}\": {}", m_CmdQueue.front().get<0>(), error_str)); m_CmdQueue.pop(); if (m_CmdQueue.empty() == false) AsyncWrite(m_CmdQueue.front().get<0>()); m_CmdQueueMutex.unlock(); } captured_data.clear(); } else if (read_data.find("notify") == 0) { //check if notify is duplicate static string last_notify_data; static const vector<string> duplicate_notifies{ "notifyclientmoved", "notifycliententerview", "notifyclientleftview" }; bool is_duplicate = false; for (auto &s : duplicate_notifies) { if (read_data.find(s) == 0) { if (last_notify_data == read_data) is_duplicate = true; break; } } if (is_duplicate == false) { //notify event boost::smatch event_result; for (auto &event : m_EventList) { if (boost::regex_search(read_data, event_result, event.get<0>())) { event.get<1>()(event_result); break; } } } last_notify_data = read_data; } else { //stack the result data if it is not an error or notification message captured_data.push_back(read_data); } AsyncRead(); } else { if (IsConnected()) { CCallbackHandler::Get()->ForwardError( EErrorType::CONNECTION_ERROR, error_code.value(), fmt::format("error while reading: {}", error_code.message())); } } } void CNetwork::OnWrite(const boost::system::error_code &error_code) { #ifdef _DEBUG logprintf("<<<< %s", m_CmdWriteBuffer.c_str()); #endif m_CmdWriteBuffer.clear(); if (error_code.value() != 0) { CCallbackHandler::Get()->ForwardError( EErrorType::CONNECTION_ERROR, error_code.value(), fmt::format("error while writing: {}", error_code.message())); } } void CNetwork::Execute(string cmd, ReadCallback_t callback) { boost::lock_guard<boost::mutex> queue_lock_guard(m_CmdQueueMutex); m_CmdQueue.push(boost::make_tuple(boost::move(cmd), boost::move(callback))); if (m_CmdQueue.size() == 1) AsyncWrite(m_CmdQueue.front().get<0>()); } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <iostream> #include <cstdio> #include "Compiler.hpp" #include "Timer.hpp" #include "DebugTimer.hpp" #include "Options.hpp" #include "StringPool.hpp" #include "FunctionTable.hpp" #include "ast/SourceFile.hpp" //Annotators #include "DefaultValues.hpp" #include "ContextAnnotator.hpp" #include "FunctionsAnnotator.hpp" #include "VariablesAnnotator.hpp" //Checkers #include "StringChecker.hpp" #include "TypeChecker.hpp" //Visitors #include "DependenciesResolver.hpp" #include "OptimizationEngine.hpp" #include "TransformerEngine.hpp" #include "IntermediateCompiler.hpp" #include "WarningsEngine.hpp" #include "SemanticalException.hpp" #include "parser/SpiritParser.hpp" #include "AssemblyFileWriter.hpp" #include "il/IntermediateProgram.hpp" #ifdef DEBUG static const bool debug = true; #else static const bool debug = false; #endif #define TIMER_START(name) Timer name_timer; #define TIMER_END(name) if(debug){std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl;} using namespace eddic; int Compiler::compile(const std::string& file) { std::cout << "Compile " << file << std::endl; Timer timer; std::string output = options["output"].as<std::string>(); int code = 0; try { TIMER_START(parsing) SpiritParser parser; //The program to build ast::SourceFile program; //Parse the file into the program bool parsing = parser.parse(file, program); TIMER_END(parsing) if(parsing){ //Symbol tables FunctionTable functionTable; StringPool pool; //Read dependencies includeDependencies(program, parser); //Annotate the AST with more informations defineDefaultValues(program); defineContexts(program); //Transform the AST transform(program); //Annotate the AST defineVariables(program); defineFunctions(program, functionTable); //Static analysis checkStrings(program, pool); checkTypes(program); //Check for warnings checkForWarnings(program, functionTable); //Optimize the AST optimize(program, functionTable, pool); //Write Intermediate representation of the parse tree IntermediateProgram il; writeIL(program, pool, il); //Write assembly to file writeAsm(il, "output.asm"); //If it's necessary, assemble and link the assembly if(!options.count("assembly")){ execCommand("as --32 -o output.o output.asm"); execCommand("ld -m elf_i386 output.o -o " + output); //Remove temporary files remove("output.asm"); remove("output.o"); } } } catch (const SemanticalException& e) { std::cout << e.what() << std::endl; code = 1; } std::cout << "Compilation took " << timer.elapsed() << "s" << std::endl; return code; } void eddic::defineDefaultValues(ast::SourceFile& program){ DebugTimer<debug> timer("Annotate with default values"); DefaultValues values; values.fill(program); } void eddic::defineContexts(ast::SourceFile& program){ DebugTimer<debug> timer("Annotate contexts"); ContextAnnotator annotator; annotator.annotate(program); } void eddic::defineVariables(ast::SourceFile& program){ DebugTimer<debug> timer("Annotate variables"); VariablesAnnotator annotator; annotator.annotate(program); } void eddic::defineFunctions(ast::SourceFile& program, FunctionTable& functionTable){ DebugTimer<debug> timer("Annotate functions"); FunctionsAnnotator annotator; annotator.annotate(program, functionTable); } void eddic::checkStrings(ast::SourceFile& program, StringPool& pool){ DebugTimer<debug> timer("Strings checking"); StringChecker checker; checker.check(program, pool); } void eddic::checkTypes(ast::SourceFile& program){ DebugTimer<debug> timer("Types checking"); TypeChecker checker; checker.check(program); } void eddic::checkForWarnings(ast::SourceFile& program, FunctionTable& table){ DebugTimer<debug> timer("Check for warnings"); WarningsEngine engine; engine.check(program, table); } void eddic::transform(ast::SourceFile& program){ DebugTimer<debug> timer("Transformation"); TransformerEngine engine; engine.transform(program); } void eddic::optimize(ast::SourceFile& program, FunctionTable& functionTable, StringPool& pool){ DebugTimer<debug> timer("Optimization"); OptimizationEngine engine; engine.optimize(program, functionTable, pool); } void eddic::writeIL(ast::SourceFile& program, StringPool& pool, IntermediateProgram& intermediateProgram){ DebugTimer<debug> timer("Compile into intermediate level"); IntermediateCompiler compiler; compiler.compile(program, pool, intermediateProgram); } void eddic::writeAsm(IntermediateProgram& il, const std::string& file){ DebugTimer<debug> timer("Write assembly"); AssemblyFileWriter writer(file); il.writeAsm(writer); writer.write(); } void eddic::includeDependencies(ast::SourceFile& sourceFile, SpiritParser& parser){ DebugTimer<debug> timer("Resolve dependencies"); DependenciesResolver resolver(parser); resolver.resolve(sourceFile); } void eddic::execCommand(const std::string& command) { DebugTimer<debug> timer("Exec " + command); if(debug){ std::cout << "eddic : exec command : " << command << std::endl; } char buffer[1024]; FILE* stream = popen(command.c_str(), "r"); while (fgets(buffer, 1024, stream) != NULL) { std::cout << buffer; } pclose(stream); } void eddic::warn(const std::string& warning){ std::cout << "warning: " << warning << std::endl; } <commit_msg>Output a little information message if the message is 64bit<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <iostream> #include <cstdio> #include "Compiler.hpp" #include "Target.hpp" #include "Timer.hpp" #include "DebugTimer.hpp" #include "Options.hpp" #include "StringPool.hpp" #include "FunctionTable.hpp" #include "ast/SourceFile.hpp" //Annotators #include "DefaultValues.hpp" #include "ContextAnnotator.hpp" #include "FunctionsAnnotator.hpp" #include "VariablesAnnotator.hpp" //Checkers #include "StringChecker.hpp" #include "TypeChecker.hpp" //Visitors #include "DependenciesResolver.hpp" #include "OptimizationEngine.hpp" #include "TransformerEngine.hpp" #include "IntermediateCompiler.hpp" #include "WarningsEngine.hpp" #include "SemanticalException.hpp" #include "parser/SpiritParser.hpp" #include "AssemblyFileWriter.hpp" #include "il/IntermediateProgram.hpp" #ifdef DEBUG static const bool debug = true; #else static const bool debug = false; #endif #define TIMER_START(name) Timer name_timer; #define TIMER_END(name) if(debug){std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl;} using namespace eddic; int Compiler::compile(const std::string& file) { std::cout << "Compile " << file << std::endl; if(TargetDetermined && Target64){ std::cout << "Warning : Looks like you're running a 64 bit system. This compiler only outputs 32 bits assembly." << std::endl; } Timer timer; std::string output = options["output"].as<std::string>(); int code = 0; try { TIMER_START(parsing) SpiritParser parser; //The program to build ast::SourceFile program; //Parse the file into the program bool parsing = parser.parse(file, program); TIMER_END(parsing) if(parsing){ //Symbol tables FunctionTable functionTable; StringPool pool; //Read dependencies includeDependencies(program, parser); //Annotate the AST with more informations defineDefaultValues(program); defineContexts(program); //Transform the AST transform(program); //Annotate the AST defineVariables(program); defineFunctions(program, functionTable); //Static analysis checkStrings(program, pool); checkTypes(program); //Check for warnings checkForWarnings(program, functionTable); //Optimize the AST optimize(program, functionTable, pool); //Write Intermediate representation of the parse tree IntermediateProgram il; writeIL(program, pool, il); //Write assembly to file writeAsm(il, "output.asm"); //If it's necessary, assemble and link the assembly if(!options.count("assembly")){ execCommand("as --32 -o output.o output.asm"); execCommand("ld -m elf_i386 output.o -o " + output); //Remove temporary files remove("output.asm"); remove("output.o"); } } } catch (const SemanticalException& e) { std::cout << e.what() << std::endl; code = 1; } std::cout << "Compilation took " << timer.elapsed() << "s" << std::endl; return code; } void eddic::defineDefaultValues(ast::SourceFile& program){ DebugTimer<debug> timer("Annotate with default values"); DefaultValues values; values.fill(program); } void eddic::defineContexts(ast::SourceFile& program){ DebugTimer<debug> timer("Annotate contexts"); ContextAnnotator annotator; annotator.annotate(program); } void eddic::defineVariables(ast::SourceFile& program){ DebugTimer<debug> timer("Annotate variables"); VariablesAnnotator annotator; annotator.annotate(program); } void eddic::defineFunctions(ast::SourceFile& program, FunctionTable& functionTable){ DebugTimer<debug> timer("Annotate functions"); FunctionsAnnotator annotator; annotator.annotate(program, functionTable); } void eddic::checkStrings(ast::SourceFile& program, StringPool& pool){ DebugTimer<debug> timer("Strings checking"); StringChecker checker; checker.check(program, pool); } void eddic::checkTypes(ast::SourceFile& program){ DebugTimer<debug> timer("Types checking"); TypeChecker checker; checker.check(program); } void eddic::checkForWarnings(ast::SourceFile& program, FunctionTable& table){ DebugTimer<debug> timer("Check for warnings"); WarningsEngine engine; engine.check(program, table); } void eddic::transform(ast::SourceFile& program){ DebugTimer<debug> timer("Transformation"); TransformerEngine engine; engine.transform(program); } void eddic::optimize(ast::SourceFile& program, FunctionTable& functionTable, StringPool& pool){ DebugTimer<debug> timer("Optimization"); OptimizationEngine engine; engine.optimize(program, functionTable, pool); } void eddic::writeIL(ast::SourceFile& program, StringPool& pool, IntermediateProgram& intermediateProgram){ DebugTimer<debug> timer("Compile into intermediate level"); IntermediateCompiler compiler; compiler.compile(program, pool, intermediateProgram); } void eddic::writeAsm(IntermediateProgram& il, const std::string& file){ DebugTimer<debug> timer("Write assembly"); AssemblyFileWriter writer(file); il.writeAsm(writer); writer.write(); } void eddic::includeDependencies(ast::SourceFile& sourceFile, SpiritParser& parser){ DebugTimer<debug> timer("Resolve dependencies"); DependenciesResolver resolver(parser); resolver.resolve(sourceFile); } void eddic::execCommand(const std::string& command) { DebugTimer<debug> timer("Exec " + command); if(debug){ std::cout << "eddic : exec command : " << command << std::endl; } char buffer[1024]; FILE* stream = popen(command.c_str(), "r"); while (fgets(buffer, 1024, stream) != NULL) { std::cout << buffer; } pclose(stream); } void eddic::warn(const std::string& warning){ std::cout << "warning: " << warning << std::endl; } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <fstream> #include <commons/ByteCode.h> #include <commons/Timer.h> #include "Compiler.h" #include "Lexer.h" #include <unistd.h> using namespace std; int Compiler::compile(string file){ cout << "Compile " << file << endl; Timer timer; ifstream inFile; inFile.open(file.c_str()); if(!inFile){ cout << "Unable to open " << file << endl; return 1; } ofstream outFile; outFile.open("main.v", ios::binary); int code = compile(&inFile, &outFile); inFile.close(); outFile.close(); cout << "Compilation took " << timer.elapsed() << "ms" << endl; return code; } int Compiler::compile(ifstream* inStream, ofstream* outStream){ Lexer lexer(inStream); while(lexer.next()){ if(!lexer.isCall()){ cout << "An instruction can only start with a call" << endl; return 1; } string call = lexer.getCurrentToken(); if(call != "PRINT"){ cout << "The call \"" << call << "\" does not exist" << endl; return 1; } if(!lexer.next() || !lexer.isLeftParenth()){ cout << "A call must be followed by a left parenth" << endl; return 1; } if(!lexer.next()){ cout << "Not enough arguments to the call" << endl; return 1; } if(!lexer.isLitteral()){ cout << "Can only pass litteral to a call" << endl; return 1; } string litteral = lexer.getCurrentToken(); if(!lexer.next()){ cout << "The call must be closed with a right parenth" << endl; return 1; } if(!lexer.isRightParenth()){ cout << "The call must be closed with a right parenth" << endl; return 1; } if(!lexer.next()){ cout << "Every instruction must be closed by ;" << endl; return 1; } if(!lexer.isStop()){ cout << "Every instruction must be closed by ;" << endl; return 1; } writeOneOperandCall(outStream, PUSH, litteral); writeSimpleCall(outStream, PRINT); } return 0; } <commit_msg>Little improvements in conditions<commit_after>#include <iostream> #include <iomanip> #include <fstream> #include <commons/ByteCode.h> #include <commons/Timer.h> #include "Compiler.h" #include "Lexer.h" #include <unistd.h> using namespace std; int Compiler::compile(string file){ cout << "Compile " << file << endl; Timer timer; ifstream inFile; inFile.open(file.c_str()); if(!inFile){ cout << "Unable to open " << file << endl; return 1; } ofstream outFile; outFile.open("main.v", ios::binary); int code = compile(&inFile, &outFile); inFile.close(); outFile.close(); cout << "Compilation took " << timer.elapsed() << "ms" << endl; return code; } int Compiler::compile(ifstream* inStream, ofstream* outStream){ Lexer lexer(inStream); while(lexer.next()){ if(!lexer.isCall()){ cout << "An instruction can only start with a call" << endl; return 1; } string call = lexer.getCurrentToken(); if(call != "PRINT"){ cout << "The call \"" << call << "\" does not exist" << endl; return 1; } if(!lexer.next() || !lexer.isLeftParenth()){ cout << "A call must be followed by a left parenth" << endl; return 1; } if(!lexer.next()){ cout << "Not enough arguments to the call" << endl; return 1; } if(!lexer.isLitteral()){ cout << "Can only pass litteral to a call" << endl; return 1; } string litteral = lexer.getCurrentToken(); if(!lexer.next() || !lexer.isRightParenth()){ cout << "The call must be closed with a right parenth" << endl; return 1; } if(!lexer.next() || !lexer.isStop()){ cout << "Every instruction must be closed by ;" << endl; return 1; } writeOneOperandCall(outStream, PUSH, litteral); writeSimpleCall(outStream, PRINT); } return 0; } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #define DEBUG #ifdef DEBUG static const bool debug = true; #else static const bool debug = false; #endif #define TIMER_START(name) Timer name_timer; #define TIMER_END(name) std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl; #include <iostream> #include <cstdio> #include "Compiler.hpp" #include "Timer.hpp" #include "DebugTimer.hpp" #include "Options.hpp" #include "StringPool.hpp" #include "FunctionTable.hpp" #include "ast/Program.hpp" #include "AssemblyFileWriter.hpp" #include "ContextAnnotator.hpp" #include "VariableChecker.hpp" #include "StringChecker.hpp" #include "FunctionChecker.hpp" #include "OptimizationEngine.hpp" #include "IntermediateCompiler.hpp" #include "SemanticalException.hpp" #include "parser/SpiritParser.hpp" #include "il/IntermediateProgram.hpp" using std::string; using std::cout; using std::endl; using namespace eddic; int Compiler::compile(const string& file) { cout << "Compile " << file << endl; Timer timer; string output = Options::get(ValueOption::OUTPUT); int code = 0; try { TIMER_START(parsing) SpiritParser parser; //The program to build ASTProgram program; //Parse the file into the program bool parsing = parser.parse(file, program); TIMER_END(parsing) if(parsing){ defineContexts(program); StringPool pool; FunctionTable functionTable; //Semantical analysis checkVariables(program); checkStrings(program, pool); checkFunctions(program, functionTable); //Optimize the AST optimize(program); //Write Intermediate representation of the parse tree IntermediateProgram il; writeIL(program, pool, il); AssemblyFileWriter writer("output.asm"); //Write assembly code il.writeAsm(writer); if(!Options::isSet(BooleanOption::ASSEMBLY_ONLY)){ execCommand("as --32 -o output.o output.asm"); string ldCommand = "gcc -m32 -static -o "; ldCommand += output; ldCommand += " output.o -lc"; execCommand(ldCommand); //Remove temporary files remove("output.asm"); remove("output.o"); } } } catch (const SemanticalException& e) { cout << e.what() << endl; code = 1; } cout << "Compilation took " << timer.elapsed() << "s" << endl; return code; } void eddic::defineContexts(ASTProgram& program){ DebugTimer<debug> timer("Annotate contexts"); ContextAnnotator annotator; annotator.annotate(program); } void eddic::checkVariables(ASTProgram& program){ DebugTimer<debug> timer("Variable checking"); VariableChecker checker; checker.check(program); } void eddic::checkStrings(ASTProgram& program, StringPool& pool){ DebugTimer<debug> timer("Strings checking"); StringChecker checker; checker.check(program, pool); } void eddic::checkFunctions(ASTProgram& program, FunctionTable& functionTable){ DebugTimer<debug> timer("Functions checking"); FunctionChecker checker; checker.check(program, functionTable); } void eddic::optimize(ASTProgram& program){ DebugTimer<debug> timer("Optimization"); OptimizationEngine engine; engine.optimize(program); } void eddic::writeIL(ASTProgram& program, StringPool& pool, IntermediateProgram& intermediateProgram){ DebugTimer<debug> timer("Compile into intermediate level"); IntermediateCompiler compiler; compiler.compile(program, pool, intermediateProgram); } void eddic::execCommand(const string& command) { cout << "eddic : exec command : " << command << endl; char buffer[1024]; FILE* stream = popen(command.c_str(), "r"); while (fgets(buffer, 1024, stream) != NULL) { cout << buffer; } pclose(stream); } <commit_msg>Debug compiler<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #define DEBUG #ifdef DEBUG static const bool debug = true; #else static const bool debug = false; #endif #define TIMER_START(name) Timer name_timer; #define TIMER_END(name) std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl; #include <iostream> #include <cstdio> #include "Compiler.hpp" #include "Timer.hpp" #include "DebugTimer.hpp" #include "Options.hpp" #include "StringPool.hpp" #include "FunctionTable.hpp" #include "ast/Program.hpp" #include "AssemblyFileWriter.hpp" #include "ContextAnnotator.hpp" #include "VariableChecker.hpp" #include "StringChecker.hpp" #include "FunctionChecker.hpp" #include "OptimizationEngine.hpp" #include "IntermediateCompiler.hpp" #include "SemanticalException.hpp" #include "parser/SpiritParser.hpp" #include "il/IntermediateProgram.hpp" using std::string; using std::cout; using std::endl; using namespace eddic; int Compiler::compile(const string& file) { cout << "Compile " << file << endl; Timer timer; string output = Options::get(ValueOption::OUTPUT); int code = 0; try { TIMER_START(parsing) SpiritParser parser; //The program to build ASTProgram program; //Parse the file into the program bool parsing = parser.parse(file, program); TIMER_END(parsing) if(parsing){ defineContexts(program); StringPool pool; FunctionTable functionTable; //Semantical analysis checkVariables(program); checkStrings(program, pool); checkFunctions(program, functionTable); //Optimize the AST optimize(program); //Write Intermediate representation of the parse tree IntermediateProgram il; writeIL(program, pool, il); AssemblyFileWriter writer("output.asm"); //Write assembly code il.writeAsm(writer); if(!Options::isSet(BooleanOption::ASSEMBLY_ONLY)){ execCommand("as --32 -o output.o output.asm"); string ldCommand = "gcc -m32 -static -o "; ldCommand += output; ldCommand += " output.o -lc"; execCommand(ldCommand); //Remove temporary files remove("output.asm"); remove("output.o"); } } } catch (const SemanticalException& e) { cout << e.what() << endl; code = 1; } cout << "Compilation took " << timer.elapsed() << "s" << endl; return code; } void eddic::defineContexts(ASTProgram& program){ DebugTimer<debug> timer("Annotate contexts"); ContextAnnotator annotator; annotator.annotate(program); } void eddic::checkVariables(ASTProgram& program){ DebugTimer<debug> timer("Variable checking"); VariableChecker checker; checker.check(program); } void eddic::checkStrings(ASTProgram& program, StringPool& pool){ DebugTimer<debug> timer("Strings checking"); StringChecker checker; checker.check(program, pool); } void eddic::checkFunctions(ASTProgram& program, FunctionTable& functionTable){ DebugTimer<debug> timer("Functions checking"); FunctionChecker checker; checker.check(program, functionTable); } void eddic::optimize(ASTProgram& program){ DebugTimer<debug> timer("Optimization"); OptimizationEngine engine; engine.optimize(program); } void eddic::writeIL(ASTProgram& program, StringPool& pool, IntermediateProgram& intermediateProgram){ DebugTimer<debug> timer("Compile into intermediate level"); IntermediateCompiler compiler; compiler.compile(program, pool, intermediateProgram); } void eddic::execCommand(const string& command) { DebugTimer<debug> timer("Exec " + command); cout << "eddic : exec command : " << command << endl; char buffer[1024]; FILE* stream = popen(command.c_str(), "r"); while (fgets(buffer, 1024, stream) != NULL) { cout << buffer; } pclose(stream); } <|endoftext|>
<commit_before>// -*- mode: c++ , coding: utf-8 -*- /** * tbrpg – Text based roll playing game * * Copyright © 2012, 2013 Mattias Andrée ([email protected]) * * 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. * * 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/>. */ #include "Container.hpp" /** * Text based roll playing game * * DD2387 Program construction with C++ * Laboration 3 * * @author Mattias Andrée <[email protected]> */ namespace tbrpg { /** * Constructor */ Container::Container() : Item() { this->class_inheritance.push_back(30); this->name = "container"; this->contains = {}; this->can_contain = {}; this->contain_limit = 50; this->weight_modifier = 1; this->weight = 1000; this->unit_value = 33333; } /** * Copy constructor * * @param original The object to clone */ Container::Container(const Container& original) : Item(original) { this->contains = original.contains; this->contain_limit = original.contain_limit; this->weight_modifier = original.weight_modifier; this->can_contain = original.can_contain; } /** * Copy constructor * * @param original The object to clone */ Container::Container(Container& original) : Item(original) { this->contains = original.contains; this->contain_limit = original.contain_limit; this->weight_modifier = original.weight_modifier; this->can_contain = original.can_contain; } /** * Move constructor * * @param original The object to clone */ Container::Container(Container&& original) : Item(original) { std::swap(this->contains, original.contains); std::swap(this->contain_limit, original.contain_limit); std::swap(this->weight_modifier, original.weight_modifier); std::swap(this->can_contain, original.can_contain); } /** * Fork the object * * @return A fork of the object */ Object* Container::fork() const { return (Object*)(new Container(*this)); } /** * Destructor */ Container::~Container() { // do nothing } /** * Assignment operator * * @param original The reference object * @return The invoked object */ Container& Container::operator =(const Container& original) { Item::__copy__((Item&)*this, (Item&)original); this->contains = original.contains; this->contain_limit = original.contain_limit; this->weight_modifier = original.weight_modifier; this->can_contain = original.can_contain; return *this; } /** * Assignment operator * * @param original The reference object * @return The invoked object */ Container& Container::operator =(Container& original) { Item::__copy__((Item&)*this, (Item&)original); this->contains = original.contains; this->contain_limit = original.contain_limit; this->weight_modifier = original.weight_modifier; this->can_contain = original.can_contain; return *this; } /** * Move operator * * @param original The moved object, its resourced will be moved * @return The invoked object */ Container& Container::operator =(Container&& original) { std::swap((Item&)*this, (Item&)original); std::swap(this->contains, original.contains); std::swap(this->contain_limit, original.contain_limit); std::swap(this->weight_modifier, original.weight_modifier); std::swap(this->can_contain, original.can_contain); return *this; } /** * Equality evaluator * * @param other The other comparand * @return Whether the instances are equal */ bool Container::operator ==(const Container& other) const { if ((Item&)(*this) != (Item&)other) return false; if (this->contains != other.contains) return false; if (this->contain_limit != other.contain_limit) return false; if (this->weight_modifier != other.weight_modifier) return false; if (this->can_contain != other.can_contain) return false; return true; } /** * Inequality evaluator * * @param other The other comparand * @return Whether the instances are not equal */ bool Container::operator !=(const Container& other) const { return (*this == other) == false; } /** * Check whether the container can hold an item * * @param item The item to add * @param remove Item to remove * @return Whether the container can hold the item */ bool Container::canHold(Item* item, Item* remove) const { int itemcount = item->quantity; if ((remove)) itemcount -= remove->quantity; for (Item* elem : this->contains) itemcount += elem->quantity; if (itemcount > this->contain_limit) return false; if (this->can_contain.size() == 0) return true; for (const Item& elem : this->can_contain) if (*item >= elem) return true; return false; } /** * Copy method * * @param self The object to modify * @param original The reference object */ void Container::__copy__(Container& self, const Container& original) { self = original; } /** * Hash method * * @return The object's hash code */ size_t Container::hash() const { size_t rc = 0; rc = (rc * 3) ^ ((rc >> (sizeof(size_t) << 2)) * 3); rc += std::hash<Item>()(*this); rc = (rc * 5) ^ ((rc >> (sizeof(size_t) << 2)) * 5); rc += std::hash<std::vector<Item*>>()(this->contains); rc = (rc * 7) ^ ((rc >> (sizeof(size_t) << 2)) * 7); rc += std::hash<int>()(this->contain_limit); rc = (rc * 9) ^ ((rc >> (sizeof(size_t) << 2)) * 9); rc += std::hash<float>()(this->weight_modifier); rc = (rc * 11) ^ ((rc >> (sizeof(size_t) << 2)) * 11); rc += std::hash<std::vector<Item>>()(this->can_contain); return rc; } } <commit_msg>containers can not contain other containers (unless you make a new class and override this), this also implies that items cannot contain themself and vanish into the void<commit_after>// -*- mode: c++ , coding: utf-8 -*- /** * tbrpg – Text based roll playing game * * Copyright © 2012, 2013 Mattias Andrée ([email protected]) * * 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. * * 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/>. */ #include "Container.hpp" /** * Text based roll playing game * * DD2387 Program construction with C++ * Laboration 3 * * @author Mattias Andrée <[email protected]> */ namespace tbrpg { /** * Constructor */ Container::Container() : Item() { this->class_inheritance.push_back(30); this->name = "container"; this->contains = {}; this->can_contain = {}; this->contain_limit = 50; this->weight_modifier = 1; this->weight = 1000; this->unit_value = 33333; } /** * Copy constructor * * @param original The object to clone */ Container::Container(const Container& original) : Item(original) { this->contains = original.contains; this->contain_limit = original.contain_limit; this->weight_modifier = original.weight_modifier; this->can_contain = original.can_contain; } /** * Copy constructor * * @param original The object to clone */ Container::Container(Container& original) : Item(original) { this->contains = original.contains; this->contain_limit = original.contain_limit; this->weight_modifier = original.weight_modifier; this->can_contain = original.can_contain; } /** * Move constructor * * @param original The object to clone */ Container::Container(Container&& original) : Item(original) { std::swap(this->contains, original.contains); std::swap(this->contain_limit, original.contain_limit); std::swap(this->weight_modifier, original.weight_modifier); std::swap(this->can_contain, original.can_contain); } /** * Fork the object * * @return A fork of the object */ Object* Container::fork() const { return (Object*)(new Container(*this)); } /** * Destructor */ Container::~Container() { // do nothing } /** * Assignment operator * * @param original The reference object * @return The invoked object */ Container& Container::operator =(const Container& original) { Item::__copy__((Item&)*this, (Item&)original); this->contains = original.contains; this->contain_limit = original.contain_limit; this->weight_modifier = original.weight_modifier; this->can_contain = original.can_contain; return *this; } /** * Assignment operator * * @param original The reference object * @return The invoked object */ Container& Container::operator =(Container& original) { Item::__copy__((Item&)*this, (Item&)original); this->contains = original.contains; this->contain_limit = original.contain_limit; this->weight_modifier = original.weight_modifier; this->can_contain = original.can_contain; return *this; } /** * Move operator * * @param original The moved object, its resourced will be moved * @return The invoked object */ Container& Container::operator =(Container&& original) { std::swap((Item&)*this, (Item&)original); std::swap(this->contains, original.contains); std::swap(this->contain_limit, original.contain_limit); std::swap(this->weight_modifier, original.weight_modifier); std::swap(this->can_contain, original.can_contain); return *this; } /** * Equality evaluator * * @param other The other comparand * @return Whether the instances are equal */ bool Container::operator ==(const Container& other) const { if ((Item&)(*this) != (Item&)other) return false; if (this->contains != other.contains) return false; if (this->contain_limit != other.contain_limit) return false; if (this->weight_modifier != other.weight_modifier) return false; if (this->can_contain != other.can_contain) return false; return true; } /** * Inequality evaluator * * @param other The other comparand * @return Whether the instances are not equal */ bool Container::operator !=(const Container& other) const { return (*this == other) == false; } /** * Check whether the container can hold an item * * @param item The item to add * @param remove Item to remove * @return Whether the container can hold the item */ bool Container::canHold(Item* item, Item* remove) const { if (*item >= PROTOTYPE(Container)) return false; int itemcount = item->quantity; if ((remove)) itemcount -= remove->quantity; for (Item* elem : this->contains) itemcount += elem->quantity; if (itemcount > this->contain_limit) return false; if (this->can_contain.size() == 0) return true; for (const Item& elem : this->can_contain) if (*item >= elem) return true; return false; } /** * Copy method * * @param self The object to modify * @param original The reference object */ void Container::__copy__(Container& self, const Container& original) { self = original; } /** * Hash method * * @return The object's hash code */ size_t Container::hash() const { size_t rc = 0; rc = (rc * 3) ^ ((rc >> (sizeof(size_t) << 2)) * 3); rc += std::hash<Item>()(*this); rc = (rc * 5) ^ ((rc >> (sizeof(size_t) << 2)) * 5); rc += std::hash<std::vector<Item*>>()(this->contains); rc = (rc * 7) ^ ((rc >> (sizeof(size_t) << 2)) * 7); rc += std::hash<int>()(this->contain_limit); rc = (rc * 9) ^ ((rc >> (sizeof(size_t) << 2)) * 9); rc += std::hash<float>()(this->weight_modifier); rc = (rc * 11) ^ ((rc >> (sizeof(size_t) << 2)) * 11); rc += std::hash<std::vector<Item>>()(this->can_contain); return rc; } } <|endoftext|>
<commit_before>// // Copyright 2015 Google 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 "Firebase.h" using std::unique_ptr; using std::shared_ptr; namespace { std::string makeFirebaseURL(const std::string& path, const std::string& auth) { std::string url; if (path[0] != '/') { url = "/"; } url += path + ".json"; if (auth.length() > 0) { url += "?auth=" + auth; } return url; } } // namespace Firebase::Firebase(const std::string& host, const std::string& auth) : host_(host), auth_(auth) { http_.reset(FirebaseHttpClient::create()); http_->setReuseConnection(true); } const std::string& Firebase::auth() const { return auth_; } void FirebaseCall::analyzeError(char* method, int status, const std::string& path_with_auth) { if (status != 200) { error_ = FirebaseError(status, std::string(method) + " " + path_with_auth + ": " + http_->errorToString(status)); } } FirebaseCall::~FirebaseCall() { http_->end(); } const JsonObject& FirebaseCall::json() { //TODO(edcoyne): This is not efficient, we should do something smarter with //the buffers. kotl: Is this still valid? if (buffer_.get() == NULL) { buffer_.reset(new StaticJsonBuffer<FIREBASE_JSONBUFFER_SIZE>()); } return buffer_.get()->parseObject(response().c_str()); } // FirebaseRequest int FirebaseRequest::sendRequest( const std::string& host, const std::string& auth, char* method, const std::string& path, const std::string& data) { std::string path_with_auth = makeFirebaseURL(path, auth); http_->setReuseConnection(true); http_->begin(host, path_with_auth); int status = http_->sendRequest(method, data); analyzeError(method, status, path_with_auth); response_ = http_->getString(); } // FirebaseStream void FirebaseStream::startStreaming(const std::string& host, const std::string& auth, const std::string& path) { std::string path_with_auth = makeFirebaseURL(path, auth); http_->setReuseConnection(true); http_->begin(host, path_with_auth); http_->addHeader("Accept", "text/event-stream"); const char* headers[] = {"Location"}; http_->collectHeaders(headers, 1); int status = http_->sendRequest("GET", ""); analyzeError("STREAM", status, path_with_auth); while (status == HttpStatus::TEMPORARY_REDIRECT) { std::string location = http_->header("Location"); http_->setReuseConnection(false); http_->end(); http_->setReuseConnection(true); http_->begin(location); status = http_->sendRequest("GET", std::string()); } } <commit_msg>Fix issue #388 ESP8266 fails to reconnect to FIREBASE #388 https://github.com/FirebaseExtended/firebase-arduino/issues/388<commit_after>// // Copyright 2015 Google 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 "Firebase.h" using std::unique_ptr; using std::shared_ptr; namespace { std::string makeFirebaseURL(const std::string& path, const std::string& auth) { std::string url; if (path[0] != '/') { url = "/"; } url += path + ".json"; if (auth.length() > 0) { url += "?auth=" + auth; } return url; } } // namespace Firebase::Firebase(const std::string& host, const std::string& auth) : host_(host), auth_(auth) { http_.reset(FirebaseHttpClient::create()); http_->setReuseConnection(true); } const std::string& Firebase::auth() const { return auth_; } void FirebaseCall::analyzeError(char* method, int status, const std::string& path_with_auth) { if (status != 200) { error_ = FirebaseError(status, std::string(method) + " " + path_with_auth + ": " + http_->errorToString(status)); } else { error_ = FirebaseError(); } } FirebaseCall::~FirebaseCall() { http_->end(); } const JsonObject& FirebaseCall::json() { //TODO(edcoyne): This is not efficient, we should do something smarter with //the buffers. kotl: Is this still valid? if (buffer_.get() == NULL) { buffer_.reset(new StaticJsonBuffer<FIREBASE_JSONBUFFER_SIZE>()); } return buffer_.get()->parseObject(response().c_str()); } // FirebaseRequest int FirebaseRequest::sendRequest( const std::string& host, const std::string& auth, char* method, const std::string& path, const std::string& data) { std::string path_with_auth = makeFirebaseURL(path, auth); http_->setReuseConnection(true); http_->begin(host, path_with_auth); int status = http_->sendRequest(method, data); analyzeError(method, status, path_with_auth); response_ = http_->getString(); } // FirebaseStream void FirebaseStream::startStreaming(const std::string& host, const std::string& auth, const std::string& path) { std::string path_with_auth = makeFirebaseURL(path, auth); http_->setReuseConnection(true); http_->begin(host, path_with_auth); http_->addHeader("Accept", "text/event-stream"); const char* headers[] = {"Location"}; http_->collectHeaders(headers, 1); int status = http_->sendRequest("GET", ""); analyzeError("STREAM", status, path_with_auth); while (status == HttpStatus::TEMPORARY_REDIRECT) { std::string location = http_->header("Location"); http_->setReuseConnection(false); http_->end(); http_->setReuseConnection(true); http_->begin(location); status = http_->sendRequest("GET", std::string()); } } <|endoftext|>
<commit_before>#include "Document.h" #include "private/Document_p.h" #include <QtCore/QCoreApplication> #include <QtDebug> using namespace arangodb; Document::Document(QObject *parent) : QObject(parent), d_ptr(new internal::DocumentPrivate) { } Document::Document(internal::DocumentPrivate *privatePointer, QObject *parent) : QObject(parent), d_ptr(privatePointer) { } Document::Document(internal::DocumentPrivate *privatePointer, QString collection, QObject *parent) : Document(privatePointer, parent) { d_func()->collectionName = collection; } Document::Document(QString collection, QObject *parent) : Document(new internal::DocumentPrivate, collection, parent) { } Document::Document(QString collection, QString key, QObject *parent) : Document(collection, parent) { set(internal::KEY, key); } Document::Document(QJsonObject obj, QObject * parent) : Document(new internal::DocumentPrivate, parent) { obj.remove(QStringLiteral("n")); d_func()->collectionName = obj.value(internal::ID).toString().split('/').at(0); d_func()->data.insert(internal::ID, obj.value(internal::ID)); d_func()->data.insert(internal::KEY, obj.value(internal::KEY)); d_func()->data.insert(internal::REV, obj.value(internal::REV)); } Document::~Document() { delete d_ptr; } bool Document::isReady() { return d_func()->isReady; } bool Document::isCreated() { return d_func()->isCreated; } bool Document::isCurrent() { return d_func()->isCurrent; } QByteArray Document::toJsonString() const { QJsonDocument doc; if ( !isEveryAttributeDirty() ) { QJsonObject obj; obj.insert(internal::ID, obj.value(internal::ID)); obj.insert(internal::KEY, obj.value(internal::KEY)); obj.insert(internal::REV, obj.value(internal::REV)); for( QString attribute : d_func()->dirtyAttributes ) { obj.insert(attribute, d_func()->data[attribute]); } doc.setObject(obj); } else { doc.setObject(d_func()->data); } return doc.toJson(); } QString Document::docID() const { return d_func()->data.value(internal::ID).toString(); } QString Document::key() const { return d_func()->data.value(internal::KEY).toString(); } QString Document::rev() const { return d_func()->data.value(internal::REV).toString(); } QString Document::collection() const { return d_func()->collectionName; } QString Document::errorMessage() const { return d_func()->errorMessage; } quint32 Document::errorCode() { return d_func()->errorCode; } quint32 Document::errorNumber() { return d_func()->errorNumber; } bool Document::hasErrorOccurred() { return d_func()->errorCode != 0; } void Document::set(const QString &key, QVariant data) { d_func()->dirtyAttributes.append(key); d_func()->data.insert(key, QJsonValue::fromVariant(data)); d_func()->isDirty = true; } QVariant Document::get(const QString &key) const { return d_func()->data.value(key).toVariant(); } bool Document::contains(const QString & key) const { return d_func()->data.contains(key); } QStringList Document::dirtyAttributes() const { return d_func()->dirtyAttributes; } bool Document::isEveryAttributeDirty() const { int attributes = d_func()->data.keys().size()-3; if ( d_func()->data.contains("error") ) { attributes--; } return d_func()->dirtyAttributes.size() >= attributes; } void Document::waitForResult() { bool b = true; QMetaObject::Connection conn1 = QObject::connect(this, &Document::ready, [&] { b = false; }); QMetaObject::Connection conn2 = QObject::connect(this, &Document::error, [&] { b = false; }); while (b) { qApp->processEvents(); } QObject::disconnect(conn1); QObject::disconnect(conn2); } void Document::_ar_dataIsAvailable() { QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); QJsonObject obj = QJsonDocument::fromJson(reply->readAll()).object(); d_func()->dirtyAttributes.clear(); reply->disconnect(this, SLOT(_ar_dataIsAvailable())); bool hasError = obj.value("error").toBool(); if ( hasError ) { d_func()->errorMessage = obj.value("errorMessage").toString(); d_func()->errorNumber = obj.value("errorNum").toVariant().toInt(); d_func()->errorCode = obj.value("code").toVariant().toInt(); emit error(); } else { d_func()->isReady = true; d_func()->isCreated = true; d_func()->isCurrent = true; for ( auto key : obj.keys() ) { d_func()->data.insert(key, obj[key]); } d_func()->resetError(); emit ready(); } } void Document::_ar_dataDeleted() { emit dataDeleted(); } void Document::_ar_dataUpdated() { QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); d_func()->isReady = true; if (reply->hasRawHeader("etag") ) { QByteArray etag = reply->rawHeader("etag"); etag.replace('"', ""); // comes from the rawHeader d_func()->isCreated = true; d_func()->isCurrent = ( etag == rev() ); } else { d_func()->isCreated = false; d_func()->isCurrent = false; } emit ready(); } void Document::save() { if ( !d_func()->isCreated || d_func()->isDirty ) { d_func()->isDirty = false; emit saveData(this); } } void Document::sync() { if ( !d_func()->isCurrent ) { emit syncData(this); } } void Document::drop() { if ( d_func()->isCreated ) { d_func()->isDirty = false; d_func()->isCreated = false; emit deleteData(this); } } void Document::updateStatus() { emit updateDataStatus(this); } <commit_msg>When a document object is created by a QJSonObject it is not current<commit_after>#include "Document.h" #include "private/Document_p.h" #include <QtCore/QCoreApplication> #include <QtDebug> using namespace arangodb; Document::Document(QObject *parent) : QObject(parent), d_ptr(new internal::DocumentPrivate) { } Document::Document(internal::DocumentPrivate *privatePointer, QObject *parent) : QObject(parent), d_ptr(privatePointer) { } Document::Document(internal::DocumentPrivate *privatePointer, QString collection, QObject *parent) : Document(privatePointer, parent) { d_func()->collectionName = collection; } Document::Document(QString collection, QObject *parent) : Document(new internal::DocumentPrivate, collection, parent) { } Document::Document(QString collection, QString key, QObject *parent) : Document(collection, parent) { set(internal::KEY, key); } Document::Document(QJsonObject obj, QObject * parent) : Document(new internal::DocumentPrivate, parent) { obj.remove(QStringLiteral("n")); d_func()->collectionName = obj.value(internal::ID).toString().split('/').at(0); d_func()->data.insert(internal::ID, obj.value(internal::ID)); d_func()->data.insert(internal::KEY, obj.value(internal::KEY)); d_func()->data.insert(internal::REV, obj.value(internal::REV)); d_func()->isCurrent = false; } Document::~Document() { delete d_ptr; } bool Document::isReady() { return d_func()->isReady; } bool Document::isCreated() { return d_func()->isCreated; } bool Document::isCurrent() { return d_func()->isCurrent; } QByteArray Document::toJsonString() const { QJsonDocument doc; if ( !isEveryAttributeDirty() ) { QJsonObject obj; obj.insert(internal::ID, obj.value(internal::ID)); obj.insert(internal::KEY, obj.value(internal::KEY)); obj.insert(internal::REV, obj.value(internal::REV)); for( QString attribute : d_func()->dirtyAttributes ) { obj.insert(attribute, d_func()->data[attribute]); } doc.setObject(obj); } else { doc.setObject(d_func()->data); } return doc.toJson(); } QString Document::docID() const { return d_func()->data.value(internal::ID).toString(); } QString Document::key() const { return d_func()->data.value(internal::KEY).toString(); } QString Document::rev() const { return d_func()->data.value(internal::REV).toString(); } QString Document::collection() const { return d_func()->collectionName; } QString Document::errorMessage() const { return d_func()->errorMessage; } quint32 Document::errorCode() { return d_func()->errorCode; } quint32 Document::errorNumber() { return d_func()->errorNumber; } bool Document::hasErrorOccurred() { return d_func()->errorCode != 0; } void Document::set(const QString &key, QVariant data) { d_func()->dirtyAttributes.append(key); d_func()->data.insert(key, QJsonValue::fromVariant(data)); d_func()->isDirty = true; } QVariant Document::get(const QString &key) const { return d_func()->data.value(key).toVariant(); } bool Document::contains(const QString & key) const { return d_func()->data.contains(key); } QStringList Document::dirtyAttributes() const { return d_func()->dirtyAttributes; } bool Document::isEveryAttributeDirty() const { int attributes = d_func()->data.keys().size()-3; if ( d_func()->data.contains("error") ) { attributes--; } return d_func()->dirtyAttributes.size() >= attributes; } void Document::waitForResult() { bool b = true; QMetaObject::Connection conn1 = QObject::connect(this, &Document::ready, [&] { b = false; }); QMetaObject::Connection conn2 = QObject::connect(this, &Document::error, [&] { b = false; }); while (b) { qApp->processEvents(); } QObject::disconnect(conn1); QObject::disconnect(conn2); } void Document::_ar_dataIsAvailable() { QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); QJsonObject obj = QJsonDocument::fromJson(reply->readAll()).object(); d_func()->dirtyAttributes.clear(); reply->disconnect(this, SLOT(_ar_dataIsAvailable())); bool hasError = obj.value("error").toBool(); if ( hasError ) { d_func()->errorMessage = obj.value("errorMessage").toString(); d_func()->errorNumber = obj.value("errorNum").toVariant().toInt(); d_func()->errorCode = obj.value("code").toVariant().toInt(); emit error(); } else { d_func()->isReady = true; d_func()->isCreated = true; d_func()->isCurrent = true; for ( auto key : obj.keys() ) { d_func()->data.insert(key, obj[key]); } d_func()->resetError(); emit ready(); } } void Document::_ar_dataDeleted() { emit dataDeleted(); } void Document::_ar_dataUpdated() { QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); d_func()->isReady = true; if (reply->hasRawHeader("etag") ) { QByteArray etag = reply->rawHeader("etag"); etag.replace('"', ""); // comes from the rawHeader d_func()->isCreated = true; d_func()->isCurrent = ( etag == rev() ); } else { d_func()->isCreated = false; d_func()->isCurrent = false; } emit ready(); } void Document::save() { if ( !d_func()->isCreated || d_func()->isDirty ) { d_func()->isDirty = false; emit saveData(this); } } void Document::sync() { if ( !d_func()->isCurrent ) { emit syncData(this); } } void Document::drop() { if ( d_func()->isCreated ) { d_func()->isDirty = false; d_func()->isCreated = false; emit deleteData(this); } } void Document::updateStatus() { emit updateDataStatus(this); } <|endoftext|>
<commit_before> #include "nucleus/FilePath.h" #include "nucleus/Macros.h" #if OS(POSIX) #include <unistd.h> #if OS(LINUX) #include <linux/limits.h> #endif #elif OS(WIN) #include "nucleus/Win/WindowsMixin.h" #endif #include "nucleus/MemoryDebug.h" namespace nu { namespace { // If this FilePath contains a drive letter specification, returns the position of the last // character of the drive letter specification, otherwise returns npos. This can only be true on // Windows, when a pathname begins with a letter followed by a colon. On other platforms, this // always returns npos. #if OS(WIN) StringLength findDriveLetter(const StringView& path) { if (path.getLength() >= 2 && path[1] == ':' && ((path[0] >= 'A' && path[0] <= 'Z') || (path[0] >= 'a' && path[0] <= 'z'))) { return 1; } return StringView::kInvalidPosition; } #else StringLength findDriveLetter(const StringView&) { return StringView::kInvalidPosition; } #endif #if OS(WIN) bool equalDriveLetterCaseInsensitive(const StringView& left, const StringView& right) { auto leftLetterPos = findDriveLetter(left); auto rightLetterPos = findDriveLetter(right); if (leftLetterPos == StringView::kInvalidPosition || rightLetterPos == StringView::kInvalidPosition) { return leftLetterPos == rightLetterPos; } auto leftLetter{left.subString(0, leftLetterPos + 1)}; auto rightLetter{right.subString(0, rightLetterPos + 1)}; #if 0 if (!StartsWith(leftLetter, rightLetter, false)) return false; #endif // 0 auto leftRest = left.subString(leftLetterPos + 1); auto rightRest = left.subString(rightLetterPos + 1); return leftRest == rightRest; } #endif // OS(WIN) // Null-terminated array of separators used to separate components in hierarchical paths. Each // character in this array is a valid separator, but kSeparators[0] is treated as the canonical // separator and will be used when composing path names. #if OS(WIN) static const char kSeparators[] = "\\/"; #else static const char kSeparators[] = "/"; #endif // A special path component meaning "this directory." static const char kCurrentDirectory[] = "."; #if 0 // A special path component meaning "the parent directory." static const char kParentDirectory[] = ".."; #endif #if 0 // The character used to identify a file extension. static const char kExtensionSeparator = '.'; #endif } // namespace // static bool FilePath::isSeparator(Char ch) { for (MemSize i = 0; i < ARRAY_SIZE(kSeparators) - 1; ++i) { if (ch == kSeparators[i]) { return true; } } return false; } // static FilePath FilePath::normalizeSeparators(const StringView& path) { FilePath result{path}; for (StringLength i = 0; i < result.m_path.getLength(); ++i) { if (isSeparator(result.m_path[i])) { result.m_path[i] = kSeparators[0]; } } return result; } FilePath::FilePath() = default; FilePath::FilePath(const StringView& path) : m_path{path.getData(), path.getLength()} {} FilePath::FilePath(const FilePath& other) = default; FilePath& FilePath::operator=(const FilePath& other) = default; bool FilePath::operator==(const FilePath& other) const { #if OS(WIN) return equalDriveLetterCaseInsensitive(m_path, other.m_path); #else return m_path == other.m_path; #endif } bool FilePath::operator!=(const FilePath& other) const { return !(*this == other); } void FilePath::clear() {} FilePath FilePath::dirName() const { FilePath newPath{*this}; newPath.stripTrailingSeparators(); auto letter = findDriveLetter(newPath.m_path); auto lastSeparator = newPath.m_path.findLastOfAny(StringView{kSeparators, ARRAY_SIZE(kSeparators) - 1}); if (lastSeparator == StringView::kInvalidPosition) { // m_path is in the current directory. newPath.m_path.resize(letter + 1); } else if (lastSeparator == letter + 1) { // m_path is in the root directory. newPath.m_path.resize(letter + 2); } else if (lastSeparator == letter + 2 && isSeparator(newPath.m_path[letter + 1])) { // m_path is in "//" (possibly with a drive letter), so leave the double separator intact // indicating alternate root. newPath.m_path.resize(letter + 3); } else if (lastSeparator != 0) { // m_path is somewhere else, trim the base name. newPath.m_path.resize(lastSeparator); } newPath.stripTrailingSeparators(); if (newPath.m_path.isEmpty()) { newPath.m_path = StringView{kCurrentDirectory, ARRAY_SIZE(kCurrentDirectory) - 1}; } return newPath; } FilePath FilePath::baseName() const { FilePath newPath = *this; newPath.stripTrailingSeparators(); // The drive letter, if any, is always stripped. auto letter = findDriveLetter(newPath.m_path); if (letter != StringView::kInvalidPosition) { newPath.m_path.erase(0, letter + 1); } // Keep everything after the final separator, but if the pathname is only one character and it's a // separator, leave it alone. auto lastSeparator = newPath.m_path.findLastOfAny(StringView{kSeparators, ARRAY_SIZE(kSeparators) - 1}); if (lastSeparator != StringView::kInvalidPosition && lastSeparator < newPath.m_path.getLength() - 1) { newPath.m_path.erase(0, lastSeparator + 1); } return newPath; } FilePath FilePath::append(const StringView& component) const { return append(FilePath{component}); } FilePath FilePath::append(const FilePath& component) const { #if 0 DCHECK(!isPathAbsolute(*appended)); #endif // 0 #if 0 if (m_path.compare(String(kCurrentDirectory, ARRAY_SIZE(kCurrentDirectory) - 1)) == 0 && !component.isEmpty()) { // Append normally doesn't do any normalization, but as a special case, when appending to // `kCurrentDirectory`, just return a new path for the `component` argument. Appending // `component` to `kCurrentDirectory` would serve no purpose other than needlessly lengthening // the path. return FilePath{component}; } #endif // 0 FilePath newPath = *this; newPath.stripTrailingSeparators(); // Don't append a separator if the path is empty (indicating the current directory) or if the path // component is empty (indicating nothing to append). if (!component.m_path.isEmpty() && !newPath.m_path.isEmpty()) { // Don't append a separator if the path still ends with a trailing separator after stripping // (indicating the root directory). if (!isSeparator(newPath.m_path[newPath.m_path.getLength() - 1])) { // Don't append a separator if the path is just a drive letter. if (findDriveLetter(newPath.m_path) + 1 != newPath.m_path.getLength()) { newPath.m_path.append(kSeparators[0]); } } } newPath.m_path.append(component.m_path); return newPath; } void FilePath::stripTrailingSeparators() { // If there is no drive letter, start will be 1, which will prevent stripping the leading // separator if there is only one separator. If there is a drive letter, start will be set // appropriately to prevent stripping the first separator following the drive letter, if a // separator immediately follows the drive letter. auto start = findDriveLetter(m_path) + 2; auto lastStripped = StringView::kInvalidPosition; for (auto pos = m_path.getLength(); pos > start && isSeparator(m_path[pos - 1]); --pos) { // If the string only has two separators and they're at the beginning, don't strip them, unless // the string began with more than two separators. if (pos != start + 1 || lastStripped == start + 2 || !isSeparator(m_path[start - 1])) { m_path.resize(pos - 1); lastStripped = pos; } } } FilePath getCurrentWorkingDirectory() { #if OS(POSIX) char buf[PATH_MAX] = {0}; const char* result = ::getcwd(buf, PATH_MAX); return FilePath{result}; #elif OS(WIN) char buf[MAX_PATH] = {0}; DWORD result = ::GetCurrentDirectoryA(MAX_PATH, buf); return FilePath{StringView{buf, result}}; #endif } bool exists(const FilePath& path) { return access(path.getPath().getData(), F_OK) != -1; } } // namespace nu <commit_msg>Win32 implementation for file exists<commit_after> #include "nucleus/FilePath.h" #include "nucleus/Macros.h" #if OS(POSIX) #include <unistd.h> #if OS(LINUX) #include <linux/limits.h> #endif #elif OS(WIN) #include "nucleus/Win/WindowsMixin.h" #endif #include "nucleus/MemoryDebug.h" namespace nu { namespace { // If this FilePath contains a drive letter specification, returns the position of the last // character of the drive letter specification, otherwise returns npos. This can only be true on // Windows, when a pathname begins with a letter followed by a colon. On other platforms, this // always returns npos. #if OS(WIN) StringLength findDriveLetter(const StringView& path) { if (path.getLength() >= 2 && path[1] == ':' && ((path[0] >= 'A' && path[0] <= 'Z') || (path[0] >= 'a' && path[0] <= 'z'))) { return 1; } return StringView::kInvalidPosition; } #else StringLength findDriveLetter(const StringView&) { return StringView::kInvalidPosition; } #endif #if OS(WIN) bool equalDriveLetterCaseInsensitive(const StringView& left, const StringView& right) { auto leftLetterPos = findDriveLetter(left); auto rightLetterPos = findDriveLetter(right); if (leftLetterPos == StringView::kInvalidPosition || rightLetterPos == StringView::kInvalidPosition) { return leftLetterPos == rightLetterPos; } auto leftLetter{left.subString(0, leftLetterPos + 1)}; auto rightLetter{right.subString(0, rightLetterPos + 1)}; #if 0 if (!StartsWith(leftLetter, rightLetter, false)) return false; #endif // 0 auto leftRest = left.subString(leftLetterPos + 1); auto rightRest = left.subString(rightLetterPos + 1); return leftRest == rightRest; } #endif // OS(WIN) // Null-terminated array of separators used to separate components in hierarchical paths. Each // character in this array is a valid separator, but kSeparators[0] is treated as the canonical // separator and will be used when composing path names. #if OS(WIN) static const char kSeparators[] = "\\/"; #else static const char kSeparators[] = "/"; #endif // A special path component meaning "this directory." static const char kCurrentDirectory[] = "."; #if 0 // A special path component meaning "the parent directory." static const char kParentDirectory[] = ".."; #endif #if 0 // The character used to identify a file extension. static const char kExtensionSeparator = '.'; #endif } // namespace // static bool FilePath::isSeparator(Char ch) { for (MemSize i = 0; i < ARRAY_SIZE(kSeparators) - 1; ++i) { if (ch == kSeparators[i]) { return true; } } return false; } // static FilePath FilePath::normalizeSeparators(const StringView& path) { FilePath result{path}; for (StringLength i = 0; i < result.m_path.getLength(); ++i) { if (isSeparator(result.m_path[i])) { result.m_path[i] = kSeparators[0]; } } return result; } FilePath::FilePath() = default; FilePath::FilePath(const StringView& path) : m_path{path.getData(), path.getLength()} {} FilePath::FilePath(const FilePath& other) = default; FilePath& FilePath::operator=(const FilePath& other) = default; bool FilePath::operator==(const FilePath& other) const { #if OS(WIN) return equalDriveLetterCaseInsensitive(m_path, other.m_path); #else return m_path == other.m_path; #endif } bool FilePath::operator!=(const FilePath& other) const { return !(*this == other); } void FilePath::clear() {} FilePath FilePath::dirName() const { FilePath newPath{*this}; newPath.stripTrailingSeparators(); auto letter = findDriveLetter(newPath.m_path); auto lastSeparator = newPath.m_path.findLastOfAny(StringView{kSeparators, ARRAY_SIZE(kSeparators) - 1}); if (lastSeparator == StringView::kInvalidPosition) { // m_path is in the current directory. newPath.m_path.resize(letter + 1); } else if (lastSeparator == letter + 1) { // m_path is in the root directory. newPath.m_path.resize(letter + 2); } else if (lastSeparator == letter + 2 && isSeparator(newPath.m_path[letter + 1])) { // m_path is in "//" (possibly with a drive letter), so leave the double separator intact // indicating alternate root. newPath.m_path.resize(letter + 3); } else if (lastSeparator != 0) { // m_path is somewhere else, trim the base name. newPath.m_path.resize(lastSeparator); } newPath.stripTrailingSeparators(); if (newPath.m_path.isEmpty()) { newPath.m_path = StringView{kCurrentDirectory, ARRAY_SIZE(kCurrentDirectory) - 1}; } return newPath; } FilePath FilePath::baseName() const { FilePath newPath = *this; newPath.stripTrailingSeparators(); // The drive letter, if any, is always stripped. auto letter = findDriveLetter(newPath.m_path); if (letter != StringView::kInvalidPosition) { newPath.m_path.erase(0, letter + 1); } // Keep everything after the final separator, but if the pathname is only one character and it's a // separator, leave it alone. auto lastSeparator = newPath.m_path.findLastOfAny(StringView{kSeparators, ARRAY_SIZE(kSeparators) - 1}); if (lastSeparator != StringView::kInvalidPosition && lastSeparator < newPath.m_path.getLength() - 1) { newPath.m_path.erase(0, lastSeparator + 1); } return newPath; } FilePath FilePath::append(const StringView& component) const { return append(FilePath{component}); } FilePath FilePath::append(const FilePath& component) const { #if 0 DCHECK(!isPathAbsolute(*appended)); #endif // 0 #if 0 if (m_path.compare(String(kCurrentDirectory, ARRAY_SIZE(kCurrentDirectory) - 1)) == 0 && !component.isEmpty()) { // Append normally doesn't do any normalization, but as a special case, when appending to // `kCurrentDirectory`, just return a new path for the `component` argument. Appending // `component` to `kCurrentDirectory` would serve no purpose other than needlessly lengthening // the path. return FilePath{component}; } #endif // 0 FilePath newPath = *this; newPath.stripTrailingSeparators(); // Don't append a separator if the path is empty (indicating the current directory) or if the path // component is empty (indicating nothing to append). if (!component.m_path.isEmpty() && !newPath.m_path.isEmpty()) { // Don't append a separator if the path still ends with a trailing separator after stripping // (indicating the root directory). if (!isSeparator(newPath.m_path[newPath.m_path.getLength() - 1])) { // Don't append a separator if the path is just a drive letter. if (findDriveLetter(newPath.m_path) + 1 != newPath.m_path.getLength()) { newPath.m_path.append(kSeparators[0]); } } } newPath.m_path.append(component.m_path); return newPath; } void FilePath::stripTrailingSeparators() { // If there is no drive letter, start will be 1, which will prevent stripping the leading // separator if there is only one separator. If there is a drive letter, start will be set // appropriately to prevent stripping the first separator following the drive letter, if a // separator immediately follows the drive letter. auto start = findDriveLetter(m_path) + 2; auto lastStripped = StringView::kInvalidPosition; for (auto pos = m_path.getLength(); pos > start && isSeparator(m_path[pos - 1]); --pos) { // If the string only has two separators and they're at the beginning, don't strip them, unless // the string began with more than two separators. if (pos != start + 1 || lastStripped == start + 2 || !isSeparator(m_path[start - 1])) { m_path.resize(pos - 1); lastStripped = pos; } } } FilePath getCurrentWorkingDirectory() { #if OS(POSIX) char buf[PATH_MAX] = {0}; const char* result = ::getcwd(buf, PATH_MAX); return FilePath{result}; #elif OS(WIN) char buf[MAX_PATH] = {0}; DWORD result = ::GetCurrentDirectoryA(MAX_PATH, buf); return FilePath{StringView{buf, result}}; #endif } bool exists(const FilePath& path) { #if OS(POSIX) return access(path.getPath().getData(), F_OK) != -1; #else DWORD fileAttributes = GetFileAttributesA(path.getPath().getData()); return fileAttributes != INVALID_FILE_ATTRIBUTES; #endif } } // namespace nu <|endoftext|>
<commit_before>#ifndef KDE_GAUSSIAN_HPP #define KDE_GAUSSIAN_HPP namespace kde { template<realScalarType> realScalarType GaussPDF(realScalarType const& x, realScalarType const& mu, realScalarType const& sigma) { realScalarType z = (x - mu)/sigma; return std::exp(-realScalarType(0.5)*z*z) /(sigma*std::sqrt( realScalarType(2.)*M_PI)); } class classicBandwidth { public: template<class realMatrixType,class realVectorType> static void compute(realMatrixType const& dataMatrix, realVectorType & bandwidth) { typedef typename realMatrixType::Scalar realScalarType; typedef typename realMatrixType::Index indexType; assert(dataMatrix.cols() == bandwidth.rows()); for(indexType i=0;i<bandwidth.rows();++i) { realScalarType cnt = (realScalarType) dataMatrix.rows(); realScalarType mean = dataMatrix.col(i).mean(); realScalarType sqMean = dataMatrix.col(i).squaredNorm(); realScalarType sigma = std::sqrt(sqMean - mean*mean); bandwidth(i) = sigma*std::pow(realScalarType(3.)*cnt/realScalarType(4.), realScalarType(-1./5.)); } } }; template<typename _realSclarType> class OptimalBandwidthEquation { public: typedef _realScalarType realScalarType; typedef Eigen::Matrix<realScalarType,Eigen::Dynamic,Eigen::Dynamic> realMatrixType; typedef Eigen::Matrix<realScalarType,Eigen::Dynamic,1> realVectorType; typedef typename realVectorType::Index indexType; static realScalarType evaluate(realScalarType const w, realScalarType const min, realScalarType const max, realVectorType const & data) { realScalarType alpha = realScalarType(1.)/(realScalarType(2.)*std::sqrt(M_PI)) ; realScalarType sigma = realScalarType(1.); realScalarType n = (realScalarType) data.rows(); realScalarType q = stiffnessIntegral(w,min,max,data); return w - std::pow(n*q*std::pow(sigma,4)/alpha,-realScalarType(1./5.)) ; } static realScalarType stiffnessIntegral(realScalarType const w, realScalarType const min, realScalarType const max, realVectorType const & data) { realScalarType epsilon = ; realScalarType cnt(1); realScalarType dx = (max - min)/cnt; realScalarType curveMax = curvature(max,w,data);; realScalarType curveMin = curvature(max,w,data); realScalarType yy = 0.5*(curveMax*curveMax + curveMin*curveMin)*dx; realScalarType maxN = (max - min)/cnt; maxN = maxN > 2048 ? 2048 : maxN; for(indexType n=2; n<= maxN; n*=2) { dx *= 0.5; realScalarType y(0); for(indexType i = 1; i <= n-1; i +=2) { realScalarType curveVal = curvature(min + i*dx, w, data); curveMin = curveVal*curveVal; y += curv_mn; } yy = 0.5*yy + y*dx; if(n > 8 && std::abs(y*dx-0.5*yy) < eps*yy) { break; } } return yy; } static realScalarType curvature(realScalarType const x, realScalarType const w, realVectorType const & data) { realScalarType y(0); for(indexType i=0;i<data.rows();++i) { y += gaussCurvature(x,data(i),w); } return y/data.rows(); } static realScalarType gaussCurvature(realScalarType const x, realScalarType const m, realScalarType const s) { realScalarType z = (x - m)/s; return ((z*z) - 1.0)*GussPDF(x,m,s)/(s*s); } } class OptimalBandwidth { public: template<class realMatrixType,class realVectorType> static void compute(realMatrixType const& dataMatrix, realVectorType & bandwidth) { typedef typename realMatrixType::Scalar realScalarType; typedef typename realMatrixType::Index indexType; assert(dataMatrix.cols() == bandwidth.rows()); realVectorType defBw(bandwidth); classicBandwidth::compute(dataMatrix,defBw); for(indexType i=0;i<bandwidth.rows();++i) { realScalarType x0 = defBw(i); } } } template<typename _realScalarType> class GaussianKDE { public: typedef _realScalarType realScalarType; typedef Eigen::Matrix<realScalarType,Eigen::Dynamic,Eigen::Dynamic> realMatrixType; typedef Eigen::Matrix<realScalarType,Eigen::Dynamic,1> realVectorType; typedef typename realVectorType::Index indexType; GaussianKDE(realMatrixType const& dataMatrix) :mDataMatrix(dataMatrix),mBandwidth(mDataMatrix.cols()) { classicBandwidth::compute(mDataMatrix,mBandwidth); } realScalarType PDF(realVectorType const& x) { realScalarType d(0); for(indexType i=0;i<mDataMatrix.rows();++i) { realScalarType a(1); for(indexType j=0;j<x.rows();++j) { a *= GaussPDF(x(j),mDataMatrix(i,j),mBandwidth(j)); } d += a; } return d/mDataMatrix.rows(); } private: realMatrixType mDataMatrix; realVectorType mBandwidth; }; } #endif //KDE_GAUSSIAN_HPP <commit_msg>some compiler errors removed<commit_after>#ifndef KDE_GAUSSIAN_HPP #define KDE_GAUSSIAN_HPP namespace kde { template<typename realScalarType> realScalarType GaussPDF(realScalarType const& x, realScalarType const& mu, realScalarType const& sigma) { realScalarType z = (x - mu)/sigma; return std::exp(-realScalarType(0.5)*z*z) /(sigma*std::sqrt( realScalarType(2.)*M_PI)); } class classicBandwidth { public: template<class realMatrixType,class realVectorType> static void compute(realMatrixType const& dataMatrix, realVectorType & bandwidth) { typedef typename realMatrixType::Scalar realScalarType; typedef typename realMatrixType::Index indexType; assert(dataMatrix.cols() == bandwidth.rows()); for(indexType i=0;i<bandwidth.rows();++i) { realScalarType cnt = (realScalarType) dataMatrix.rows(); realScalarType mean = dataMatrix.col(i).mean(); realScalarType sqMean = dataMatrix.col(i).squaredNorm(); realScalarType sigma = std::sqrt(sqMean - mean*mean); bandwidth(i) = sigma*std::pow(realScalarType(3.)*cnt/realScalarType(4.), realScalarType(-1./5.)); } } }; template<typename _realScalarType> class OptimalBandwidthEquation { public: typedef _realScalarType realScalarType; typedef Eigen::Matrix<realScalarType,Eigen::Dynamic,Eigen::Dynamic> realMatrixType; typedef Eigen::Matrix<realScalarType,Eigen::Dynamic,1> realVectorType; typedef typename realVectorType::Index indexType; static realScalarType evaluate(realScalarType const w, realScalarType const min, realScalarType const max, realVectorType const & data) { realScalarType alpha = realScalarType(1.)/(realScalarType(2.)*std::sqrt(M_PI)) ; realScalarType sigma = realScalarType(1.); realScalarType n = (realScalarType) data.rows(); realScalarType q = stiffnessIntegral(w,min,max,data); return w - std::pow(n*q*std::pow(sigma,4)/alpha,-realScalarType(1./5.)) ; } static realScalarType stiffnessIntegral(realScalarType const w, realScalarType const min, realScalarType const max, realVectorType const & data) { realScalarType epsilon = 1e-4; realScalarType cnt(1); realScalarType dx = (max - min)/cnt; realScalarType curveMax = curvature(max,w,data);; realScalarType curveMin = curvature(max,w,data); realScalarType yy = 0.5*(curveMax*curveMax + curveMin*curveMin)*dx; realScalarType maxN = (max - min)/cnt; maxN = maxN > 2048 ? 2048 : maxN; for(indexType n=2; n<= maxN; n*=2) { dx *= 0.5; realScalarType y(0); for(indexType i = 1; i <= n-1; i +=2) { realScalarType curveVal = curvature(min + i*dx, w, data); curveMin = curveVal*curveVal; y += curveMin; } yy = 0.5*yy + y*dx; if(n > 8 && std::abs(y*dx-0.5*yy) < epsilon*yy) { break; } } return yy; } static realScalarType curvature(realScalarType const x, realScalarType const w, realVectorType const & data) { realScalarType y(0); for(indexType i=0;i<data.rows();++i) { y += gaussCurvature(x,data(i),w); } return y/data.rows(); } static realScalarType gaussCurvature(realScalarType const x, realScalarType const m, realScalarType const s) { realScalarType z = (x - m)/s; return ((z*z) - 1.0)*GussPDF(x,m,s)/(s*s); } }; class OptimalBandwidth { public: template<class realMatrixType,class realVectorType> static void compute(realMatrixType const& dataMatrix, realVectorType & bandwidth) { typedef typename realMatrixType::Scalar realScalarType; typedef typename realMatrixType::Index indexType; assert(dataMatrix.cols() == bandwidth.rows()); realVectorType defBw(bandwidth); classicBandwidth::compute(dataMatrix,defBw); for(indexType i=0;i<bandwidth.rows();++i) { realScalarType x0 = defBw(i); realScalarType y0 = OptimalBandwidthEquation<realScalarType>::evaluate(x0, dataMatrix.col(i).min(),dataMatrix.col(i).max(), dataMatrix.col(i)); } } }; template<typename _realScalarType> class GaussianKDE { public: typedef _realScalarType realScalarType; typedef Eigen::Matrix<realScalarType,Eigen::Dynamic,Eigen::Dynamic> realMatrixType; typedef Eigen::Matrix<realScalarType,Eigen::Dynamic,1> realVectorType; typedef typename realVectorType::Index indexType; GaussianKDE(realMatrixType const& dataMatrix) :mDataMatrix(dataMatrix),mBandwidth(mDataMatrix.cols()) { classicBandwidth::compute(mDataMatrix,mBandwidth); } realScalarType PDF(realVectorType const& x) { realScalarType d(0); for(indexType i=0;i<mDataMatrix.rows();++i) { realScalarType a(1); for(indexType j=0;j<x.rows();++j) { a *= GaussPDF(x(j),mDataMatrix(i,j),mBandwidth(j)); } d += a; } return d/mDataMatrix.rows(); } private: realMatrixType mDataMatrix; realVectorType mBandwidth; }; } #endif //KDE_GAUSSIAN_HPP <|endoftext|>
<commit_before>// Module: Log4CPLUS // File: socket-win32.cxx // Created: 4/2003 // Author: Tad E. Smith // // // Copyright 2003-2010 Tad E. Smith // // 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 <log4cplus/config.hxx> #if defined (LOG4CPLUS_USE_WINSOCK) #include <cassert> #include <cerrno> #include <vector> #include <cstring> #include <log4cplus/internal/socket.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/thread/threads.h> #include <log4cplus/helpers/stringhelper.h> ///////////////////////////////////////////////////////////////////////////// // file LOCAL Classes ///////////////////////////////////////////////////////////////////////////// namespace { enum WSInitStates { WS_UNINITIALIZED, WS_INITIALIZING, WS_INITIALIZED }; static WSADATA wsa; static LONG volatile winsock_state = WS_UNINITIALIZED; static void init_winsock_worker () { log4cplus::helpers::LogLog * loglog = log4cplus::helpers::LogLog::getLogLog (); // Try to change the state to WS_INITIALIZING. LONG val = ::InterlockedCompareExchange ( const_cast<LPLONG>(&winsock_state), WS_INITIALIZING, WS_UNINITIALIZED); switch (val) { case WS_UNINITIALIZED: { int ret = WSAStartup (MAKEWORD (2, 2), &wsa); if (ret != 0) { // Revert the state back to WS_UNINITIALIZED to unblock other // threads and let them throw exception. val = ::InterlockedCompareExchange ( const_cast<LPLONG>(&winsock_state), WS_UNINITIALIZED, WS_INITIALIZING); assert (val == WS_INITIALIZING); loglog->error (LOG4CPLUS_TEXT ("Could not initialize WinSock."), true); } // WinSock is initialized, change the state to WS_INITIALIZED. val = ::InterlockedCompareExchange ( const_cast<LPLONG>(&winsock_state), WS_INITIALIZED, WS_INITIALIZING); assert (val == WS_INITIALIZING); return; } case WS_INITIALIZING: // Wait for state change. while (true) { switch (winsock_state) { case WS_INITIALIZED: return; case WS_INITIALIZING: log4cplus::thread::yield (); continue; default: assert (0); loglog->error (LOG4CPLUS_TEXT ("Unknown WinSock state."), true); } } case WS_INITIALIZED: // WinSock is already initialized. return; default: assert (0); loglog->error (LOG4CPLUS_TEXT ("Unknown WinSock state."), true); } } static void init_winsock () { // Quick check first to avoid the expensive interlocked compare // and exchange. if (winsock_state == WS_INITIALIZED) return; else init_winsock_worker (); } struct WinSockInitializer { ~WinSockInitializer () { if (winsock_state == WS_INITIALIZED) WSACleanup (); } static WinSockInitializer winSockInitializer; }; WinSockInitializer WinSockInitializer::winSockInitializer; } // namespace namespace log4cplus { namespace helpers { ///////////////////////////////////////////////////////////////////////////// // Global Methods ///////////////////////////////////////////////////////////////////////////// SOCKET_TYPE openSocket(unsigned short port, SocketState& state) { struct sockaddr_in server; init_winsock (); SOCKET sock = WSASocket (AF_INET, SOCK_STREAM, AF_UNSPEC, 0, 0 #if defined (WSA_FLAG_NO_HANDLE_INHERIT) , WSA_FLAG_NO_HANDLE_INHERIT #else , 0 #endif ); if (sock == INVALID_OS_SOCKET_VALUE) goto error; server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(port); if (bind(sock, reinterpret_cast<struct sockaddr*>(&server), sizeof(server)) != 0) goto error; if (::listen(sock, 10) != 0) goto error; state = ok; return to_log4cplus_socket (sock); error: int eno = WSAGetLastError (); if (sock != INVALID_OS_SOCKET_VALUE) ::closesocket (sock); set_last_socket_error (eno); return INVALID_SOCKET_VALUE; } SOCKET_TYPE connectSocket(const tstring& hostn, unsigned short port, bool udp, SocketState& state) { struct hostent * hp; struct sockaddr_in insock; int retval; init_winsock (); SOCKET sock = WSASocket (AF_INET, (udp ? SOCK_DGRAM : SOCK_STREAM), AF_UNSPEC, 0, 0 #if defined (WSA_FLAG_NO_HANDLE_INHERIT) , WSA_FLAG_NO_HANDLE_INHERIT #else , 0 #endif ); if (sock == INVALID_OS_SOCKET_VALUE) goto error; hp = ::gethostbyname( LOG4CPLUS_TSTRING_TO_STRING(hostn).c_str() ); if (hp == 0 || hp->h_addrtype != AF_INET) { insock.sin_family = AF_INET; INT insock_size = sizeof (insock); INT ret = WSAStringToAddress (const_cast<LPTSTR>(hostn.c_str ()), AF_INET, 0, reinterpret_cast<struct sockaddr *>(&insock), &insock_size); if (ret == SOCKET_ERROR || insock_size != static_cast<INT>(sizeof (insock))) { state = bad_address; goto error; } } else std::memcpy (&insock.sin_addr, hp->h_addr_list[0], sizeof (insock.sin_addr)); insock.sin_port = htons(port); insock.sin_family = AF_INET; while( (retval = ::connect(sock, (struct sockaddr*)&insock, sizeof(insock))) == -1 && (WSAGetLastError() == WSAEINTR)) ; if (retval == SOCKET_ERROR) goto error; state = ok; return to_log4cplus_socket (sock); error: int eno = WSAGetLastError (); if (sock != INVALID_OS_SOCKET_VALUE) ::closesocket (sock); set_last_socket_error (eno); return INVALID_SOCKET_VALUE; } SOCKET_TYPE acceptSocket(SOCKET_TYPE sock, SocketState & state) { init_winsock (); SOCKET osSocket = to_os_socket (sock); // Check that the socket is ok. int val = 0; int optlen = sizeof (val); int ret = getsockopt (osSocket, SOL_SOCKET, SO_TYPE, reinterpret_cast<char *>(&val), &optlen); if (ret == SOCKET_ERROR) goto error; // Now that we know the socket is working ok we can wait for // either a new connection or for a transition to bad state. while (1) { fd_set readSet; timeval timeout; FD_ZERO (&readSet); FD_SET (osSocket, &readSet); timeout.tv_sec = 0; timeout.tv_usec = 200 * 1000; int selectResponse = ::select (1, &readSet, NULL, NULL, &timeout); if (selectResponse < 0) { DWORD const eno = WSAGetLastError (); if (eno == WSAENOTSOCK || eno == WSAEINVAL) WSASetLastError (ERROR_NO_DATA); goto error; } else if (selectResponse == 0) // Timeout. continue; else if (selectResponse == 1) { SOCKET connected_socket = ::accept (osSocket, NULL, NULL); if (connected_socket != INVALID_OS_SOCKET_VALUE) state = ok; else goto error; return to_log4cplus_socket (connected_socket); } else { helpers::getLogLog ().error ( LOG4CPLUS_TEXT ("unexpected select() return value: ") + helpers::convertIntegerToString (selectResponse)); WSASetLastError (ERROR_UNSUPPORTED_TYPE); goto error; } } error: DWORD eno = WSAGetLastError (); set_last_socket_error (eno); return to_log4cplus_socket (INVALID_SOCKET); } int closeSocket(SOCKET_TYPE sock) { return ::closesocket (to_os_socket (sock)); } long read(SOCKET_TYPE sock, SocketBuffer& buffer) { long res, read = 0; os_socket_type const osSocket = to_os_socket (sock); do { res = ::recv(osSocket, buffer.getBuffer() + read, static_cast<int>(buffer.getMaxSize() - read), 0); if (res == SOCKET_ERROR) { set_last_socket_error (WSAGetLastError ()); return res; } // A return of 0 indicates the socket is closed, // return to prevent an infinite loop. if (res == 0) return read; read += res; } while (read < static_cast<long>(buffer.getMaxSize())); return read; } long write(SOCKET_TYPE sock, const SocketBuffer& buffer) { long ret = ::send (to_os_socket (sock), buffer.getBuffer(), static_cast<int>(buffer.getSize()), 0); if (ret == SOCKET_ERROR) set_last_socket_error (WSAGetLastError ()); return ret; } long write(SOCKET_TYPE sock, const std::string & buffer) { long ret = ::send (to_os_socket (sock), buffer.c_str (), static_cast<int>(buffer.size ()), 0); if (ret == SOCKET_ERROR) set_last_socket_error (WSAGetLastError ()); return ret; } tstring getHostname (bool fqdn) { char const * hostname = "unknown"; int ret; std::vector<char> hn (1024, 0); while (true) { ret = ::gethostname (&hn[0], static_cast<int>(hn.size ()) - 1); if (ret == 0) { hostname = &hn[0]; break; } else if (ret != 0 && WSAGetLastError () == WSAEFAULT) // Out buffer was too short. Retry with buffer twice the size. hn.resize (hn.size () * 2, 0); else break; } if (ret != 0 || (ret == 0 && ! fqdn)) return LOG4CPLUS_STRING_TO_TSTRING (hostname); struct ::hostent * hp = ::gethostbyname (hostname); if (hp) hostname = hp->h_name; return LOG4CPLUS_STRING_TO_TSTRING (hostname); } int setTCPNoDelay (SOCKET_TYPE sock, bool val) { int result; int enabled = static_cast<int>(val); if ((result = setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&enabled),sizeof(enabled))) != 0) { int eno = WSAGetLastError (); set_last_socket_error (eno); } return result; } } } // namespace log4cplus { namespace helpers { #endif // LOG4CPLUS_USE_WINSOCK <commit_msg>socket-win32.cxx: Call init_winsock() in getHostname(). Fixes bug #154.<commit_after>// Module: Log4CPLUS // File: socket-win32.cxx // Created: 4/2003 // Author: Tad E. Smith // // // Copyright 2003-2010 Tad E. Smith // // 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 <log4cplus/config.hxx> #if defined (LOG4CPLUS_USE_WINSOCK) #include <cassert> #include <cerrno> #include <vector> #include <cstring> #include <log4cplus/internal/socket.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/thread/threads.h> #include <log4cplus/helpers/stringhelper.h> ///////////////////////////////////////////////////////////////////////////// // file LOCAL Classes ///////////////////////////////////////////////////////////////////////////// namespace { enum WSInitStates { WS_UNINITIALIZED, WS_INITIALIZING, WS_INITIALIZED }; static WSADATA wsa; static LONG volatile winsock_state = WS_UNINITIALIZED; static void init_winsock_worker () { log4cplus::helpers::LogLog * loglog = log4cplus::helpers::LogLog::getLogLog (); // Try to change the state to WS_INITIALIZING. LONG val = ::InterlockedCompareExchange ( const_cast<LPLONG>(&winsock_state), WS_INITIALIZING, WS_UNINITIALIZED); switch (val) { case WS_UNINITIALIZED: { int ret = WSAStartup (MAKEWORD (2, 2), &wsa); if (ret != 0) { // Revert the state back to WS_UNINITIALIZED to unblock other // threads and let them throw exception. val = ::InterlockedCompareExchange ( const_cast<LPLONG>(&winsock_state), WS_UNINITIALIZED, WS_INITIALIZING); assert (val == WS_INITIALIZING); loglog->error (LOG4CPLUS_TEXT ("Could not initialize WinSock."), true); } // WinSock is initialized, change the state to WS_INITIALIZED. val = ::InterlockedCompareExchange ( const_cast<LPLONG>(&winsock_state), WS_INITIALIZED, WS_INITIALIZING); assert (val == WS_INITIALIZING); return; } case WS_INITIALIZING: // Wait for state change. while (true) { switch (winsock_state) { case WS_INITIALIZED: return; case WS_INITIALIZING: log4cplus::thread::yield (); continue; default: assert (0); loglog->error (LOG4CPLUS_TEXT ("Unknown WinSock state."), true); } } case WS_INITIALIZED: // WinSock is already initialized. return; default: assert (0); loglog->error (LOG4CPLUS_TEXT ("Unknown WinSock state."), true); } } static void init_winsock () { // Quick check first to avoid the expensive interlocked compare // and exchange. if (winsock_state == WS_INITIALIZED) return; else init_winsock_worker (); } struct WinSockInitializer { ~WinSockInitializer () { if (winsock_state == WS_INITIALIZED) WSACleanup (); } static WinSockInitializer winSockInitializer; }; WinSockInitializer WinSockInitializer::winSockInitializer; } // namespace namespace log4cplus { namespace helpers { ///////////////////////////////////////////////////////////////////////////// // Global Methods ///////////////////////////////////////////////////////////////////////////// SOCKET_TYPE openSocket(unsigned short port, SocketState& state) { struct sockaddr_in server; init_winsock (); SOCKET sock = WSASocket (AF_INET, SOCK_STREAM, AF_UNSPEC, 0, 0 #if defined (WSA_FLAG_NO_HANDLE_INHERIT) , WSA_FLAG_NO_HANDLE_INHERIT #else , 0 #endif ); if (sock == INVALID_OS_SOCKET_VALUE) goto error; server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(port); if (bind(sock, reinterpret_cast<struct sockaddr*>(&server), sizeof(server)) != 0) goto error; if (::listen(sock, 10) != 0) goto error; state = ok; return to_log4cplus_socket (sock); error: int eno = WSAGetLastError (); if (sock != INVALID_OS_SOCKET_VALUE) ::closesocket (sock); set_last_socket_error (eno); return INVALID_SOCKET_VALUE; } SOCKET_TYPE connectSocket(const tstring& hostn, unsigned short port, bool udp, SocketState& state) { struct hostent * hp; struct sockaddr_in insock; int retval; init_winsock (); SOCKET sock = WSASocket (AF_INET, (udp ? SOCK_DGRAM : SOCK_STREAM), AF_UNSPEC, 0, 0 #if defined (WSA_FLAG_NO_HANDLE_INHERIT) , WSA_FLAG_NO_HANDLE_INHERIT #else , 0 #endif ); if (sock == INVALID_OS_SOCKET_VALUE) goto error; hp = ::gethostbyname( LOG4CPLUS_TSTRING_TO_STRING(hostn).c_str() ); if (hp == 0 || hp->h_addrtype != AF_INET) { insock.sin_family = AF_INET; INT insock_size = sizeof (insock); INT ret = WSAStringToAddress (const_cast<LPTSTR>(hostn.c_str ()), AF_INET, 0, reinterpret_cast<struct sockaddr *>(&insock), &insock_size); if (ret == SOCKET_ERROR || insock_size != static_cast<INT>(sizeof (insock))) { state = bad_address; goto error; } } else std::memcpy (&insock.sin_addr, hp->h_addr_list[0], sizeof (insock.sin_addr)); insock.sin_port = htons(port); insock.sin_family = AF_INET; while( (retval = ::connect(sock, (struct sockaddr*)&insock, sizeof(insock))) == -1 && (WSAGetLastError() == WSAEINTR)) ; if (retval == SOCKET_ERROR) goto error; state = ok; return to_log4cplus_socket (sock); error: int eno = WSAGetLastError (); if (sock != INVALID_OS_SOCKET_VALUE) ::closesocket (sock); set_last_socket_error (eno); return INVALID_SOCKET_VALUE; } SOCKET_TYPE acceptSocket(SOCKET_TYPE sock, SocketState & state) { init_winsock (); SOCKET osSocket = to_os_socket (sock); // Check that the socket is ok. int val = 0; int optlen = sizeof (val); int ret = getsockopt (osSocket, SOL_SOCKET, SO_TYPE, reinterpret_cast<char *>(&val), &optlen); if (ret == SOCKET_ERROR) goto error; // Now that we know the socket is working ok we can wait for // either a new connection or for a transition to bad state. while (1) { fd_set readSet; timeval timeout; FD_ZERO (&readSet); FD_SET (osSocket, &readSet); timeout.tv_sec = 0; timeout.tv_usec = 200 * 1000; int selectResponse = ::select (1, &readSet, NULL, NULL, &timeout); if (selectResponse < 0) { DWORD const eno = WSAGetLastError (); if (eno == WSAENOTSOCK || eno == WSAEINVAL) WSASetLastError (ERROR_NO_DATA); goto error; } else if (selectResponse == 0) // Timeout. continue; else if (selectResponse == 1) { SOCKET connected_socket = ::accept (osSocket, NULL, NULL); if (connected_socket != INVALID_OS_SOCKET_VALUE) state = ok; else goto error; return to_log4cplus_socket (connected_socket); } else { helpers::getLogLog ().error ( LOG4CPLUS_TEXT ("unexpected select() return value: ") + helpers::convertIntegerToString (selectResponse)); WSASetLastError (ERROR_UNSUPPORTED_TYPE); goto error; } } error: DWORD eno = WSAGetLastError (); set_last_socket_error (eno); return to_log4cplus_socket (INVALID_SOCKET); } int closeSocket(SOCKET_TYPE sock) { return ::closesocket (to_os_socket (sock)); } long read(SOCKET_TYPE sock, SocketBuffer& buffer) { long res, read = 0; os_socket_type const osSocket = to_os_socket (sock); do { res = ::recv(osSocket, buffer.getBuffer() + read, static_cast<int>(buffer.getMaxSize() - read), 0); if (res == SOCKET_ERROR) { set_last_socket_error (WSAGetLastError ()); return res; } // A return of 0 indicates the socket is closed, // return to prevent an infinite loop. if (res == 0) return read; read += res; } while (read < static_cast<long>(buffer.getMaxSize())); return read; } long write(SOCKET_TYPE sock, const SocketBuffer& buffer) { long ret = ::send (to_os_socket (sock), buffer.getBuffer(), static_cast<int>(buffer.getSize()), 0); if (ret == SOCKET_ERROR) set_last_socket_error (WSAGetLastError ()); return ret; } long write(SOCKET_TYPE sock, const std::string & buffer) { long ret = ::send (to_os_socket (sock), buffer.c_str (), static_cast<int>(buffer.size ()), 0); if (ret == SOCKET_ERROR) set_last_socket_error (WSAGetLastError ()); return ret; } tstring getHostname (bool fqdn) { init_winsock (); char const * hostname = "unknown"; int ret; std::vector<char> hn (1024, 0); while (true) { ret = ::gethostname (&hn[0], static_cast<int>(hn.size ()) - 1); if (ret == 0) { hostname = &hn[0]; break; } else if (ret != 0 && WSAGetLastError () == WSAEFAULT) // Out buffer was too short. Retry with buffer twice the size. hn.resize (hn.size () * 2, 0); else break; } if (ret != 0 || (ret == 0 && ! fqdn)) return LOG4CPLUS_STRING_TO_TSTRING (hostname); struct ::hostent * hp = ::gethostbyname (hostname); if (hp) hostname = hp->h_name; return LOG4CPLUS_STRING_TO_TSTRING (hostname); } int setTCPNoDelay (SOCKET_TYPE sock, bool val) { int result; int enabled = static_cast<int>(val); if ((result = setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&enabled),sizeof(enabled))) != 0) { int eno = WSAGetLastError (); set_last_socket_error (eno); } return result; } } } // namespace log4cplus { namespace helpers { #endif // LOG4CPLUS_USE_WINSOCK <|endoftext|>
<commit_before>// Module: Log4CPLUS // File: socket-win32.cxx // Created: 4/2003 // Author: Tad E. Smith // // // Copyright 2003-2010 Tad E. Smith // // 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 <log4cplus/config.hxx> #if defined (LOG4CPLUS_USE_WINSOCK) #include <cassert> #include <cerrno> #include <vector> #include <cstring> #include <log4cplus/internal/socket.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/thread/threads.h> #include <log4cplus/helpers/stringhelper.h> ///////////////////////////////////////////////////////////////////////////// // file LOCAL Classes ///////////////////////////////////////////////////////////////////////////// namespace { enum WSInitStates { WS_UNINITIALIZED, WS_INITIALIZING, WS_INITIALIZED }; static WSADATA wsa; static LONG volatile winsock_state = WS_UNINITIALIZED; static void init_winsock_worker () { log4cplus::helpers::LogLog * loglog = log4cplus::helpers::LogLog::getLogLog (); // Try to change the state to WS_INITIALIZING. LONG val = ::InterlockedCompareExchange ( const_cast<LPLONG>(&winsock_state), WS_INITIALIZING, WS_UNINITIALIZED); switch (val) { case WS_UNINITIALIZED: { int ret = WSAStartup (MAKEWORD (2, 2), &wsa); if (ret != 0) { // Revert the state back to WS_UNINITIALIZED to unblock other // threads and let them throw exception. val = ::InterlockedCompareExchange ( const_cast<LPLONG>(&winsock_state), WS_UNINITIALIZED, WS_INITIALIZING); assert (val == WS_INITIALIZING); loglog->error (LOG4CPLUS_TEXT ("Could not initialize WinSock."), true); } // WinSock is initialized, change the state to WS_INITIALIZED. val = ::InterlockedCompareExchange ( const_cast<LPLONG>(&winsock_state), WS_INITIALIZED, WS_INITIALIZING); assert (val == WS_INITIALIZING); return; } case WS_INITIALIZING: // Wait for state change. while (true) { switch (winsock_state) { case WS_INITIALIZED: return; case WS_INITIALIZING: log4cplus::thread::yield (); continue; default: assert (0); loglog->error (LOG4CPLUS_TEXT ("Unknown WinSock state."), true); } } case WS_INITIALIZED: // WinSock is already initialized. return; default: assert (0); loglog->error (LOG4CPLUS_TEXT ("Unknown WinSock state."), true); } } static void init_winsock () { // Quick check first to avoid the expensive interlocked compare // and exchange. if (winsock_state == WS_INITIALIZED) return; else init_winsock_worker (); } struct WinSockInitializer { ~WinSockInitializer () { if (winsock_state == WS_INITIALIZED) WSACleanup (); } static WinSockInitializer winSockInitializer; }; WinSockInitializer WinSockInitializer::winSockInitializer; } // namespace namespace log4cplus { namespace helpers { ///////////////////////////////////////////////////////////////////////////// // Global Methods ///////////////////////////////////////////////////////////////////////////// SOCKET_TYPE openSocket(unsigned short port, SocketState& state) { struct sockaddr_in server; init_winsock (); SOCKET sock = WSASocket (AF_INET, SOCK_STREAM, AF_UNSPEC, 0, 0 #if defined (WSA_FLAG_NO_HANDLE_INHERIT) , WSA_FLAG_NO_HANDLE_INHERIT #else , 0 #endif ); if (sock == INVALID_OS_SOCKET_VALUE) goto error; server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(port); if (bind(sock, reinterpret_cast<struct sockaddr*>(&server), sizeof(server)) != 0) goto error; if (::listen(sock, 10) != 0) goto error; state = ok; return to_log4cplus_socket (sock); error: int eno = WSAGetLastError (); if (sock != INVALID_OS_SOCKET_VALUE) ::closesocket (sock); set_last_socket_error (eno); return INVALID_SOCKET_VALUE; } SOCKET_TYPE connectSocket(const tstring& hostn, unsigned short port, bool udp, SocketState& state) { struct hostent * hp; struct sockaddr_in insock; int retval; init_winsock (); SOCKET sock = WSASocket (AF_INET, (udp ? SOCK_DGRAM : SOCK_STREAM), AF_UNSPEC, 0, 0 #if defined (WSA_FLAG_NO_HANDLE_INHERIT) , WSA_FLAG_NO_HANDLE_INHERIT #else , 0 #endif ); if (sock == INVALID_OS_SOCKET_VALUE) goto error; hp = ::gethostbyname( LOG4CPLUS_TSTRING_TO_STRING(hostn).c_str() ); if (hp == 0 || hp->h_addrtype != AF_INET) { insock.sin_family = AF_INET; INT insock_size = sizeof (insock); INT ret = WSAStringToAddress (const_cast<LPTSTR>(hostn.c_str ()), AF_INET, 0, reinterpret_cast<struct sockaddr *>(&insock), &insock_size); if (ret == SOCKET_ERROR || insock_size != static_cast<INT>(sizeof (insock))) { state = bad_address; goto error; } } else std::memcpy (&insock.sin_addr, hp->h_addr_list[0], sizeof (insock.sin_addr)); insock.sin_port = htons(port); insock.sin_family = AF_INET; while( (retval = ::connect(sock, (struct sockaddr*)&insock, sizeof(insock))) == -1 && (WSAGetLastError() == WSAEINTR)) ; if (retval == SOCKET_ERROR) goto error; state = ok; return to_log4cplus_socket (sock); error: int eno = WSAGetLastError (); if (sock != INVALID_OS_SOCKET_VALUE) ::closesocket (sock); set_last_socket_error (eno); return INVALID_SOCKET_VALUE; } SOCKET_TYPE acceptSocket(SOCKET_TYPE sock, SocketState & state) { init_winsock (); SOCKET osSocket = to_os_socket (sock); // Check that the socket is ok. int val = 0; int optlen = sizeof (val); int ret = getsockopt (osSocket, SOL_SOCKET, SO_TYPE, reinterpret_cast<char *>(&val), &optlen); if (ret == SOCKET_ERROR) goto error; // Now that we know the socket is working ok we can wait for // either a new connection or for a transition to bad state. while (1) { fd_set readSet; timeval timeout; FD_ZERO (&readSet); FD_SET (osSocket, &readSet); timeout.tv_sec = 0; timeout.tv_usec = 200 * 1000; int selectResponse = ::select (1, &readSet, NULL, NULL, &timeout); if (selectResponse < 0) { DWORD const eno = WSAGetLastError (); if (eno == WSAENOTSOCK || eno == WSAEINVAL) WSASetLastError (ERROR_NO_DATA); goto error; } else if (selectResponse == 0) // Timeout. continue; else if (selectResponse == 1) { SOCKET connected_socket = ::accept (osSocket, NULL, NULL); if (connected_socket != INVALID_OS_SOCKET_VALUE) state = ok; else goto error; return to_log4cplus_socket (connected_socket); } else { helpers::getLogLog ().error ( LOG4CPLUS_TEXT ("unexpected select() return value: ") + helpers::convertIntegerToString (selectResponse)); WSASetLastError (ERROR_UNSUPPORTED_TYPE); goto error; } } error: DWORD eno = WSAGetLastError (); set_last_socket_error (eno); return to_log4cplus_socket (INVALID_SOCKET); } int closeSocket(SOCKET_TYPE sock) { return ::closesocket (to_os_socket (sock)); } long read(SOCKET_TYPE sock, SocketBuffer& buffer) { long res, read = 0; do { res = ::recv(to_os_socket (sock), buffer.getBuffer() + read, static_cast<int>(buffer.getMaxSize() - read), 0); if (res == SOCKET_ERROR) { set_last_socket_error (WSAGetLastError ()); return res; } read += res; } while (read < static_cast<long>(buffer.getMaxSize())); return read; } long write(SOCKET_TYPE sock, const SocketBuffer& buffer) { long ret = ::send (to_os_socket (sock), buffer.getBuffer(), static_cast<int>(buffer.getSize()), 0); if (ret == SOCKET_ERROR) set_last_socket_error (WSAGetLastError ()); return ret; } long write(SOCKET_TYPE sock, const std::string & buffer) { long ret = ::send (to_os_socket (sock), buffer.c_str (), static_cast<int>(buffer.size ()), 0); if (ret == SOCKET_ERROR) set_last_socket_error (WSAGetLastError ()); return ret; } tstring getHostname (bool fqdn) { char const * hostname = "unknown"; int ret; std::vector<char> hn (1024, 0); while (true) { ret = ::gethostname (&hn[0], static_cast<int>(hn.size ()) - 1); if (ret == 0) { hostname = &hn[0]; break; } else if (ret != 0 && WSAGetLastError () == WSAEFAULT) // Out buffer was too short. Retry with buffer twice the size. hn.resize (hn.size () * 2, 0); else break; } if (ret != 0 || (ret == 0 && ! fqdn)) return LOG4CPLUS_STRING_TO_TSTRING (hostname); struct ::hostent * hp = ::gethostbyname (hostname); if (hp) hostname = hp->h_name; return LOG4CPLUS_STRING_TO_TSTRING (hostname); } int setTCPNoDelay (SOCKET_TYPE sock, bool val) { int result; int enabled = static_cast<int>(val); if ((result = setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&enabled),sizeof(enabled))) != 0) { int eno = WSAGetLastError (); set_last_socket_error (eno); } return result; } } } // namespace log4cplus { namespace helpers { #endif // LOG4CPLUS_USE_WINSOCK <commit_msg>socket-win32.cxx: Prevent infinite loop in read() when recv() returns 0.<commit_after>// Module: Log4CPLUS // File: socket-win32.cxx // Created: 4/2003 // Author: Tad E. Smith // // // Copyright 2003-2010 Tad E. Smith // // 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 <log4cplus/config.hxx> #if defined (LOG4CPLUS_USE_WINSOCK) #include <cassert> #include <cerrno> #include <vector> #include <cstring> #include <log4cplus/internal/socket.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/thread/threads.h> #include <log4cplus/helpers/stringhelper.h> ///////////////////////////////////////////////////////////////////////////// // file LOCAL Classes ///////////////////////////////////////////////////////////////////////////// namespace { enum WSInitStates { WS_UNINITIALIZED, WS_INITIALIZING, WS_INITIALIZED }; static WSADATA wsa; static LONG volatile winsock_state = WS_UNINITIALIZED; static void init_winsock_worker () { log4cplus::helpers::LogLog * loglog = log4cplus::helpers::LogLog::getLogLog (); // Try to change the state to WS_INITIALIZING. LONG val = ::InterlockedCompareExchange ( const_cast<LPLONG>(&winsock_state), WS_INITIALIZING, WS_UNINITIALIZED); switch (val) { case WS_UNINITIALIZED: { int ret = WSAStartup (MAKEWORD (2, 2), &wsa); if (ret != 0) { // Revert the state back to WS_UNINITIALIZED to unblock other // threads and let them throw exception. val = ::InterlockedCompareExchange ( const_cast<LPLONG>(&winsock_state), WS_UNINITIALIZED, WS_INITIALIZING); assert (val == WS_INITIALIZING); loglog->error (LOG4CPLUS_TEXT ("Could not initialize WinSock."), true); } // WinSock is initialized, change the state to WS_INITIALIZED. val = ::InterlockedCompareExchange ( const_cast<LPLONG>(&winsock_state), WS_INITIALIZED, WS_INITIALIZING); assert (val == WS_INITIALIZING); return; } case WS_INITIALIZING: // Wait for state change. while (true) { switch (winsock_state) { case WS_INITIALIZED: return; case WS_INITIALIZING: log4cplus::thread::yield (); continue; default: assert (0); loglog->error (LOG4CPLUS_TEXT ("Unknown WinSock state."), true); } } case WS_INITIALIZED: // WinSock is already initialized. return; default: assert (0); loglog->error (LOG4CPLUS_TEXT ("Unknown WinSock state."), true); } } static void init_winsock () { // Quick check first to avoid the expensive interlocked compare // and exchange. if (winsock_state == WS_INITIALIZED) return; else init_winsock_worker (); } struct WinSockInitializer { ~WinSockInitializer () { if (winsock_state == WS_INITIALIZED) WSACleanup (); } static WinSockInitializer winSockInitializer; }; WinSockInitializer WinSockInitializer::winSockInitializer; } // namespace namespace log4cplus { namespace helpers { ///////////////////////////////////////////////////////////////////////////// // Global Methods ///////////////////////////////////////////////////////////////////////////// SOCKET_TYPE openSocket(unsigned short port, SocketState& state) { struct sockaddr_in server; init_winsock (); SOCKET sock = WSASocket (AF_INET, SOCK_STREAM, AF_UNSPEC, 0, 0 #if defined (WSA_FLAG_NO_HANDLE_INHERIT) , WSA_FLAG_NO_HANDLE_INHERIT #else , 0 #endif ); if (sock == INVALID_OS_SOCKET_VALUE) goto error; server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(port); if (bind(sock, reinterpret_cast<struct sockaddr*>(&server), sizeof(server)) != 0) goto error; if (::listen(sock, 10) != 0) goto error; state = ok; return to_log4cplus_socket (sock); error: int eno = WSAGetLastError (); if (sock != INVALID_OS_SOCKET_VALUE) ::closesocket (sock); set_last_socket_error (eno); return INVALID_SOCKET_VALUE; } SOCKET_TYPE connectSocket(const tstring& hostn, unsigned short port, bool udp, SocketState& state) { struct hostent * hp; struct sockaddr_in insock; int retval; init_winsock (); SOCKET sock = WSASocket (AF_INET, (udp ? SOCK_DGRAM : SOCK_STREAM), AF_UNSPEC, 0, 0 #if defined (WSA_FLAG_NO_HANDLE_INHERIT) , WSA_FLAG_NO_HANDLE_INHERIT #else , 0 #endif ); if (sock == INVALID_OS_SOCKET_VALUE) goto error; hp = ::gethostbyname( LOG4CPLUS_TSTRING_TO_STRING(hostn).c_str() ); if (hp == 0 || hp->h_addrtype != AF_INET) { insock.sin_family = AF_INET; INT insock_size = sizeof (insock); INT ret = WSAStringToAddress (const_cast<LPTSTR>(hostn.c_str ()), AF_INET, 0, reinterpret_cast<struct sockaddr *>(&insock), &insock_size); if (ret == SOCKET_ERROR || insock_size != static_cast<INT>(sizeof (insock))) { state = bad_address; goto error; } } else std::memcpy (&insock.sin_addr, hp->h_addr_list[0], sizeof (insock.sin_addr)); insock.sin_port = htons(port); insock.sin_family = AF_INET; while( (retval = ::connect(sock, (struct sockaddr*)&insock, sizeof(insock))) == -1 && (WSAGetLastError() == WSAEINTR)) ; if (retval == SOCKET_ERROR) goto error; state = ok; return to_log4cplus_socket (sock); error: int eno = WSAGetLastError (); if (sock != INVALID_OS_SOCKET_VALUE) ::closesocket (sock); set_last_socket_error (eno); return INVALID_SOCKET_VALUE; } SOCKET_TYPE acceptSocket(SOCKET_TYPE sock, SocketState & state) { init_winsock (); SOCKET osSocket = to_os_socket (sock); // Check that the socket is ok. int val = 0; int optlen = sizeof (val); int ret = getsockopt (osSocket, SOL_SOCKET, SO_TYPE, reinterpret_cast<char *>(&val), &optlen); if (ret == SOCKET_ERROR) goto error; // Now that we know the socket is working ok we can wait for // either a new connection or for a transition to bad state. while (1) { fd_set readSet; timeval timeout; FD_ZERO (&readSet); FD_SET (osSocket, &readSet); timeout.tv_sec = 0; timeout.tv_usec = 200 * 1000; int selectResponse = ::select (1, &readSet, NULL, NULL, &timeout); if (selectResponse < 0) { DWORD const eno = WSAGetLastError (); if (eno == WSAENOTSOCK || eno == WSAEINVAL) WSASetLastError (ERROR_NO_DATA); goto error; } else if (selectResponse == 0) // Timeout. continue; else if (selectResponse == 1) { SOCKET connected_socket = ::accept (osSocket, NULL, NULL); if (connected_socket != INVALID_OS_SOCKET_VALUE) state = ok; else goto error; return to_log4cplus_socket (connected_socket); } else { helpers::getLogLog ().error ( LOG4CPLUS_TEXT ("unexpected select() return value: ") + helpers::convertIntegerToString (selectResponse)); WSASetLastError (ERROR_UNSUPPORTED_TYPE); goto error; } } error: DWORD eno = WSAGetLastError (); set_last_socket_error (eno); return to_log4cplus_socket (INVALID_SOCKET); } int closeSocket(SOCKET_TYPE sock) { return ::closesocket (to_os_socket (sock)); } long read(SOCKET_TYPE sock, SocketBuffer& buffer) { long res, read = 0; os_socket_type const osSocket = to_os_socket (sock); do { res = ::recv(osSocket, buffer.getBuffer() + read, static_cast<int>(buffer.getMaxSize() - read), 0); if (res == SOCKET_ERROR) { set_last_socket_error (WSAGetLastError ()); return res; } // A return of 0 indicates the socket is closed, // return to prevent an infinite loop. if (res == 0) return read; read += res; } while (read < static_cast<long>(buffer.getMaxSize())); return read; } long write(SOCKET_TYPE sock, const SocketBuffer& buffer) { long ret = ::send (to_os_socket (sock), buffer.getBuffer(), static_cast<int>(buffer.getSize()), 0); if (ret == SOCKET_ERROR) set_last_socket_error (WSAGetLastError ()); return ret; } long write(SOCKET_TYPE sock, const std::string & buffer) { long ret = ::send (to_os_socket (sock), buffer.c_str (), static_cast<int>(buffer.size ()), 0); if (ret == SOCKET_ERROR) set_last_socket_error (WSAGetLastError ()); return ret; } tstring getHostname (bool fqdn) { char const * hostname = "unknown"; int ret; std::vector<char> hn (1024, 0); while (true) { ret = ::gethostname (&hn[0], static_cast<int>(hn.size ()) - 1); if (ret == 0) { hostname = &hn[0]; break; } else if (ret != 0 && WSAGetLastError () == WSAEFAULT) // Out buffer was too short. Retry with buffer twice the size. hn.resize (hn.size () * 2, 0); else break; } if (ret != 0 || (ret == 0 && ! fqdn)) return LOG4CPLUS_STRING_TO_TSTRING (hostname); struct ::hostent * hp = ::gethostbyname (hostname); if (hp) hostname = hp->h_name; return LOG4CPLUS_STRING_TO_TSTRING (hostname); } int setTCPNoDelay (SOCKET_TYPE sock, bool val) { int result; int enabled = static_cast<int>(val); if ((result = setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&enabled),sizeof(enabled))) != 0) { int eno = WSAGetLastError (); set_last_socket_error (eno); } return result; } } } // namespace log4cplus { namespace helpers { #endif // LOG4CPLUS_USE_WINSOCK <|endoftext|>
<commit_before>/* * author: Max Kellermann <[email protected]> */ #include "Direct.hxx" #include "Prepared.hxx" #include "system/sigutil.h" #include "system/fd_util.h" #include <inline/compiler.h> #include <assert.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <stdio.h> static void CheckedDup2(int oldfd, int newfd) { if (oldfd < 0) return; if (oldfd == newfd) fd_set_cloexec(oldfd, false); else dup2(oldfd, newfd); } gcc_noreturn static void Exec(const char *path, const PreparedChildProcess &p) { p.refence.Apply(); p.ns.Setup(); p.rlimits.Apply(); constexpr int CONTROL_FILENO = 3; CheckedDup2(p.stdin_fd, STDIN_FILENO); CheckedDup2(p.stdout_fd, STDOUT_FILENO); CheckedDup2(p.stderr_fd, STDERR_FILENO); CheckedDup2(p.control_fd, CONTROL_FILENO); execve(path, const_cast<char *const*>(p.args.raw()), const_cast<char *const*>(p.env.raw())); fprintf(stderr, "failed to execute %s: %s\n", path, strerror(errno)); _exit(EXIT_FAILURE); } struct SpawnChildProcessContext { const PreparedChildProcess &params; const char *path; sigset_t signals; SpawnChildProcessContext(PreparedChildProcess &_params) :params(_params), path(_params.Finish()) {} }; static int spawn_fn(void *_ctx) { auto &ctx = *(SpawnChildProcessContext *)_ctx; install_default_signal_handlers(); leave_signal_section(&ctx.signals); Exec(ctx.path, ctx.params); } pid_t SpawnChildProcess(PreparedChildProcess &&params) { int clone_flags = SIGCHLD; clone_flags = params.ns.GetCloneFlags(clone_flags); SpawnChildProcessContext ctx(params); /* avoid race condition due to libevent signal handler in child process */ enter_signal_section(&ctx.signals); char stack[8192]; long pid = clone(spawn_fn, stack + sizeof(stack), clone_flags, &ctx); if (pid < 0) { int e = errno; leave_signal_section(&ctx.signals); return -e; } leave_signal_section(&ctx.signals); return pid; } <commit_msg>spawn/Direct: simplify error code path<commit_after>/* * author: Max Kellermann <[email protected]> */ #include "Direct.hxx" #include "Prepared.hxx" #include "system/sigutil.h" #include "system/fd_util.h" #include <inline/compiler.h> #include <assert.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <stdio.h> static void CheckedDup2(int oldfd, int newfd) { if (oldfd < 0) return; if (oldfd == newfd) fd_set_cloexec(oldfd, false); else dup2(oldfd, newfd); } gcc_noreturn static void Exec(const char *path, const PreparedChildProcess &p) { p.refence.Apply(); p.ns.Setup(); p.rlimits.Apply(); constexpr int CONTROL_FILENO = 3; CheckedDup2(p.stdin_fd, STDIN_FILENO); CheckedDup2(p.stdout_fd, STDOUT_FILENO); CheckedDup2(p.stderr_fd, STDERR_FILENO); CheckedDup2(p.control_fd, CONTROL_FILENO); execve(path, const_cast<char *const*>(p.args.raw()), const_cast<char *const*>(p.env.raw())); fprintf(stderr, "failed to execute %s: %s\n", path, strerror(errno)); _exit(EXIT_FAILURE); } struct SpawnChildProcessContext { const PreparedChildProcess &params; const char *path; sigset_t signals; SpawnChildProcessContext(PreparedChildProcess &_params) :params(_params), path(_params.Finish()) {} }; static int spawn_fn(void *_ctx) { auto &ctx = *(SpawnChildProcessContext *)_ctx; install_default_signal_handlers(); leave_signal_section(&ctx.signals); Exec(ctx.path, ctx.params); } pid_t SpawnChildProcess(PreparedChildProcess &&params) { int clone_flags = SIGCHLD; clone_flags = params.ns.GetCloneFlags(clone_flags); SpawnChildProcessContext ctx(params); /* avoid race condition due to libevent signal handler in child process */ enter_signal_section(&ctx.signals); char stack[8192]; long pid = clone(spawn_fn, stack + sizeof(stack), clone_flags, &ctx); if (pid < 0) pid = -errno; leave_signal_section(&ctx.signals); return pid; } <|endoftext|>
<commit_before>/* Copyright (c) 2017, EPL-Vizards * 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 EPL-Vizards 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 EPL-Vizards 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. */ /*! * \file TimeLineModel.cpp */ #include "TimeLineModel.hpp" #include "MainWindow.hpp" #include "PlotCreator.hpp" #include "TimeLineWidget.hpp" using namespace EPL_Viz; using namespace EPL_DataCollect; TimeLineModel::TimeLineModel(MainWindow *mw, QwtPlot *widget) : QwtBaseModel(mw, widget) { (void)mw; (void)widget; viewportSize = DEF_VIEWPORT_SIZE; widget->setAxisAutoScale(QwtPlot::xTop, false); zoomer = std::make_unique<TimeLineMagnifier>(&maxXValue, widget->canvas()); zoomer->setAxisEnabled(QwtPlot::xTop, QwtPlot::yRight); // connect(mw->findChild<TimelineWidget *>("dockTime"), SIGNAL(zoom(QPoint)), this, SLOT(zoom(QPoint))); widget->setAxisScale(QwtPlot::yLeft, 0, 10); widget->setAxisAutoScale(QwtPlot::yLeft, true); widget->setAxisAutoScale(QwtPlot::xTop, false); widget->setAxisScale(QwtPlot::xTop, 0, DEF_VIEWPORT_SIZE, 1); resetAxes(); } TimeLineModel::~TimeLineModel() {} void TimeLineModel::init() { markers.clear(); viewportSize = DEF_VIEWPORT_SIZE; curCycleMarker.setLineStyle(QwtPlotMarker::VLine); curCycleMarker.setLinePen(QColor(0, 0, 0), 2, Qt::PenStyle::DotLine); curCycleMarker.setXAxis(QwtPlot::xTop); curCycleMarker.setXValue(static_cast<double>(0)); curCycleMarker.setLabel(QwtText("View")); curCycleMarker.attach(plot); newestCycleMarker.setLineStyle(QwtPlotMarker::VLine); newestCycleMarker.setLinePen(QColor(255, 0, 0), 2, Qt::PenStyle::DotLine); newestCycleMarker.setXAxis(QwtPlot::xTop); newestCycleMarker.setXValue(static_cast<double>(0)); newestCycleMarker.setLabel(QwtText("Backend")); newestCycleMarker.attach(plot); zoomer = std::make_unique<TimeLineMagnifier>(&maxXValue, plot->canvas()); zoomer->setAxisEnabled(QwtPlot::xTop, true); zoomer->setAxisEnabled(QwtPlot::yLeft, false); log = getMainWindow()->getCaptureInstance()->getEventLog(); appid = log->getAppID(); QwtBaseModel::init(); } void TimeLineModel::update(ProtectedCycle &cycle) { // Change cyclemarker position uint32_t cycleNum = window->getCycleNum(); if (cycleNum == UINT32_MAX) cycleNum = cycle->getCycleNum(); curCycleMarker.setXValue(static_cast<double>(cycleNum)); // Set newest Cycle marker uint32_t newest = window->getCaptureInstance()->getCycleContainer()->pollCycle().getCycleNum(); newestCycleMarker.setXValue(static_cast<double>(newest)); maxXValue = newest; // Add new markers std::vector<EventBase *> nEvents = log->pollEvents(appid); for (EventBase *ev : nEvents) { std::shared_ptr<QwtPlotMarker> marker = std::make_shared<QwtPlotMarker>(QString::fromStdString(ev->getDescription())); marker->setLineStyle(QwtPlotMarker::VLine); marker->setLabel(QString::fromStdString(ev->getName())); uint32_t x; ev->getCycleRange(&x); marker->setXValue(static_cast<double>(x)); marker->attach(plot); markers.append(marker); } QwtBaseModel::update(cycle); } void TimeLineModel::updateViewport(int value) { int64_t nmin = (static_cast<int64_t>(value) - viewportSize / 2); int64_t nmax = (static_cast<int64_t>(value) + viewportSize / 2); if (nmin < 0) { nmax += std::abs(nmin); nmin = 0; } if (nmax > maxXValue) { nmin -= (nmax - maxXValue); nmax = maxXValue; } // qDebug() << "Changing viewport to [" + QString::number(nmin) + "-" + QString::number(nmax) + "]"; postToThread([&] { plot->setAxisScale(plot->xTop, static_cast<double>(nmin), static_cast<double>(nmax), 1); }, plot); replot(); } /* void TimeLineModel::zoom(QPoint angle) { // zoomer->zoom(angle.y()); qDebug() << "Wrong zoom called"; int size = 10; double oldLower = plot->axisScaleDiv(QwtPlot::xTop).lowerBound(); double oldUpper = plot->axisScaleDiv(QwtPlot::xTop).upperBound(); double newLower = oldLower; double newUpper = oldUpper; newLower -= size * angle.y(); newUpper += size * angle.y(); if (newLower < 0) newLower = 0; if (newLower > maxXValue) newLower = maxXValue; if (newUpper < 0) newLower = 0; if (newUpper > maxXValue) newUpper = maxXValue; plot->setAxisScale(plot->xTop, newLower, newUpper); plot->replot(); emit requestRedraw(); } */ void TimeLineModel::resetAxes() { // plot->setAxisMaxMajor(QwtPlot::xTop, 1); postToThread([&] { plot->setAxisMaxMinor(QwtPlot::xTop, 0); }, plot); postToThread([&] { plot->setAxisScale(QwtPlot::xTop, 0, maxXValue); }, plot); } <commit_msg>Added colors to Timelinemarkers<commit_after>/* Copyright (c) 2017, EPL-Vizards * 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 EPL-Vizards 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 EPL-Vizards 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. */ /*! * \file TimeLineModel.cpp */ #include "TimeLineModel.hpp" #include "MainWindow.hpp" #include "PlotCreator.hpp" #include "TimeLineWidget.hpp" using namespace EPL_Viz; using namespace EPL_DataCollect; TimeLineModel::TimeLineModel(MainWindow *mw, QwtPlot *widget) : QwtBaseModel(mw, widget) { (void)mw; (void)widget; viewportSize = DEF_VIEWPORT_SIZE; widget->setAxisAutoScale(QwtPlot::xTop, false); zoomer = std::make_unique<TimeLineMagnifier>(&maxXValue, widget->canvas()); zoomer->setAxisEnabled(QwtPlot::xTop, QwtPlot::yRight); // connect(mw->findChild<TimelineWidget *>("dockTime"), SIGNAL(zoom(QPoint)), this, SLOT(zoom(QPoint))); widget->setAxisScale(QwtPlot::yLeft, 0, 10); widget->setAxisAutoScale(QwtPlot::yLeft, true); widget->setAxisAutoScale(QwtPlot::xTop, false); widget->setAxisScale(QwtPlot::xTop, 0, DEF_VIEWPORT_SIZE, 1); resetAxes(); } TimeLineModel::~TimeLineModel() {} void TimeLineModel::init() { markers.clear(); viewportSize = DEF_VIEWPORT_SIZE; curCycleMarker.setLineStyle(QwtPlotMarker::VLine); curCycleMarker.setLinePen(QColor(0, 0, 0), 2, Qt::PenStyle::DotLine); curCycleMarker.setXAxis(QwtPlot::xTop); curCycleMarker.setXValue(static_cast<double>(0)); curCycleMarker.setLabel(QwtText("View")); curCycleMarker.attach(plot); newestCycleMarker.setLineStyle(QwtPlotMarker::VLine); newestCycleMarker.setLinePen(QColor(255, 0, 0), 2, Qt::PenStyle::DotLine); newestCycleMarker.setXAxis(QwtPlot::xTop); newestCycleMarker.setXValue(static_cast<double>(0)); newestCycleMarker.setLabel(QwtText("Backend")); newestCycleMarker.attach(plot); zoomer = std::make_unique<TimeLineMagnifier>(&maxXValue, plot->canvas()); zoomer->setAxisEnabled(QwtPlot::xTop, true); zoomer->setAxisEnabled(QwtPlot::yLeft, false); log = getMainWindow()->getCaptureInstance()->getEventLog(); appid = log->getAppID(); QwtBaseModel::init(); } void TimeLineModel::update(ProtectedCycle &cycle) { // Change cyclemarker position uint32_t cycleNum = window->getCycleNum(); if (cycleNum == UINT32_MAX) cycleNum = cycle->getCycleNum(); curCycleMarker.setXValue(static_cast<double>(cycleNum)); // Set newest Cycle marker uint32_t newest = window->getCaptureInstance()->getCycleContainer()->pollCycle().getCycleNum(); newestCycleMarker.setXValue(static_cast<double>(newest)); maxXValue = newest; // Add new markers std::vector<EventBase *> nEvents = log->pollEvents(appid); qDebug() << "number of new Events to timeline: " + QString::number(nEvents.size()); for (EventBase *ev : nEvents) { std::shared_ptr<QwtPlotMarker> marker = std::make_shared<QwtPlotMarker>(QString::fromStdString(ev->getDescription())); marker->setLineStyle(QwtPlotMarker::VLine); QColor col; switch (ev->getType()) { case EvType::ERROR: col = QColor(200, 0, 0); break; case EvType::WARNING: col = QColor(250, 250, 0); break; case EvType::INFO: col = QColor(0, 200, 0); break; default: col = QColor(0, 0, 0); } marker->setLinePen(col); uint32_t x; ev->getCycleRange(&x); marker->setXValue(static_cast<double>(x)); marker->attach(plot); markers.append(marker); } QwtBaseModel::update(cycle); } void TimeLineModel::updateViewport(int value) { int64_t nmin = (static_cast<int64_t>(value) - viewportSize / 2); int64_t nmax = (static_cast<int64_t>(value) + viewportSize / 2); if (nmin < 0) { nmax += std::abs(nmin); nmin = 0; } if (nmax > maxXValue) { nmin -= (nmax - maxXValue); nmax = maxXValue; } // qDebug() << "Changing viewport to [" + QString::number(nmin) + "-" + QString::number(nmax) + "]"; postToThread([&] { plot->setAxisScale(plot->xTop, static_cast<double>(nmin), static_cast<double>(nmax), 1); }, plot); replot(); } /* void TimeLineModel::zoom(QPoint angle) { // zoomer->zoom(angle.y()); qDebug() << "Wrong zoom called"; int size = 10; double oldLower = plot->axisScaleDiv(QwtPlot::xTop).lowerBound(); double oldUpper = plot->axisScaleDiv(QwtPlot::xTop).upperBound(); double newLower = oldLower; double newUpper = oldUpper; newLower -= size * angle.y(); newUpper += size * angle.y(); if (newLower < 0) newLower = 0; if (newLower > maxXValue) newLower = maxXValue; if (newUpper < 0) newLower = 0; if (newUpper > maxXValue) newUpper = maxXValue; plot->setAxisScale(plot->xTop, newLower, newUpper); plot->replot(); emit requestRedraw(); } */ void TimeLineModel::resetAxes() { // plot->setAxisMaxMajor(QwtPlot::xTop, 1); postToThread([&] { plot->setAxisMaxMinor(QwtPlot::xTop, 0); }, plot); postToThread([&] { plot->setAxisScale(QwtPlot::xTop, 0, maxXValue); }, plot); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include <svx/svxids.hrc> //-> Fonts & Items #include <vcl/font.hxx> #include <editeng/fontitem.hxx> #include <editeng/fhgtitem.hxx> #include <editeng/wghtitem.hxx> #include <editeng/udlnitem.hxx> #include <editeng/crsditem.hxx> #include <editeng/postitem.hxx> #include <editeng/cntritem.hxx> #include <editeng/shdditem.hxx> //<- Fonts & Items #include <editeng/bulitem.hxx> #include <editeng/brshitem.hxx> #include <vcl/graph.hxx> #include <svl/itemset.hxx> #include <svl/itempool.hxx> #include <editeng/numitem.hxx> #include <editeng/eeitem.hxx> #include "bulmaper.hxx" #define GetWhich(nSlot) rSet.GetPool()->GetWhich( nSlot ) void SdBulletMapper::MapFontsInNumRule( SvxNumRule& aNumRule, const SfxItemSet& rSet ) { const sal_uInt16 nCount = aNumRule.GetLevelCount(); for( sal_uInt16 nLevel = 0; nLevel < nCount; nLevel++ ) { const SvxNumberFormat& rSrcLevel = aNumRule.GetLevel(nLevel); SvxNumberFormat aNewLevel( rSrcLevel ); if(rSrcLevel.GetNumberingType() != com::sun::star::style::NumberingType::CHAR_SPECIAL && rSrcLevel.GetNumberingType() != com::sun::star::style::NumberingType::NUMBER_NONE ) { // wenn Aufzaehlung statt Bullet gewaehlt wurde, wird der Bullet-Font // dem Vorlagen-Font angeglichen // to be implemented if module supports CJK long nFontID = SID_ATTR_CHAR_FONT; long nFontHeightID = SID_ATTR_CHAR_FONTHEIGHT; long nWeightID = SID_ATTR_CHAR_WEIGHT; long nPostureID = SID_ATTR_CHAR_POSTURE; if( 0 ) { nFontID = EE_CHAR_FONTINFO_CJK; nFontHeightID = EE_CHAR_FONTHEIGHT_CJK; nWeightID = EE_CHAR_WEIGHT_CJK; nPostureID = EE_CHAR_ITALIC_CJK; } else if( 0 ) { nFontID = EE_CHAR_FONTINFO_CTL; nFontHeightID = EE_CHAR_FONTHEIGHT_CTL; nWeightID = EE_CHAR_WEIGHT_CTL; nPostureID = EE_CHAR_ITALIC_CTL; } Font aMyFont; const SvxFontItem& rFItem = (SvxFontItem&)rSet.Get(GetWhich( (sal_uInt16)nFontID )); aMyFont.SetFamily(rFItem.GetFamily()); aMyFont.SetName(rFItem.GetFamilyName()); aMyFont.SetCharSet(rFItem.GetCharSet()); aMyFont.SetPitch(rFItem.GetPitch()); const SvxFontHeightItem& rFHItem = (SvxFontHeightItem&)rSet.Get(GetWhich( (sal_uInt16)nFontHeightID )); aMyFont.SetSize(Size(0, rFHItem.GetHeight())); const SvxWeightItem& rWItem = (SvxWeightItem&)rSet.Get(GetWhich( (sal_uInt16)nWeightID )); aMyFont.SetWeight(rWItem.GetWeight()); const SvxPostureItem& rPItem = (SvxPostureItem&)rSet.Get(GetWhich( (sal_uInt16)nPostureID )); aMyFont.SetItalic(rPItem.GetPosture()); const SvxUnderlineItem& rUItem = (SvxUnderlineItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_UNDERLINE)); aMyFont.SetUnderline(rUItem.GetLineStyle()); const SvxOverlineItem& rOItem = (SvxOverlineItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_OVERLINE)); aMyFont.SetOverline(rOItem.GetLineStyle()); const SvxCrossedOutItem& rCOItem = (SvxCrossedOutItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_STRIKEOUT)); aMyFont.SetStrikeout(rCOItem.GetStrikeout()); const SvxContourItem& rCItem = (SvxContourItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_CONTOUR)); aMyFont.SetOutline(rCItem.GetValue()); const SvxShadowedItem& rSItem = (SvxShadowedItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_SHADOWED)); aMyFont.SetShadow(rSItem.GetValue()); aNewLevel.SetBulletFont(&aMyFont); aNumRule.SetLevel(nLevel, aNewLevel ); } else if( rSrcLevel.GetNumberingType() == com::sun::star::style::NumberingType::CHAR_SPECIAL ) { String aEmpty; aNewLevel.SetPrefix( aEmpty ); aNewLevel.SetSuffix( aEmpty ); aNumRule.SetLevel(nLevel, aNewLevel ); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>remove this TODO created in 2000<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include <svx/svxids.hrc> //-> Fonts & Items #include <vcl/font.hxx> #include <editeng/fontitem.hxx> #include <editeng/fhgtitem.hxx> #include <editeng/wghtitem.hxx> #include <editeng/udlnitem.hxx> #include <editeng/crsditem.hxx> #include <editeng/postitem.hxx> #include <editeng/cntritem.hxx> #include <editeng/shdditem.hxx> //<- Fonts & Items #include <editeng/bulitem.hxx> #include <editeng/brshitem.hxx> #include <vcl/graph.hxx> #include <svl/itemset.hxx> #include <svl/itempool.hxx> #include <editeng/numitem.hxx> #include <editeng/eeitem.hxx> #include "bulmaper.hxx" #define GetWhich(nSlot) rSet.GetPool()->GetWhich( nSlot ) void SdBulletMapper::MapFontsInNumRule( SvxNumRule& aNumRule, const SfxItemSet& rSet ) { const sal_uInt16 nCount = aNumRule.GetLevelCount(); for( sal_uInt16 nLevel = 0; nLevel < nCount; nLevel++ ) { const SvxNumberFormat& rSrcLevel = aNumRule.GetLevel(nLevel); SvxNumberFormat aNewLevel( rSrcLevel ); if(rSrcLevel.GetNumberingType() != com::sun::star::style::NumberingType::CHAR_SPECIAL && rSrcLevel.GetNumberingType() != com::sun::star::style::NumberingType::NUMBER_NONE ) { // wenn Aufzaehlung statt Bullet gewaehlt wurde, wird der Bullet-Font // dem Vorlagen-Font angeglichen // to be implemented if module supports CJK long nFontID = SID_ATTR_CHAR_FONT; long nFontHeightID = SID_ATTR_CHAR_FONTHEIGHT; long nWeightID = SID_ATTR_CHAR_WEIGHT; long nPostureID = SID_ATTR_CHAR_POSTURE; Font aMyFont; const SvxFontItem& rFItem = (SvxFontItem&)rSet.Get(GetWhich( (sal_uInt16)nFontID )); aMyFont.SetFamily(rFItem.GetFamily()); aMyFont.SetName(rFItem.GetFamilyName()); aMyFont.SetCharSet(rFItem.GetCharSet()); aMyFont.SetPitch(rFItem.GetPitch()); const SvxFontHeightItem& rFHItem = (SvxFontHeightItem&)rSet.Get(GetWhich( (sal_uInt16)nFontHeightID )); aMyFont.SetSize(Size(0, rFHItem.GetHeight())); const SvxWeightItem& rWItem = (SvxWeightItem&)rSet.Get(GetWhich( (sal_uInt16)nWeightID )); aMyFont.SetWeight(rWItem.GetWeight()); const SvxPostureItem& rPItem = (SvxPostureItem&)rSet.Get(GetWhich( (sal_uInt16)nPostureID )); aMyFont.SetItalic(rPItem.GetPosture()); const SvxUnderlineItem& rUItem = (SvxUnderlineItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_UNDERLINE)); aMyFont.SetUnderline(rUItem.GetLineStyle()); const SvxOverlineItem& rOItem = (SvxOverlineItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_OVERLINE)); aMyFont.SetOverline(rOItem.GetLineStyle()); const SvxCrossedOutItem& rCOItem = (SvxCrossedOutItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_STRIKEOUT)); aMyFont.SetStrikeout(rCOItem.GetStrikeout()); const SvxContourItem& rCItem = (SvxContourItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_CONTOUR)); aMyFont.SetOutline(rCItem.GetValue()); const SvxShadowedItem& rSItem = (SvxShadowedItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_SHADOWED)); aMyFont.SetShadow(rSItem.GetValue()); aNewLevel.SetBulletFont(&aMyFont); aNumRule.SetLevel(nLevel, aNewLevel ); } else if( rSrcLevel.GetNumberingType() == com::sun::star::style::NumberingType::CHAR_SPECIAL ) { String aEmpty; aNewLevel.SetPrefix( aEmpty ); aNewLevel.SetSuffix( aEmpty ); aNumRule.SetLevel(nLevel, aNewLevel ); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if !defined(_MSC_VER) #ifdef __linux__ // Linux #include <freetype/ftoutln.h> #include <ft2build.h> #include FT_FREETYPE_H #else // Mac OS X #include <ApplicationServices/ApplicationServices.h> // g++ -framework Cocoa #endif // __linux__ #else // Windows // TODO(yusukes): Support Windows. #endif // _MSC_VER #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include <cstdio> #include <cstdlib> #include <cstring> #include "opentype-sanitiser.h" #include "ots-memory-stream.h" namespace { int Usage(const char *argv0) { std::fprintf(stderr, "Usage: %s <ttf file>\n", argv0); return 1; } } // namespace int main(int argc, char **argv) { if (argc != 2) return Usage(argv[0]); const int fd = ::open(argv[1], O_RDONLY); if (fd < 0) { ::perror("open"); return 1; } struct stat st; ::fstat(fd, &st); uint8_t *data = new uint8_t[st.st_size]; if (::read(fd, data, st.st_size) != st.st_size) { ::close(fd); std::fprintf(stderr, "Failed to read file!\n"); return 1; } ::close(fd); // A transcoded font is usually smaller than an original font. // However, it can be slightly bigger than the original one due to // name table replacement and/or padding for glyf table. // // However, a WOFF font gets decompressed and so can be *much* larger than // the original. uint8_t *result = new uint8_t[st.st_size * 8]; ots::MemoryStream output(result, st.st_size * 8); bool r = ots::Process(&output, data, st.st_size); if (!r) { std::fprintf(stderr, "Failed to sanitise file!\n"); return 1; } const size_t result_len = output.Tell(); free(data); uint8_t *result2 = new uint8_t[result_len]; ots::MemoryStream output2(result2, result_len); r = ots::Process(&output2, result, result_len); if (!r) { std::fprintf(stderr, "Failed to sanitise previous output!\n"); return 1; } const size_t result2_len = output2.Tell(); bool dump_results = false; if (result2_len != result_len) { std::fprintf(stderr, "Outputs differ in length\n"); dump_results = true; } else if (std::memcmp(result2, result, result_len)) { std::fprintf(stderr, "Outputs differ in content\n"); dump_results = true; } if (dump_results) { std::fprintf(stderr, "Dumping results to out1.tff and out2.tff\n"); int fd1 = ::open("out1.ttf", O_WRONLY | O_CREAT | O_TRUNC, 0600); int fd2 = ::open("out2.ttf", O_WRONLY | O_CREAT | O_TRUNC, 0600); if (fd1 < 0 || fd2 < 0) { ::perror("opening output file"); return 1; } if ((::write(fd1, result, result_len) < 0) || (::write(fd2, result2, result2_len) < 0)) { ::perror("writing output file"); return 1; } } // Verify that the transcoded font can be opened by the font renderer for // Linux (FreeType2), Mac OS X, or Windows. #if !defined(_MSC_VER) #ifdef __linux__ // Linux FT_Library library; FT_Error error = ::FT_Init_FreeType(&library); if (error) { std::fprintf(stderr, "Failed to initialize FreeType2!\n"); return 1; } FT_Face dummy; error = ::FT_New_Memory_Face(library, result, result_len, 0, &dummy); if (error) { std::fprintf(stderr, "Failed to open the transcoded font\n"); return 1; } #else // Mac OS X ATSFontContainerRef container_ref = 0; ATSFontActivateFromMemory(result, result_len, 3, kATSFontFormatUnspecified, NULL, kATSOptionFlagsDefault, &container_ref); if (!container_ref) { std::fprintf(stderr, "Failed to open the transcoded font\n"); return 1; } ItemCount count; ATSFontFindFromContainer( container_ref, kATSOptionFlagsDefault, 0, NULL, &count); if (!count) { std::fprintf(stderr, "Failed to open the transcoded font\n"); return 1; } ATSFontRef ats_font_ref = 0; ATSFontFindFromContainer( container_ref, kATSOptionFlagsDefault, 1, &ats_font_ref, NULL); if (!ats_font_ref) { std::fprintf(stderr, "Failed to open the transcoded font\n"); return 1; } CGFontRef cg_font_ref = CGFontCreateWithPlatformFont(&ats_font_ref); if (!CGFontGetNumberOfGlyphs(cg_font_ref)) { std::fprintf(stderr, "Failed to open the transcoded font\n"); return 1; } #endif // __linux__ #else // Windows // TODO(yusukes): Support Windows. #endif // _MSC_VER return 0; } <commit_msg>Strict check for FDSelect in the CFF table<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if !defined(_MSC_VER) #ifdef __linux__ // Linux #include <freetype/ftoutln.h> #include <ft2build.h> #include FT_FREETYPE_H #else // Mac OS X #include <ApplicationServices/ApplicationServices.h> // g++ -framework Cocoa #endif // __linux__ #else // Windows // TODO(yusukes): Support Windows. #endif // _MSC_VER #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include <cstdio> #include <cstdlib> #include <cstring> #include "opentype-sanitiser.h" #include "ots-memory-stream.h" namespace { int Usage(const char *argv0) { std::fprintf(stderr, "Usage: %s <ttf file>\n", argv0); return 1; } } // namespace int main(int argc, char **argv) { if (argc != 2) return Usage(argv[0]); const int fd = ::open(argv[1], O_RDONLY); if (fd < 0) { ::perror("open"); return 1; } struct stat st; ::fstat(fd, &st); uint8_t *data = new uint8_t[st.st_size]; if (::read(fd, data, st.st_size) != st.st_size) { ::close(fd); std::fprintf(stderr, "Failed to read file!\n"); return 1; } ::close(fd); // A transcoded font is usually smaller than an original font. // However, it can be slightly bigger than the original one due to // name table replacement and/or padding for glyf table. // // However, a WOFF font gets decompressed and so can be *much* larger than // the original. uint8_t *result = new uint8_t[st.st_size * 8]; ots::MemoryStream output(result, st.st_size * 8); bool r = ots::Process(&output, data, st.st_size); if (!r) { std::fprintf(stderr, "Failed to sanitise file!\n"); return 1; } const size_t result_len = output.Tell(); delete[] data; uint8_t *result2 = new uint8_t[result_len]; ots::MemoryStream output2(result2, result_len); r = ots::Process(&output2, result, result_len); if (!r) { std::fprintf(stderr, "Failed to sanitise previous output!\n"); return 1; } const size_t result2_len = output2.Tell(); bool dump_results = false; if (result2_len != result_len) { std::fprintf(stderr, "Outputs differ in length\n"); dump_results = true; } else if (std::memcmp(result2, result, result_len)) { std::fprintf(stderr, "Outputs differ in content\n"); dump_results = true; } if (dump_results) { std::fprintf(stderr, "Dumping results to out1.tff and out2.tff\n"); int fd1 = ::open("out1.ttf", O_WRONLY | O_CREAT | O_TRUNC, 0600); int fd2 = ::open("out2.ttf", O_WRONLY | O_CREAT | O_TRUNC, 0600); if (fd1 < 0 || fd2 < 0) { ::perror("opening output file"); return 1; } if ((::write(fd1, result, result_len) < 0) || (::write(fd2, result2, result2_len) < 0)) { ::perror("writing output file"); return 1; } } // Verify that the transcoded font can be opened by the font renderer for // Linux (FreeType2), Mac OS X, or Windows. #if !defined(_MSC_VER) #ifdef __linux__ // Linux FT_Library library; FT_Error error = ::FT_Init_FreeType(&library); if (error) { std::fprintf(stderr, "Failed to initialize FreeType2!\n"); return 1; } FT_Face dummy; error = ::FT_New_Memory_Face(library, result, result_len, 0, &dummy); if (error) { std::fprintf(stderr, "Failed to open the transcoded font\n"); return 1; } #else // Mac OS X ATSFontContainerRef container_ref = 0; ATSFontActivateFromMemory(result, result_len, 3, kATSFontFormatUnspecified, NULL, kATSOptionFlagsDefault, &container_ref); if (!container_ref) { std::fprintf(stderr, "Failed to open the transcoded font\n"); return 1; } ItemCount count; ATSFontFindFromContainer( container_ref, kATSOptionFlagsDefault, 0, NULL, &count); if (!count) { std::fprintf(stderr, "Failed to open the transcoded font\n"); return 1; } ATSFontRef ats_font_ref = 0; ATSFontFindFromContainer( container_ref, kATSOptionFlagsDefault, 1, &ats_font_ref, NULL); if (!ats_font_ref) { std::fprintf(stderr, "Failed to open the transcoded font\n"); return 1; } CGFontRef cg_font_ref = CGFontCreateWithPlatformFont(&ats_font_ref); if (!CGFontGetNumberOfGlyphs(cg_font_ref)) { std::fprintf(stderr, "Failed to open the transcoded font\n"); return 1; } #endif // __linux__ #else // Windows // TODO(yusukes): Support Windows. #endif // _MSC_VER return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fudspord.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 04:41:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #include "fudspord.hxx" #include <svx/svxids.hrc> #ifndef _VCL_POINTR_HXX //autogen #include <vcl/pointr.hxx> #endif #include "app.hrc" #ifndef SD_FU_POOR_HXX #include "fupoor.hxx" #endif #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SD_WINDOW_SHELL_HXX #include "Window.hxx" #endif #include "drawdoc.hxx" namespace sd { TYPEINIT1( FuDisplayOrder, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuDisplayOrder::FuDisplayOrder ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuPoor(pViewSh, pWin, pView, pDoc, rReq), pUserMarker(NULL), pRefObj(NULL) { pUserMarker = new SdrViewUserMarker(pView); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuDisplayOrder::~FuDisplayOrder() { delete pUserMarker; } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL FuDisplayOrder::MouseButtonDown(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); return TRUE; } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL FuDisplayOrder::MouseMove(const MouseEvent& rMEvt) { SdrObject* pPickObj; SdrPageView* pPV; Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); USHORT nHitLog = USHORT ( pWindow->PixelToLogic(Size(HITPIX,0)).Width() ); if ( pView->PickObj(aPnt, pPickObj, pPV) ) { if (pRefObj != pPickObj) { pRefObj = pPickObj; pUserMarker->SetXPolyPolygon(pRefObj, pView->GetPageViewPvNum(0)); pUserMarker->Show(); } } else { pRefObj = NULL; pUserMarker->Hide(); } return TRUE; } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL FuDisplayOrder::MouseButtonUp(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); SdrPageView* pPV = NULL; Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); USHORT nHitLog = USHORT ( pWindow->PixelToLogic(Size(HITPIX,0)).Width() ); if ( pView->PickObj(aPnt, pRefObj, pPV) ) { if (nSlotId == SID_BEFORE_OBJ) { pView->PutMarkedInFrontOfObj(pRefObj); } else { pView->PutMarkedBehindObj(pRefObj); } } pViewShell->Cancel(); return TRUE; } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuDisplayOrder::Activate() { aPtr = pWindow->GetPointer(); pWindow->SetPointer( Pointer( POINTER_REFHAND ) ); if (pUserMarker) { pUserMarker->Show(); } } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuDisplayOrder::Deactivate() { if (pUserMarker) { pUserMarker->Hide(); } pWindow->SetPointer( aPtr ); } } // end of namespace sd <commit_msg>INTEGRATION: CWS impressfunctions (1.4.38); FILE MERGED 2005/10/28 10:57:36 cl 1.4.38.1: #125341# reworked FuPoor classes to use refcounting<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fudspord.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-12-14 16:57:59 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #include "fudspord.hxx" #include <svx/svxids.hrc> #ifndef _VCL_POINTR_HXX //autogen #include <vcl/pointr.hxx> #endif #include "app.hrc" #ifndef SD_FU_POOR_HXX #include "fupoor.hxx" #endif #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SD_WINDOW_SHELL_HXX #include "Window.hxx" #endif #include "drawdoc.hxx" namespace sd { TYPEINIT1( FuDisplayOrder, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuDisplayOrder::FuDisplayOrder ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuPoor(pViewSh, pWin, pView, pDoc, rReq), pUserMarker(NULL), pRefObj(NULL) { pUserMarker = new SdrViewUserMarker(pView); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuDisplayOrder::~FuDisplayOrder() { delete pUserMarker; } FunctionReference FuDisplayOrder::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) { FunctionReference xFunc( new FuDisplayOrder( pViewSh, pWin, pView, pDoc, rReq ) ); return xFunc; } /************************************************************************* |* |* MouseButtonDown-event |* \************************************************************************/ BOOL FuDisplayOrder::MouseButtonDown(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); return TRUE; } /************************************************************************* |* |* MouseMove-event |* \************************************************************************/ BOOL FuDisplayOrder::MouseMove(const MouseEvent& rMEvt) { SdrObject* pPickObj; SdrPageView* pPV; Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); USHORT nHitLog = USHORT ( pWindow->PixelToLogic(Size(HITPIX,0)).Width() ); if ( pView->PickObj(aPnt, pPickObj, pPV) ) { if (pRefObj != pPickObj) { pRefObj = pPickObj; pUserMarker->SetXPolyPolygon(pRefObj, pView->GetPageViewPvNum(0)); pUserMarker->Show(); } } else { pRefObj = NULL; pUserMarker->Hide(); } return TRUE; } /************************************************************************* |* |* MouseButtonUp-event |* \************************************************************************/ BOOL FuDisplayOrder::MouseButtonUp(const MouseEvent& rMEvt) { // #95491# remember button state for creation of own MouseEvents SetMouseButtonCode(rMEvt.GetButtons()); SdrPageView* pPV = NULL; Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) ); USHORT nHitLog = USHORT ( pWindow->PixelToLogic(Size(HITPIX,0)).Width() ); if ( pView->PickObj(aPnt, pRefObj, pPV) ) { if (nSlotId == SID_BEFORE_OBJ) { pView->PutMarkedInFrontOfObj(pRefObj); } else { pView->PutMarkedBehindObj(pRefObj); } } pViewShell->Cancel(); return TRUE; } /************************************************************************* |* |* Function aktivieren |* \************************************************************************/ void FuDisplayOrder::Activate() { aPtr = pWindow->GetPointer(); pWindow->SetPointer( Pointer( POINTER_REFHAND ) ); if (pUserMarker) { pUserMarker->Show(); } } /************************************************************************* |* |* Function deaktivieren |* \************************************************************************/ void FuDisplayOrder::Deactivate() { if (pUserMarker) { pUserMarker->Hide(); } pWindow->SetPointer( aPtr ); } } // end of namespace sd <|endoftext|>
<commit_before>#include "UnitTest++.h" #include "types.h" #include "query.h" #include "queryablehost.h" #include "rtgconf.h" #include "rtgtargets.h" void mock_set_speed(unsigned int newspeed); // From snmp-mock.cpp SUITE(LongTests) { TEST(one_host_one_Mbps_10_secs) { mock_set_speed(1000000 / 8); RTGConf conf("test/example-rtg.conf"); RTGTargets hosts("test/example-targets.cfg", conf); ResultCache cache; QueryableHost qh(hosts[0], cache); std::vector<std::string> queries = qh.get_inserts(); CHECK_EQUAL((size_t)0, queries.size()); // No inserts first iteration sleep(10); queries = qh.get_inserts(); CHECK_EQUAL((size_t)1, queries.size()); // One insert next iteration size_t pos = queries[0].find(", 1250000, 125000)"); CHECK(pos != std::string::npos); pos = queries[0].find(", 1250000, 125000)", pos+1); CHECK(pos != std::string::npos); } TEST(one_host_hundred_Mbps_one_interval) { mock_set_speed(100e6 / 8); RTGConf conf("test/example-rtg.conf"); RTGTargets hosts("test/example-targets.cfg", conf); ResultCache cache; QueryableHost qh(hosts[0], cache); std::vector<std::string> queries = qh.get_inserts(); CHECK_EQUAL((size_t)0, queries.size()); // No inserts first iteration sleep(conf.interval); queries = qh.get_inserts(); CHECK_EQUAL((size_t)0, queries.size()); // No inserts next iteration due to too high speed } } <commit_msg>Avoid float/int warning<commit_after>#include "UnitTest++.h" #include "types.h" #include "query.h" #include "queryablehost.h" #include "rtgconf.h" #include "rtgtargets.h" void mock_set_speed(unsigned int newspeed); // From snmp-mock.cpp SUITE(LongTests) { TEST(one_host_one_Mbps_10_secs) { mock_set_speed(1000000 / 8); RTGConf conf("test/example-rtg.conf"); RTGTargets hosts("test/example-targets.cfg", conf); ResultCache cache; QueryableHost qh(hosts[0], cache); std::vector<std::string> queries = qh.get_inserts(); CHECK_EQUAL((size_t)0, queries.size()); // No inserts first iteration sleep(10); queries = qh.get_inserts(); CHECK_EQUAL((size_t)1, queries.size()); // One insert next iteration size_t pos = queries[0].find(", 1250000, 125000)"); CHECK(pos != std::string::npos); pos = queries[0].find(", 1250000, 125000)", pos+1); CHECK(pos != std::string::npos); } TEST(one_host_hundred_Mbps_one_interval) { mock_set_speed(100000000 / 8); RTGConf conf("test/example-rtg.conf"); RTGTargets hosts("test/example-targets.cfg", conf); ResultCache cache; QueryableHost qh(hosts[0], cache); std::vector<std::string> queries = qh.get_inserts(); CHECK_EQUAL((size_t)0, queries.size()); // No inserts first iteration sleep(conf.interval); queries = qh.get_inserts(); CHECK_EQUAL((size_t)0, queries.size()); // No inserts next iteration due to too high speed } } <|endoftext|>
<commit_before>/* * Copyright 2015 WebAssembly Community Group participants * * 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 "support/file.h" #include <cstdlib> #include <limits> template <typename T> T wasm::read_file(const std::string &filename, Flags::BinaryOption binary, Flags::DebugOption debug) { if (debug == Flags::Debug) std::cerr << "Loading '" << filename << "'..." << std::endl; std::ifstream infile; auto flags = std::ifstream::in; if (binary == Flags::Binary) flags |= std::ifstream::binary; infile.open(filename, flags); if (!infile.is_open()) { std::cerr << "Failed opening '" << filename << "'" << std::endl; exit(EXIT_FAILURE); } infile.seekg(0, std::ios::end); std::streampos insize = infile.tellg(); if (uint64_t(insize) >= std::numeric_limits<size_t>::max()) { // Building a 32-bit executable where size_t == 32 bits, we are not able to create strings larger than 2^32 bytes in length, so must abort here. std::cerr << "Failed opening '" << filename << "': Input file too large: " << insize << " bytes. Try rebuilding in 64-bit mode." << std::endl; exit(EXIT_FAILURE); } T input(size_t(insize) + (binary == Flags::Binary ? 0 : 1), '\0'); infile.seekg(0); infile.read(&input[0], insize); return input; } // Explicit instantiations for the explicit specializations. template std::string wasm::read_file<>(const std::string &, Flags::BinaryOption, Flags::DebugOption); template std::vector<char> wasm::read_file<>(const std::string &, Flags::BinaryOption, Flags::DebugOption); wasm::Output::Output(const std::string &filename, Flags::BinaryOption binary, Flags::DebugOption debug) : outfile(), out([this, filename, binary, debug]() { std::streambuf *buffer; if (filename.size()) { if (debug == Flags::Debug) std::cerr << "Opening '" << filename << std::endl; auto flags = std::ofstream::out | std::ofstream::trunc; if (binary == Flags::Binary) flags |= std::ofstream::binary; outfile.open(filename, flags); if (!outfile.is_open()) { std::cerr << "Failed opening '" << filename << "'" << std::endl; exit(EXIT_FAILURE); } buffer = outfile.rdbuf(); } else { buffer = std::cout.rdbuf(); } return buffer; }()) {} <commit_msg>Changed type of flags to fix Visual Studio 2015 error (#418)<commit_after>/* * Copyright 2015 WebAssembly Community Group participants * * 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 "support/file.h" #include <cstdlib> #include <limits> template <typename T> T wasm::read_file(const std::string &filename, Flags::BinaryOption binary, Flags::DebugOption debug) { if (debug == Flags::Debug) std::cerr << "Loading '" << filename << "'..." << std::endl; std::ifstream infile; std::ios_base::openmode flags = std::ifstream::in; if (binary == Flags::Binary) flags |= std::ifstream::binary; infile.open(filename, flags); if (!infile.is_open()) { std::cerr << "Failed opening '" << filename << "'" << std::endl; exit(EXIT_FAILURE); } infile.seekg(0, std::ios::end); std::streampos insize = infile.tellg(); if (uint64_t(insize) >= std::numeric_limits<size_t>::max()) { // Building a 32-bit executable where size_t == 32 bits, we are not able to create strings larger than 2^32 bytes in length, so must abort here. std::cerr << "Failed opening '" << filename << "': Input file too large: " << insize << " bytes. Try rebuilding in 64-bit mode." << std::endl; exit(EXIT_FAILURE); } T input(size_t(insize) + (binary == Flags::Binary ? 0 : 1), '\0'); infile.seekg(0); infile.read(&input[0], insize); return input; } // Explicit instantiations for the explicit specializations. template std::string wasm::read_file<>(const std::string &, Flags::BinaryOption, Flags::DebugOption); template std::vector<char> wasm::read_file<>(const std::string &, Flags::BinaryOption, Flags::DebugOption); wasm::Output::Output(const std::string &filename, Flags::BinaryOption binary, Flags::DebugOption debug) : outfile(), out([this, filename, binary, debug]() { std::streambuf *buffer; if (filename.size()) { if (debug == Flags::Debug) std::cerr << "Opening '" << filename << std::endl; auto flags = std::ofstream::out | std::ofstream::trunc; if (binary == Flags::Binary) flags |= std::ofstream::binary; outfile.open(filename, flags); if (!outfile.is_open()) { std::cerr << "Failed opening '" << filename << "'" << std::endl; exit(EXIT_FAILURE); } buffer = outfile.rdbuf(); } else { buffer = std::cout.rdbuf(); } return buffer; }()) {} <|endoftext|>
<commit_before>//===---------------------- system_error.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "__config" #define _LIBCPP_BUILDING_SYSTEM_ERROR #include "system_error" #include "include/config_elast.h" #include "cerrno" #include "cstring" #include "cstdio" #include "cstdlib" #include "cassert" #include "string" #include "string.h" #if defined(__ANDROID__) #include <android/api-level.h> #endif _LIBCPP_BEGIN_NAMESPACE_STD // class error_category error_category::error_category() _NOEXCEPT { } error_category::~error_category() _NOEXCEPT { } error_condition error_category::default_error_condition(int ev) const _NOEXCEPT { return error_condition(ev, *this); } bool error_category::equivalent(int code, const error_condition& condition) const _NOEXCEPT { return default_error_condition(code) == condition; } bool error_category::equivalent(const error_code& code, int condition) const _NOEXCEPT { return *this == code.category() && code.value() == condition; } namespace { // GLIBC also uses 1024 as the maximum buffer size internally. constexpr size_t strerror_buff_size = 1024; string do_strerror_r(int ev); #if defined(__linux__) && !defined(_LIBCPP_HAS_MUSL_LIBC) \ && (!defined(__ANDROID__) || __ANDROID_API__ >= 23) // GNU Extended version string do_strerror_r(int ev) { char buffer[strerror_buff_size]; char* ret = ::strerror_r(ev, buffer, strerror_buff_size); return string(ret); } #else // POSIX version string do_strerror_r(int ev) { char buffer[strerror_buff_size]; const int old_errno = errno; int ret; if ((ret = ::strerror_r(ev, buffer, strerror_buff_size)) != 0) { // If `ret == -1` then the error is specified using `errno`, otherwise // `ret` represents the error. const int new_errno = ret == -1 ? errno : ret; errno = old_errno; if (new_errno == EINVAL) { std::snprintf(buffer, strerror_buff_size, "Unknown error %d", ev); return string(buffer); } else { assert(new_errno == ERANGE); // FIXME maybe? 'strerror_buff_size' is likely to exceed the // maximum error size so ERANGE shouldn't be returned. std::abort(); } } return string(buffer); } #endif } // end namespace string __do_message::message(int ev) const { #if defined(_LIBCPP_HAS_NO_THREADS) return string(::strerror(ev)); #else return do_strerror_r(ev); #endif } class _LIBCPP_HIDDEN __generic_error_category : public __do_message { public: virtual const char* name() const _NOEXCEPT; virtual string message(int ev) const; }; const char* __generic_error_category::name() const _NOEXCEPT { return "generic"; } string __generic_error_category::message(int ev) const { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return string("unspecified generic_category error"); #endif // _LIBCPP_ELAST return __do_message::message(ev); } const error_category& generic_category() _NOEXCEPT { static __generic_error_category s; return s; } class _LIBCPP_HIDDEN __system_error_category : public __do_message { public: virtual const char* name() const _NOEXCEPT; virtual string message(int ev) const; virtual error_condition default_error_condition(int ev) const _NOEXCEPT; }; const char* __system_error_category::name() const _NOEXCEPT { return "system"; } string __system_error_category::message(int ev) const { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return string("unspecified system_category error"); #endif // _LIBCPP_ELAST return __do_message::message(ev); } error_condition __system_error_category::default_error_condition(int ev) const _NOEXCEPT { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return error_condition(ev, system_category()); #endif // _LIBCPP_ELAST return error_condition(ev, generic_category()); } const error_category& system_category() _NOEXCEPT { static __system_error_category s; return s; } // error_condition string error_condition::message() const { return __cat_->message(__val_); } // error_code string error_code::message() const { return __cat_->message(__val_); } // system_error string system_error::__init(const error_code& ec, string what_arg) { if (ec) { if (!what_arg.empty()) what_arg += ": "; what_arg += ec.message(); } return what_arg; } system_error::system_error(error_code ec, const string& what_arg) : runtime_error(__init(ec, what_arg)), __ec_(ec) { } system_error::system_error(error_code ec, const char* what_arg) : runtime_error(__init(ec, what_arg)), __ec_(ec) { } system_error::system_error(error_code ec) : runtime_error(__init(ec, "")), __ec_(ec) { } system_error::system_error(int ev, const error_category& ecat, const string& what_arg) : runtime_error(__init(error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) { } system_error::system_error(int ev, const error_category& ecat, const char* what_arg) : runtime_error(__init(error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) { } system_error::system_error(int ev, const error_category& ecat) : runtime_error(__init(error_code(ev, ecat), "")), __ec_(error_code(ev, ecat)) { } system_error::~system_error() _NOEXCEPT { } void __throw_system_error(int ev, const char* what_arg) { #ifndef _LIBCPP_NO_EXCEPTIONS throw system_error(error_code(ev, system_category()), what_arg); #else (void)ev; (void)what_arg; _VSTD::abort(); #endif } _LIBCPP_END_NAMESPACE_STD <commit_msg>system_error: use strerror_r only for threaded code<commit_after>//===---------------------- system_error.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "__config" #define _LIBCPP_BUILDING_SYSTEM_ERROR #include "system_error" #include "include/config_elast.h" #include "cerrno" #include "cstring" #include "cstdio" #include "cstdlib" #include "cassert" #include "string" #include "string.h" #if defined(__ANDROID__) #include <android/api-level.h> #endif _LIBCPP_BEGIN_NAMESPACE_STD // class error_category error_category::error_category() _NOEXCEPT { } error_category::~error_category() _NOEXCEPT { } error_condition error_category::default_error_condition(int ev) const _NOEXCEPT { return error_condition(ev, *this); } bool error_category::equivalent(int code, const error_condition& condition) const _NOEXCEPT { return default_error_condition(code) == condition; } bool error_category::equivalent(const error_code& code, int condition) const _NOEXCEPT { return *this == code.category() && code.value() == condition; } #if !defined(_LIBCPP_HAS_NO_THREADS) namespace { // GLIBC also uses 1024 as the maximum buffer size internally. constexpr size_t strerror_buff_size = 1024; string do_strerror_r(int ev); #if defined(__linux__) && !defined(_LIBCPP_HAS_MUSL_LIBC) \ && (!defined(__ANDROID__) || __ANDROID_API__ >= 23) // GNU Extended version string do_strerror_r(int ev) { char buffer[strerror_buff_size]; char* ret = ::strerror_r(ev, buffer, strerror_buff_size); return string(ret); } #else // POSIX version string do_strerror_r(int ev) { char buffer[strerror_buff_size]; const int old_errno = errno; int ret; if ((ret = ::strerror_r(ev, buffer, strerror_buff_size)) != 0) { // If `ret == -1` then the error is specified using `errno`, otherwise // `ret` represents the error. const int new_errno = ret == -1 ? errno : ret; errno = old_errno; if (new_errno == EINVAL) { std::snprintf(buffer, strerror_buff_size, "Unknown error %d", ev); return string(buffer); } else { assert(new_errno == ERANGE); // FIXME maybe? 'strerror_buff_size' is likely to exceed the // maximum error size so ERANGE shouldn't be returned. std::abort(); } } return string(buffer); } #endif } // end namespace #endif string __do_message::message(int ev) const { #if defined(_LIBCPP_HAS_NO_THREADS) return string(::strerror(ev)); #else return do_strerror_r(ev); #endif } class _LIBCPP_HIDDEN __generic_error_category : public __do_message { public: virtual const char* name() const _NOEXCEPT; virtual string message(int ev) const; }; const char* __generic_error_category::name() const _NOEXCEPT { return "generic"; } string __generic_error_category::message(int ev) const { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return string("unspecified generic_category error"); #endif // _LIBCPP_ELAST return __do_message::message(ev); } const error_category& generic_category() _NOEXCEPT { static __generic_error_category s; return s; } class _LIBCPP_HIDDEN __system_error_category : public __do_message { public: virtual const char* name() const _NOEXCEPT; virtual string message(int ev) const; virtual error_condition default_error_condition(int ev) const _NOEXCEPT; }; const char* __system_error_category::name() const _NOEXCEPT { return "system"; } string __system_error_category::message(int ev) const { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return string("unspecified system_category error"); #endif // _LIBCPP_ELAST return __do_message::message(ev); } error_condition __system_error_category::default_error_condition(int ev) const _NOEXCEPT { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return error_condition(ev, system_category()); #endif // _LIBCPP_ELAST return error_condition(ev, generic_category()); } const error_category& system_category() _NOEXCEPT { static __system_error_category s; return s; } // error_condition string error_condition::message() const { return __cat_->message(__val_); } // error_code string error_code::message() const { return __cat_->message(__val_); } // system_error string system_error::__init(const error_code& ec, string what_arg) { if (ec) { if (!what_arg.empty()) what_arg += ": "; what_arg += ec.message(); } return what_arg; } system_error::system_error(error_code ec, const string& what_arg) : runtime_error(__init(ec, what_arg)), __ec_(ec) { } system_error::system_error(error_code ec, const char* what_arg) : runtime_error(__init(ec, what_arg)), __ec_(ec) { } system_error::system_error(error_code ec) : runtime_error(__init(ec, "")), __ec_(ec) { } system_error::system_error(int ev, const error_category& ecat, const string& what_arg) : runtime_error(__init(error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) { } system_error::system_error(int ev, const error_category& ecat, const char* what_arg) : runtime_error(__init(error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) { } system_error::system_error(int ev, const error_category& ecat) : runtime_error(__init(error_code(ev, ecat), "")), __ec_(error_code(ev, ecat)) { } system_error::~system_error() _NOEXCEPT { } void __throw_system_error(int ev, const char* what_arg) { #ifndef _LIBCPP_NO_EXCEPTIONS throw system_error(error_code(ev, system_category()), what_arg); #else (void)ev; (void)what_arg; _VSTD::abort(); #endif } _LIBCPP_END_NAMESPACE_STD <|endoftext|>
<commit_before>//===---------------------- system_error.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "__config" #define _LIBCPP_BUILDING_SYSTEM_ERROR #include "system_error" #include "include/config_elast.h" #include "cerrno" #include "cstring" #include "cstdio" #include "cstdlib" #include "cassert" #include "string" #include "string.h" _LIBCPP_BEGIN_NAMESPACE_STD // class error_category error_category::error_category() _NOEXCEPT { } error_category::~error_category() _NOEXCEPT { } error_condition error_category::default_error_condition(int ev) const _NOEXCEPT { return error_condition(ev, *this); } bool error_category::equivalent(int code, const error_condition& condition) const _NOEXCEPT { return default_error_condition(code) == condition; } bool error_category::equivalent(const error_code& code, int condition) const _NOEXCEPT { return *this == code.category() && code.value() == condition; } namespace { // GLIBC also uses 1024 as the maximum buffer size internally. constexpr size_t strerror_buff_size = 1024; string do_strerror_r(int ev); #if defined(__linux__) && !defined(_LIBCPP_HAS_MUSL_LIBC) // GNU Extended version string do_strerror_r(int ev) { char buffer[strerror_buff_size]; char* ret = ::strerror_r(ev, buffer, strerror_buff_size); return string(ret); } #else // POSIX version string do_strerror_r(int ev) { char buffer[strerror_buff_size]; const int old_errno = errno; if (::strerror_r(ev, buffer, strerror_buff_size) == -1) { const int new_errno = errno; errno = old_errno; if (new_errno == EINVAL) { std::snprintf(buffer, strerror_buff_size, "Unknown error %d", ev); return string(buffer); } else { assert(new_errno == ERANGE); // FIXME maybe? 'strerror_buff_size' is likely to exceed the // maximum error size so ERANGE shouldn't be returned. std::abort(); } } return string(buffer); } #endif } // end namespace string __do_message::message(int ev) const { #if defined(_LIBCPP_HAS_NO_THREADS) return string(::strerror(ev)); #else return do_strerror_r(ev); #endif } class _LIBCPP_HIDDEN __generic_error_category : public __do_message { public: virtual const char* name() const _NOEXCEPT; virtual string message(int ev) const; }; const char* __generic_error_category::name() const _NOEXCEPT { return "generic"; } string __generic_error_category::message(int ev) const { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return string("unspecified generic_category error"); #endif // _LIBCPP_ELAST return __do_message::message(ev); } const error_category& generic_category() _NOEXCEPT { static __generic_error_category s; return s; } class _LIBCPP_HIDDEN __system_error_category : public __do_message { public: virtual const char* name() const _NOEXCEPT; virtual string message(int ev) const; virtual error_condition default_error_condition(int ev) const _NOEXCEPT; }; const char* __system_error_category::name() const _NOEXCEPT { return "system"; } string __system_error_category::message(int ev) const { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return string("unspecified system_category error"); #endif // _LIBCPP_ELAST return __do_message::message(ev); } error_condition __system_error_category::default_error_condition(int ev) const _NOEXCEPT { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return error_condition(ev, system_category()); #endif // _LIBCPP_ELAST return error_condition(ev, generic_category()); } const error_category& system_category() _NOEXCEPT { static __system_error_category s; return s; } // error_condition string error_condition::message() const { return __cat_->message(__val_); } // error_code string error_code::message() const { return __cat_->message(__val_); } // system_error string system_error::__init(const error_code& ec, string what_arg) { if (ec) { if (!what_arg.empty()) what_arg += ": "; what_arg += ec.message(); } return what_arg; } system_error::system_error(error_code ec, const string& what_arg) : runtime_error(__init(ec, what_arg)), __ec_(ec) { } system_error::system_error(error_code ec, const char* what_arg) : runtime_error(__init(ec, what_arg)), __ec_(ec) { } system_error::system_error(error_code ec) : runtime_error(__init(ec, "")), __ec_(ec) { } system_error::system_error(int ev, const error_category& ecat, const string& what_arg) : runtime_error(__init(error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) { } system_error::system_error(int ev, const error_category& ecat, const char* what_arg) : runtime_error(__init(error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) { } system_error::system_error(int ev, const error_category& ecat) : runtime_error(__init(error_code(ev, ecat), "")), __ec_(error_code(ev, ecat)) { } system_error::~system_error() _NOEXCEPT { } void __throw_system_error(int ev, const char* what_arg) { #ifndef _LIBCPP_NO_EXCEPTIONS throw system_error(error_code(ev, system_category()), what_arg); #else (void)ev; (void)what_arg; #endif } _LIBCPP_END_NAMESPACE_STD <commit_msg>Fix error checking for strerror_r implementations that return the error code.<commit_after>//===---------------------- system_error.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "__config" #define _LIBCPP_BUILDING_SYSTEM_ERROR #include "system_error" #include "include/config_elast.h" #include "cerrno" #include "cstring" #include "cstdio" #include "cstdlib" #include "cassert" #include "string" #include "string.h" _LIBCPP_BEGIN_NAMESPACE_STD // class error_category error_category::error_category() _NOEXCEPT { } error_category::~error_category() _NOEXCEPT { } error_condition error_category::default_error_condition(int ev) const _NOEXCEPT { return error_condition(ev, *this); } bool error_category::equivalent(int code, const error_condition& condition) const _NOEXCEPT { return default_error_condition(code) == condition; } bool error_category::equivalent(const error_code& code, int condition) const _NOEXCEPT { return *this == code.category() && code.value() == condition; } namespace { // GLIBC also uses 1024 as the maximum buffer size internally. constexpr size_t strerror_buff_size = 1024; string do_strerror_r(int ev); #if defined(__linux__) && !defined(_LIBCPP_HAS_MUSL_LIBC) // GNU Extended version string do_strerror_r(int ev) { char buffer[strerror_buff_size]; char* ret = ::strerror_r(ev, buffer, strerror_buff_size); return string(ret); } #else // POSIX version string do_strerror_r(int ev) { char buffer[strerror_buff_size]; const int old_errno = errno; if ((int ret = ::strerror_r(ev, buffer, strerror_buff_size)) != 0) { // If `ret == -1` then the error is specified using `errno`, otherwise // `ret` represents the error. const int new_errno = ret == -1 ? errno : ret; errno = old_errno; if (new_errno == EINVAL) { std::snprintf(buffer, strerror_buff_size, "Unknown error %d", ev); return string(buffer); } else { assert(new_errno == ERANGE); // FIXME maybe? 'strerror_buff_size' is likely to exceed the // maximum error size so ERANGE shouldn't be returned. std::abort(); } } return string(buffer); } #endif } // end namespace string __do_message::message(int ev) const { #if defined(_LIBCPP_HAS_NO_THREADS) return string(::strerror(ev)); #else return do_strerror_r(ev); #endif } class _LIBCPP_HIDDEN __generic_error_category : public __do_message { public: virtual const char* name() const _NOEXCEPT; virtual string message(int ev) const; }; const char* __generic_error_category::name() const _NOEXCEPT { return "generic"; } string __generic_error_category::message(int ev) const { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return string("unspecified generic_category error"); #endif // _LIBCPP_ELAST return __do_message::message(ev); } const error_category& generic_category() _NOEXCEPT { static __generic_error_category s; return s; } class _LIBCPP_HIDDEN __system_error_category : public __do_message { public: virtual const char* name() const _NOEXCEPT; virtual string message(int ev) const; virtual error_condition default_error_condition(int ev) const _NOEXCEPT; }; const char* __system_error_category::name() const _NOEXCEPT { return "system"; } string __system_error_category::message(int ev) const { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return string("unspecified system_category error"); #endif // _LIBCPP_ELAST return __do_message::message(ev); } error_condition __system_error_category::default_error_condition(int ev) const _NOEXCEPT { #ifdef _LIBCPP_ELAST if (ev > _LIBCPP_ELAST) return error_condition(ev, system_category()); #endif // _LIBCPP_ELAST return error_condition(ev, generic_category()); } const error_category& system_category() _NOEXCEPT { static __system_error_category s; return s; } // error_condition string error_condition::message() const { return __cat_->message(__val_); } // error_code string error_code::message() const { return __cat_->message(__val_); } // system_error string system_error::__init(const error_code& ec, string what_arg) { if (ec) { if (!what_arg.empty()) what_arg += ": "; what_arg += ec.message(); } return what_arg; } system_error::system_error(error_code ec, const string& what_arg) : runtime_error(__init(ec, what_arg)), __ec_(ec) { } system_error::system_error(error_code ec, const char* what_arg) : runtime_error(__init(ec, what_arg)), __ec_(ec) { } system_error::system_error(error_code ec) : runtime_error(__init(ec, "")), __ec_(ec) { } system_error::system_error(int ev, const error_category& ecat, const string& what_arg) : runtime_error(__init(error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) { } system_error::system_error(int ev, const error_category& ecat, const char* what_arg) : runtime_error(__init(error_code(ev, ecat), what_arg)), __ec_(error_code(ev, ecat)) { } system_error::system_error(int ev, const error_category& ecat) : runtime_error(__init(error_code(ev, ecat), "")), __ec_(error_code(ev, ecat)) { } system_error::~system_error() _NOEXCEPT { } void __throw_system_error(int ev, const char* what_arg) { #ifndef _LIBCPP_NO_EXCEPTIONS throw system_error(error_code(ev, system_category()), what_arg); #else (void)ev; (void)what_arg; #endif } _LIBCPP_END_NAMESPACE_STD <|endoftext|>
<commit_before>// Copyright (c) 2020, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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 "triton/common/table_printer.h" #ifdef _WIN32 // suppress the min and max definitions in Windef.h. #define NOMINMAX #include <Windows.h> #else #include <sys/ioctl.h> #include <unistd.h> #endif #include <algorithm> #include <iomanip> #include <iostream> #include <memory> #include <numeric> #include <sstream> #include <string> #include <vector> namespace triton { namespace common { // // ASCII table printer. // void TablePrinter::InsertRow(const std::vector<std::string>& row) { std::vector<std::vector<std::string>> table_row; // Number of lines in each field in the record size_t max_height = 0; // Update max length of data items in each row for (size_t i = 0; i < row.size(); ++i) { table_row.push_back(std::vector<std::string>{}); std::stringstream ss(row[i]); std::string line; size_t max_width = 0; while (std::getline(ss, line, '\n')) { table_row[i].push_back(line); if (line.size() > max_width) max_width = line.size(); } if (max_width > max_widths_[i]) max_widths_[i] = max_width; size_t number_of_lines = table_row[i].size(); if (max_height < number_of_lines) max_height = number_of_lines; } max_heights_.push_back(max_height); data_.emplace_back(table_row); } void TablePrinter::FairShare() { // initialize original index locations size_t array_size = max_widths_.size(); std::vector<size_t> idx(array_size); iota(idx.begin(), idx.end(), 0); stable_sort(idx.begin(), idx.end(), [this](size_t i1, size_t i2) { return this->max_widths_[i1] < this->max_widths_[i2]; }); size_t loop_index = 1; for (auto itr = idx.begin(); itr != idx.end(); ++itr) { // If a column is not using all the space allocated to it if (max_widths_[*itr] < shares_[*itr]) { float excess = shares_[*itr] - max_widths_[*itr]; shares_[*itr] -= excess; if (itr == idx.end() - 1) break; auto update_itr = idx.begin() + (itr - idx.begin() + 1); // excess amount of unused space that must be distributed evenly to the // next columns float excess_per_column = excess / (array_size - loop_index); for (; update_itr != idx.end(); ++update_itr) { shares_[*update_itr] += excess_per_column; excess -= excess_per_column; } } ++loop_index; } // Remove any decimal shares for (auto itr = idx.begin(); itr != idx.end(); ++itr) { shares_[*itr] = (size_t)shares_[*itr]; } // For each record for (size_t i = 0; i < data_.size(); i++) { auto current_row = data_[i]; // For each field in the record for (size_t j = 0; j < current_row.size(); j++) { // For each line in the record for (size_t line_index = 0; line_index < current_row[j].size(); line_index++) { std::string line = current_row[j][line_index]; size_t num_rows = (line.size() + shares_[j] - 1) / shares_[j]; // If the number of rows required for this record is larger than 1, we // will break that line and put it in multiple lines if (num_rows > 1) { // Remove the multi-line field, it will be replaced by the line // that can fits the column size data_[i][j].erase(data_[i][j].begin() + line_index); for (size_t k = 0; k < num_rows; k++) { size_t start_index = std::min((size_t)(k * shares_[j]), line.size()); size_t end_index = std::min((size_t)((k + 1) * shares_[j]), line.size()); data_[i][j].insert( data_[i][j].begin() + line_index + k, line.substr(start_index, end_index - start_index)); } // We need to advance the index for the splitted lines. line_index += num_rows - 1; } if (max_heights_[i] < (num_rows - 1 + current_row[j].size())) max_heights_[i] += num_rows - 1; } } } } void TablePrinter::AddRow(std::stringstream& table, size_t row_index) { auto row = data_[row_index]; size_t max_height = max_heights_[row_index]; for (size_t j = 0; j < max_height; j++) { table << "|" << std::left; for (size_t i = 0; i < row.size(); i++) { if (j < row[i].size()) table << " " << std::setw(shares_[i]) << row[i][j] << " |"; else table << " " << std::setw(shares_[i]) << " " << " |"; } // Do not add new line if this is the last row of this record if (j != max_height - 1) table << "\n"; } table << "\n"; } void TablePrinter::AddRowDivider(std::stringstream& table) { table << "+"; for (const auto& share : shares_) { for (size_t i = 0; i < share + 2; i++) table << "-"; table << "+"; } table << "\n"; } std::string TablePrinter::PrintTable() { std::stringstream table; table << "\n"; FairShare(); AddRowDivider(table); // Add table headers AddRow(table, 0); AddRowDivider(table); for (size_t j = 1; j < data_.size(); j++) { AddRow(table, j); } AddRowDivider(table); return std::move(table.str()); } // TablePrinter will take the ownership of `headers`. TablePrinter::TablePrinter(const std::vector<std::string>& headers) { // terminal size size_t column_size = 500; #ifdef _WIN32 CONSOLE_SCREEN_BUFFER_INFO csbi; int ret = GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); if (ret && (csbi.dwSize.X != 0)) { column_size = csbi.dwSize.X; } #else struct winsize terminal_size; int status = ioctl(STDOUT_FILENO, TIOCGWINSZ, &terminal_size); if ((status == 0) && (terminal_size.ws_col != 0)) { column_size = terminal_size.ws_col; } #endif for (size_t i = 0; i < headers.size(); ++i) { max_widths_.emplace_back(0); } // Calculate fair share of every column size_t number_of_columns = headers.size(); // Terminal width is the actual terminal width minus two times spaces // required before and after each column and number of columns plus 1 for // the pipes between the columns size_t terminal_width = column_size - (2 * number_of_columns) - (number_of_columns + 1); int equal_share = terminal_width / headers.size(); for (size_t i = 0; i < headers.size(); ++i) { shares_.emplace_back(equal_share); terminal_width -= equal_share; } InsertRow(headers); } }} // namespace triton::common <commit_msg>Fix pessimizing move in function return (#31)<commit_after>// Copyright (c) 2020, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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 "triton/common/table_printer.h" #ifdef _WIN32 // suppress the min and max definitions in Windef.h. #define NOMINMAX #include <Windows.h> #else #include <sys/ioctl.h> #include <unistd.h> #endif #include <algorithm> #include <iomanip> #include <iostream> #include <memory> #include <numeric> #include <sstream> #include <string> #include <vector> namespace triton { namespace common { // // ASCII table printer. // void TablePrinter::InsertRow(const std::vector<std::string>& row) { std::vector<std::vector<std::string>> table_row; // Number of lines in each field in the record size_t max_height = 0; // Update max length of data items in each row for (size_t i = 0; i < row.size(); ++i) { table_row.push_back(std::vector<std::string>{}); std::stringstream ss(row[i]); std::string line; size_t max_width = 0; while (std::getline(ss, line, '\n')) { table_row[i].push_back(line); if (line.size() > max_width) max_width = line.size(); } if (max_width > max_widths_[i]) max_widths_[i] = max_width; size_t number_of_lines = table_row[i].size(); if (max_height < number_of_lines) max_height = number_of_lines; } max_heights_.push_back(max_height); data_.emplace_back(table_row); } void TablePrinter::FairShare() { // initialize original index locations size_t array_size = max_widths_.size(); std::vector<size_t> idx(array_size); iota(idx.begin(), idx.end(), 0); stable_sort(idx.begin(), idx.end(), [this](size_t i1, size_t i2) { return this->max_widths_[i1] < this->max_widths_[i2]; }); size_t loop_index = 1; for (auto itr = idx.begin(); itr != idx.end(); ++itr) { // If a column is not using all the space allocated to it if (max_widths_[*itr] < shares_[*itr]) { float excess = shares_[*itr] - max_widths_[*itr]; shares_[*itr] -= excess; if (itr == idx.end() - 1) break; auto update_itr = idx.begin() + (itr - idx.begin() + 1); // excess amount of unused space that must be distributed evenly to the // next columns float excess_per_column = excess / (array_size - loop_index); for (; update_itr != idx.end(); ++update_itr) { shares_[*update_itr] += excess_per_column; excess -= excess_per_column; } } ++loop_index; } // Remove any decimal shares for (auto itr = idx.begin(); itr != idx.end(); ++itr) { shares_[*itr] = (size_t)shares_[*itr]; } // For each record for (size_t i = 0; i < data_.size(); i++) { auto current_row = data_[i]; // For each field in the record for (size_t j = 0; j < current_row.size(); j++) { // For each line in the record for (size_t line_index = 0; line_index < current_row[j].size(); line_index++) { std::string line = current_row[j][line_index]; size_t num_rows = (line.size() + shares_[j] - 1) / shares_[j]; // If the number of rows required for this record is larger than 1, we // will break that line and put it in multiple lines if (num_rows > 1) { // Remove the multi-line field, it will be replaced by the line // that can fits the column size data_[i][j].erase(data_[i][j].begin() + line_index); for (size_t k = 0; k < num_rows; k++) { size_t start_index = std::min((size_t)(k * shares_[j]), line.size()); size_t end_index = std::min((size_t)((k + 1) * shares_[j]), line.size()); data_[i][j].insert( data_[i][j].begin() + line_index + k, line.substr(start_index, end_index - start_index)); } // We need to advance the index for the splitted lines. line_index += num_rows - 1; } if (max_heights_[i] < (num_rows - 1 + current_row[j].size())) max_heights_[i] += num_rows - 1; } } } } void TablePrinter::AddRow(std::stringstream& table, size_t row_index) { auto row = data_[row_index]; size_t max_height = max_heights_[row_index]; for (size_t j = 0; j < max_height; j++) { table << "|" << std::left; for (size_t i = 0; i < row.size(); i++) { if (j < row[i].size()) table << " " << std::setw(shares_[i]) << row[i][j] << " |"; else table << " " << std::setw(shares_[i]) << " " << " |"; } // Do not add new line if this is the last row of this record if (j != max_height - 1) table << "\n"; } table << "\n"; } void TablePrinter::AddRowDivider(std::stringstream& table) { table << "+"; for (const auto& share : shares_) { for (size_t i = 0; i < share + 2; i++) table << "-"; table << "+"; } table << "\n"; } std::string TablePrinter::PrintTable() { std::stringstream table; table << "\n"; FairShare(); AddRowDivider(table); // Add table headers AddRow(table, 0); AddRowDivider(table); for (size_t j = 1; j < data_.size(); j++) { AddRow(table, j); } AddRowDivider(table); return table.str(); } // TablePrinter will take the ownership of `headers`. TablePrinter::TablePrinter(const std::vector<std::string>& headers) { // terminal size size_t column_size = 500; #ifdef _WIN32 CONSOLE_SCREEN_BUFFER_INFO csbi; int ret = GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); if (ret && (csbi.dwSize.X != 0)) { column_size = csbi.dwSize.X; } #else struct winsize terminal_size; int status = ioctl(STDOUT_FILENO, TIOCGWINSZ, &terminal_size); if ((status == 0) && (terminal_size.ws_col != 0)) { column_size = terminal_size.ws_col; } #endif for (size_t i = 0; i < headers.size(); ++i) { max_widths_.emplace_back(0); } // Calculate fair share of every column size_t number_of_columns = headers.size(); // Terminal width is the actual terminal width minus two times spaces // required before and after each column and number of columns plus 1 for // the pipes between the columns size_t terminal_width = column_size - (2 * number_of_columns) - (number_of_columns + 1); int equal_share = terminal_width / headers.size(); for (size_t i = 0; i < headers.size(); ++i) { shares_.emplace_back(equal_share); terminal_width -= equal_share; } InsertRow(headers); } }} // namespace triton::common <|endoftext|>
<commit_before>#include "task_manager.hpp" namespace TaskDistribution { TaskManager::TaskManager(ObjectArchive<Key>& archive, ComputingUnitManager& unit_manager): archive_(archive), unit_manager_(unit_manager) { /*if (!archive.available_objects().empty()) load_archive();*/ } TaskManager::~TaskManager() { } void TaskManager::run() { run_single(); } void TaskManager::run_single() { while (!ready_.empty()) { Key task_key = ready_.front(); ready_.pop_front(); TaskEntry entry; archive_.load(task_key, entry); task_begin_handler_(task_key); unit_manager_.process_local(entry); task_completed(task_key); } } void TaskManager::task_completed(Key const& task_key) { { auto it = map_task_to_children_.find(task_key); if (it != map_task_to_children_.end()) { for (auto& child_key: it->second) { TaskEntry child_entry; archive_.load(child_key, child_entry); child_entry.active_parents--; if (child_entry.active_parents == 0) ready_.push_back(child_key); archive_.insert(child_key, child_entry); } } } task_end_handler_(task_key); } size_t TaskManager::id() const { return 0; } std::string TaskManager::load_string_to_hash(Key const& key) { std::string data_str; if (key.type != Key::Task) { archive_.load_raw(key, data_str); } else { TaskEntry entry; archive_.load(key, entry); // Special case of identity task if (!entry.computing_unit_id_key.is_valid()) return ""; entry.task_key = Key(); entry.result_key = Key(); entry.parents_key = Key(); entry.children_key = Key(); entry.active_parents = 0; data_str = ObjectArchive<Key>::serialize(entry); } return data_str; } void TaskManager::update_used_keys(std::map<int, size_t> const& used_keys) { auto it = used_keys.find(id()); if (it != used_keys.end()) Key::next_obj = std::max(Key::next_obj, it->second + 1); } void TaskManager::load_archive() { if (archive_.available_objects().empty()) return; if (id() != 0) return; std::hash<std::string> hasher; std::map<int, size_t> used_keys; for (auto key : archive_.available_objects()) { if (!key->is_valid()) continue; used_keys[key->node_id] = std::max(used_keys[key->node_id], key->obj_id); std::string data_str = load_string_to_hash(*key); if (data_str == "") continue; size_t hash = hasher(data_str); map_hash_to_key_.emplace(hash, *key); } update_used_keys(used_keys); } void TaskManager::set_task_creation_handler(creation_handler_type handler) { task_creation_handler_ = handler; } void TaskManager::clear_task_creation_handler() { task_creation_handler_ = [](std::string const&, Key const&){}; } void TaskManager::set_task_begin_handler(action_handler_type handler) { task_begin_handler_ = handler; } void TaskManager::clear_task_begin_handler() { task_begin_handler_ = [](Key const&){}; } void TaskManager::set_task_end_handler(action_handler_type handler) { task_end_handler_ = handler; } void TaskManager::clear_task_end_handler() { task_end_handler_ = [](Key const&){}; } Key TaskManager::new_key(Key::Type type) { return Key::new_key(type); } void TaskManager::create_family_lists(TaskEntry& entry) { if (!entry.parents_key.is_valid()) { entry.parents_key = new_key(Key::Parents); archive_.insert(entry.parents_key, KeySet()); } if (!entry.children_key.is_valid()) { entry.children_key = new_key(Key::Children); archive_.insert(entry.children_key, KeySet()); } } void TaskManager::add_dependency(TaskEntry& child_entry, Key const& parent_key, KeySet& parents) { TaskEntry parent_entry; archive_.load(parent_key, parent_entry); KeySet children; archive_.load(parent_entry.children_key, children); // Creates map used to check if tasks are ready to run map_task_to_children_[parent_key].insert(child_entry.task_key); // Only add as active if it's a new parent if (parents.find(parent_key) == parents.end()) { parents.insert(parent_key); if (!parent_entry.result_key.is_valid() && parent_entry.should_save) child_entry.active_parents++; } children.insert(child_entry.task_key); archive_.insert(parent_entry.children_key, children); } }; <commit_msg>Fixed special identity case.<commit_after>#include "task_manager.hpp" namespace TaskDistribution { TaskManager::TaskManager(ObjectArchive<Key>& archive, ComputingUnitManager& unit_manager): archive_(archive), unit_manager_(unit_manager) { /*if (!archive.available_objects().empty()) load_archive();*/ } TaskManager::~TaskManager() { } void TaskManager::run() { run_single(); } void TaskManager::run_single() { while (!ready_.empty()) { Key task_key = ready_.front(); ready_.pop_front(); TaskEntry entry; archive_.load(task_key, entry); task_begin_handler_(task_key); unit_manager_.process_local(entry); task_completed(task_key); } } void TaskManager::task_completed(Key const& task_key) { { auto it = map_task_to_children_.find(task_key); if (it != map_task_to_children_.end()) { for (auto& child_key: it->second) { TaskEntry child_entry; archive_.load(child_key, child_entry); child_entry.active_parents--; if (child_entry.active_parents == 0) ready_.push_back(child_key); archive_.insert(child_key, child_entry); } } } task_end_handler_(task_key); } size_t TaskManager::id() const { return 0; } std::string TaskManager::load_string_to_hash(Key const& key) { std::string data_str; if (key.type != Key::Task) { archive_.load_raw(key, data_str); } else { TaskEntry entry; archive_.load(key, entry); // Special case of tasks different from the identity if (entry.computing_unit_id_key.is_valid()) { entry.result_key = Key(); entry.parents_key = Key(); entry.children_key = Key(); entry.active_parents = 0; } entry.task_key = Key(); data_str = ObjectArchive<Key>::serialize(entry); } return data_str; } void TaskManager::update_used_keys(std::map<int, size_t> const& used_keys) { auto it = used_keys.find(id()); if (it != used_keys.end()) Key::next_obj = std::max(Key::next_obj, it->second + 1); } void TaskManager::load_archive() { if (archive_.available_objects().empty()) return; if (id() != 0) return; std::hash<std::string> hasher; std::map<int, size_t> used_keys; for (auto key : archive_.available_objects()) { if (!key->is_valid()) continue; used_keys[key->node_id] = std::max(used_keys[key->node_id], key->obj_id); std::string data_str = load_string_to_hash(*key); if (data_str == "") continue; size_t hash = hasher(data_str); map_hash_to_key_.emplace(hash, *key); } update_used_keys(used_keys); } void TaskManager::set_task_creation_handler(creation_handler_type handler) { task_creation_handler_ = handler; } void TaskManager::clear_task_creation_handler() { task_creation_handler_ = [](std::string const&, Key const&){}; } void TaskManager::set_task_begin_handler(action_handler_type handler) { task_begin_handler_ = handler; } void TaskManager::clear_task_begin_handler() { task_begin_handler_ = [](Key const&){}; } void TaskManager::set_task_end_handler(action_handler_type handler) { task_end_handler_ = handler; } void TaskManager::clear_task_end_handler() { task_end_handler_ = [](Key const&){}; } Key TaskManager::new_key(Key::Type type) { return Key::new_key(type); } void TaskManager::create_family_lists(TaskEntry& entry) { if (!entry.parents_key.is_valid()) { entry.parents_key = new_key(Key::Parents); archive_.insert(entry.parents_key, KeySet()); } if (!entry.children_key.is_valid()) { entry.children_key = new_key(Key::Children); archive_.insert(entry.children_key, KeySet()); } } void TaskManager::add_dependency(TaskEntry& child_entry, Key const& parent_key, KeySet& parents) { TaskEntry parent_entry; archive_.load(parent_key, parent_entry); KeySet children; archive_.load(parent_entry.children_key, children); // Creates map used to check if tasks are ready to run map_task_to_children_[parent_key].insert(child_entry.task_key); // Only add as active if it's a new parent if (parents.find(parent_key) == parents.end()) { parents.insert(parent_key); if (!parent_entry.result_key.is_valid() && parent_entry.should_save) child_entry.active_parents++; } children.insert(child_entry.task_key); archive_.insert(parent_entry.children_key, children); } }; <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <list> #include <set> #include <map> #include "memdb/utils.h" #include "base/all.h" using namespace base; using namespace mdb; using namespace std; TEST(utils, stringhash32) { EXPECT_EQ(stringhash32("hello"), stringhash32("hello")); EXPECT_NEQ(stringhash32("hello"), stringhash32("world")); Log::debug("stringhash32('hello') = %u", stringhash32("hello")); } TEST(utils, stringhash64) { EXPECT_EQ(stringhash64("hello"), stringhash64("hello")); EXPECT_NEQ(stringhash64("hello"), stringhash64("world")); Log::debug("stringhash64('hello') = %llu", stringhash64("hello")); } TEST(utils, inthash32) { EXPECT_EQ(inthash32(1987, 1001), inthash32(1987, 1001)); EXPECT_NEQ(inthash32(1987, 1989), inthash32(1987, 1001)); Log::debug("inthash32(1987, 1001) = %u", inthash32(1987, 1001)); } TEST(utils, inthash64) { EXPECT_EQ(inthash64(1987, 1001), inthash64(1987, 1001)); EXPECT_NEQ(inthash64(1987, 1989), inthash64(1987, 1001)); Log::debug("inthash64(1987, 1001) = %llu", inthash64(1987, 1001)); } template<class T> T& get_value(T& v, std::true_type) { return v; } template<class T> typename T::second_type& get_value(T& v, std::false_type) { return v.second; } template <class Container> static void print_container_values(const Container& container) { for (auto it : container) { cout << "value in container: " << get_value(it, std::is_same<int, decltype(it)>()) << endl; } } TEST(utils, value_enumerator) { print_container_values(set<int>({1, 2, 3, 4})); print_container_values(vector<int>({1, 2, 3, 4})); map<int, int> m; m[1] = 2; m[3] = 4; print_container_values(m); } <commit_msg>minor update<commit_after>#include <iostream> #include <vector> #include <list> #include <set> #include <map> #include "memdb/utils.h" #include "base/all.h" using namespace base; using namespace mdb; using namespace std; TEST(utils, stringhash32) { EXPECT_EQ(stringhash32("hello"), stringhash32("hello")); EXPECT_NEQ(stringhash32("hello"), stringhash32("world")); Log::debug("stringhash32('hello') = %u", stringhash32("hello")); } TEST(utils, stringhash64) { EXPECT_EQ(stringhash64("hello"), stringhash64("hello")); EXPECT_NEQ(stringhash64("hello"), stringhash64("world")); Log::debug("stringhash64('hello') = %llu", stringhash64("hello")); } TEST(utils, inthash32) { EXPECT_EQ(inthash32(1987, 1001), inthash32(1987, 1001)); EXPECT_NEQ(inthash32(1987, 1989), inthash32(1987, 1001)); Log::debug("inthash32(1987, 1001) = %u", inthash32(1987, 1001)); } TEST(utils, inthash64) { EXPECT_EQ(inthash64(1987, 1001), inthash64(1987, 1001)); EXPECT_NEQ(inthash64(1987, 1989), inthash64(1987, 1001)); Log::debug("inthash64(1987, 1001) = %llu", inthash64(1987, 1001)); } template<class T> const T& get_value(const T& v, std::true_type) { return v; } template<class T> const typename T::second_type& get_value(const T& v, std::false_type) { return v.second; } template <class Container> static void print_container_values(const Container& container) { for (auto it = container.begin(); it != container.end(); ++it) { cout << "value in container: " << get_value(*it, std::is_same<int, typename Container::value_type>()) << endl; } } TEST(utils, value_enumerator) { print_container_values(set<int>({1, 2, 3, 4})); print_container_values(vector<int>({1, 2, 3, 4})); map<int, int> m; m[1] = 2; m[3] = 4; print_container_values(m); } <|endoftext|>
<commit_before>#include "cmdline.h" #include "align.hpp" #include "algorithm.h" #include <cassert> #include <iostream> #include <stdexcept> namespace text { struct option_t { explicit option_t(const std::string& short_name = std::string(), const std::string& name = std::string(), const std::string& description = std::string(), const std::string& default_value = std::string()) : m_short_name(short_name), m_name(name), m_description(description), m_default_value(default_value), m_given(false) { } std::string concatenate() const { return (m_short_name.empty() ? "" : ("-" + m_short_name) + ",") + "--" + m_name + (m_default_value.empty() ? "" : ("(" + m_default_value + ")")); } bool has() const { return m_given; } std::string get() const { return m_value.empty() ? m_default_value : m_value; } // attributes std::string m_short_name; std::string m_name; std::string m_description; std::string m_default_value; std::string m_value; bool m_given; }; bool operator==(const option_t& option, const std::string& name_or_short_name) { return option.m_short_name == name_or_short_name || option.m_name == name_or_short_name; } using options_t = std::vector<option_t>; struct cmdline_t::impl_t { explicit impl_t(const std::string& title) : m_title(title) { } auto find(const std::string& name_or_short_name) { return std::find(m_options.begin(), m_options.end(), name_or_short_name); } auto store(const std::string& name_or_short_name, const std::string& value = std::string()) { auto it = find(name_or_short_name); if (it == m_options.end()) { throw std::runtime_error("cmdline: unrecognized option [" + name_or_short_name + "]"); } else { it->m_given = true; it->m_value = value; } } std::string m_title; options_t m_options; }; cmdline_t::cmdline_t(const std::string& title) : m_impl(new impl_t(title)) { add("h", "help", "usage"); } cmdline_t::~cmdline_t() = default; void cmdline_t::add(const std::string& short_name, const std::string& name, const std::string& description) const { const std::string default_value; add(short_name, name, description, default_value); } void cmdline_t::add( const std::string& short_name, const std::string& name, const std::string& description, const std::string& default_value) const { if ( name.empty() || text::starts_with(name, "-") || text::starts_with(name, "--")) { throw std::runtime_error("cmdline: invalid option name [" + name + "]"); } if ( !short_name.empty() && (short_name.size() != 1 || short_name[0] == '-')) { throw std::runtime_error("cmdline: invalid short option name [" + short_name + "]"); } if ( m_impl->find(name) != m_impl->m_options.end()) { throw std::runtime_error("cmdline: duplicated option [" + name + "]"); } if ( !short_name.empty() && m_impl->find(short_name) != m_impl->m_options.end()) { throw std::runtime_error("cmdline: duplicated option [" + short_name + "]"); } m_impl->m_options.emplace_back(short_name, name, description, default_value); } void cmdline_t::process(const int argc, char* argv[]) const { std::string current_name_or_short_name; for (int i = 1; i < argc; ++ i) { const std::string token = argv[i]; assert(!token.empty()); if (text::starts_with(token, "--")) { const std::string name = token.substr(2); m_impl->store(name); current_name_or_short_name = name; } else if (text::starts_with(token, "-")) { const std::string short_name = token.substr(1); m_impl->store(short_name); current_name_or_short_name = short_name; } else { const std::string& value = token; if (current_name_or_short_name.empty()) { throw std::runtime_error("cmdline: missing option before value [" + value + "]"); } m_impl->store(current_name_or_short_name, value); current_name_or_short_name.clear(); } } if (has("help")) { usage(); } } bool cmdline_t::has(const std::string& name_or_short_name) const { const auto it = m_impl->find(name_or_short_name); if (it == m_impl->m_options.end()) { throw std::runtime_error("cmdline: unrecognized option [" + name_or_short_name + "]"); } return it->m_given; } std::string cmdline_t::get(const std::string& name_or_short_name) const { const auto it = m_impl->find(name_or_short_name); if (it == m_impl->m_options.end()) { throw std::runtime_error("cmdline: unrecognized option [" + name_or_short_name + "]"); } else if (!it->m_given && it->m_default_value.empty()) { throw std::runtime_error("cmdline: no value provided for option [" + name_or_short_name + "]"); } return it->get(); } void cmdline_t::usage() const { std::cout << m_impl->m_title << std::endl; size_t max_option_size = 0; for (const auto& option : m_impl->m_options) { max_option_size = std::max(max_option_size, option.concatenate().size()); } max_option_size += 4; for (const auto& option : m_impl->m_options) { std::cout << " " << text::align(option.concatenate(), max_option_size) << option.m_description << std::endl; } std::cout << std::endl; exit(EXIT_FAILURE); } } <commit_msg>better check for option names in the command line<commit_after>#include "cmdline.h" #include "align.hpp" #include "algorithm.h" #include <cassert> #include <iostream> #include <stdexcept> namespace text { struct option_t { explicit option_t(const std::string& short_name = std::string(), const std::string& name = std::string(), const std::string& description = std::string(), const std::string& default_value = std::string()) : m_short_name(short_name), m_name(name), m_description(description), m_default_value(default_value), m_given(false) { } std::string concatenate() const { return (m_short_name.empty() ? "" : ("-" + m_short_name) + ",") + "--" + m_name + (m_default_value.empty() ? "" : ("(" + m_default_value + ")")); } bool has() const { return m_given; } std::string get() const { return m_value.empty() ? m_default_value : m_value; } // attributes std::string m_short_name; std::string m_name; std::string m_description; std::string m_default_value; std::string m_value; bool m_given; }; bool operator==(const option_t& option, const std::string& name_or_short_name) { return option.m_short_name == name_or_short_name || option.m_name == name_or_short_name; } using options_t = std::vector<option_t>; struct cmdline_t::impl_t { explicit impl_t(const std::string& title) : m_title(title) { } auto find(const std::string& name_or_short_name) { return std::find(m_options.begin(), m_options.end(), name_or_short_name); } auto store(const std::string& name_or_short_name, const std::string& value = std::string()) { auto it = find(name_or_short_name); if (it == m_options.end()) { throw std::runtime_error("cmdline: unrecognized option [" + name_or_short_name + "]"); } else { it->m_given = true; it->m_value = value; } } std::string m_title; options_t m_options; }; cmdline_t::cmdline_t(const std::string& title) : m_impl(new impl_t(title)) { add("h", "help", "usage"); } cmdline_t::~cmdline_t() = default; void cmdline_t::add(const std::string& short_name, const std::string& name, const std::string& description) const { const std::string default_value; add(short_name, name, description, default_value); } void cmdline_t::add( const std::string& short_name, const std::string& name, const std::string& description, const std::string& default_value) const { if ( name.empty() || text::starts_with(name, "-") || text::starts_with(name, "--")) { throw std::runtime_error("cmdline: invalid option name [" + name + "]"); } if ( !short_name.empty() && (short_name.size() != 1 || short_name[0] == '-')) { throw std::runtime_error("cmdline: invalid short option name [" + short_name + "]"); } if ( m_impl->find(name) != m_impl->m_options.end()) { throw std::runtime_error("cmdline: duplicated option [" + name + "]"); } if ( !short_name.empty() && m_impl->find(short_name) != m_impl->m_options.end()) { throw std::runtime_error("cmdline: duplicated option [" + short_name + "]"); } m_impl->m_options.emplace_back(short_name, name, description, default_value); } void cmdline_t::process(const int argc, char* argv[]) const { std::string current_name_or_short_name; for (int i = 1; i < argc; ++ i) { const std::string token = argv[i]; assert(!token.empty()); if (text::starts_with(token, "--")) { const std::string name = token.substr(2); if (name.empty()) { throw std::runtime_error( "cmdline: invalid option name [" + name + "/" + token + "]"); } m_impl->store(name); current_name_or_short_name = name; } else if (text::starts_with(token, "-")) { const std::string short_name = token.substr(1); if (short_name.size() != 1) { throw std::runtime_error( "cmdline: invalid short option name [" + short_name + "/" + token + "]"); } m_impl->store(short_name); current_name_or_short_name = short_name; } else { const std::string& value = token; if (current_name_or_short_name.empty()) { throw std::runtime_error("cmdline: missing option before value [" + value + "]"); } m_impl->store(current_name_or_short_name, value); current_name_or_short_name.clear(); } } if (has("help")) { usage(); } } bool cmdline_t::has(const std::string& name_or_short_name) const { const auto it = m_impl->find(name_or_short_name); if (it == m_impl->m_options.end()) { throw std::runtime_error("cmdline: unrecognized option [" + name_or_short_name + "]"); } return it->m_given; } std::string cmdline_t::get(const std::string& name_or_short_name) const { const auto it = m_impl->find(name_or_short_name); if (it == m_impl->m_options.end()) { throw std::runtime_error("cmdline: unrecognized option [" + name_or_short_name + "]"); } else if (!it->m_given && it->m_default_value.empty()) { throw std::runtime_error("cmdline: no value provided for option [" + name_or_short_name + "]"); } return it->get(); } void cmdline_t::usage() const { std::cout << m_impl->m_title << std::endl; size_t max_option_size = 0; for (const auto& option : m_impl->m_options) { max_option_size = std::max(max_option_size, option.concatenate().size()); } max_option_size += 4; for (const auto& option : m_impl->m_options) { std::cout << " " << text::align(option.concatenate(), max_option_size) << option.m_description << std::endl; } std::cout << std::endl; exit(EXIT_FAILURE); } } <|endoftext|>
<commit_before>/* * Copyright 2010, * Nicolas Mansard, Olivier Stasse, François Bleibel, Florent Lamiraux * * CNRS * * This file is part of sot-core. * sot-core 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. * sot-core 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 sot-core. If not, see <http://www.gnu.org/licenses/>. */ /* --------------------------------------------------------------------- */ /* --- INCLUDE --------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* jrl-mathtools */ #include <jrl/mathtools/vector3.hh> /* SOT */ #include "sot/core/device.hh" #include "sot/core/debug.hh" using namespace std; #include <dynamic-graph/factory.h> #include <dynamic-graph/all-commands.h> using namespace dynamicgraph::sot; using namespace dynamicgraph; const std::string Device::CLASS_NAME = "Device"; /* --------------------------------------------------------------------- */ /* --- CLASS ----------------------------------------------------------- */ /* --------------------------------------------------------------------- */ void Device::integrateRollPitchYaw(ml::Vector& state, const ml::Vector& control, double dt) { jrlMathTools::Vector3D<double> omega; // Translation part for (unsigned int i=0; i<3; i++) { state(i) += control(i)*dt; ffPose_(i,3) = state(i); omega(i) = control(i+3); } // Rotation part double roll = state(3); double pitch = state(4); double yaw = state(5); std::vector<jrlMathTools::Vector3D<double> > column; // Build rotation matrix as a vector of colums jrlMathTools::Vector3D<double> e1; e1(0) = cos(pitch)*cos(yaw); e1(1) = cos(pitch)*sin(yaw); e1(2) = -sin(pitch); column.push_back(e1); jrlMathTools::Vector3D<double> e2; e2(0) = sin(roll)*sin(pitch)*cos(yaw) - cos(roll)*sin(yaw); e2(1) = sin(roll)*sin(pitch)*sin(yaw) + cos(roll)*cos(yaw); e2(2) = sin(roll)*cos(pitch); column.push_back(e2); jrlMathTools::Vector3D<double> e3; e3(0) = cos(roll)*sin(pitch)*cos(yaw) + sin(roll)*sin(yaw); e3(1) = cos(roll)*sin(pitch)*sin(yaw) - sin(roll)*cos(yaw); e3(2) = cos(roll)*cos(pitch); column.push_back(e3); // Apply Rodrigues (1795–1851) formula for rotation about omega vector double angle = dt*omega.norm(); if (angle == 0) { return; } jrlMathTools::Vector3D<double> k = omega/omega.norm(); // ei <- ei cos(angle) + sin(angle)(k ^ ei) + (k.ei)(1-cos(angle))k for (unsigned int i=0; i<3; i++) { jrlMathTools::Vector3D<double> ei = column[i]; column[i] = ei*cos(angle) + (k^ei)*sin(angle) + k*((k*ei)*(1-cos(angle))); } // Store new position if ffPose_ member. for (unsigned int r = 0; r < 3; r++) { for (unsigned int c = 0; c < 3; c++) { ffPose_(r,c) = column[c](r); } } const double & nx = column[2](2); const double & ny = column[1](2); state(3) = atan2(ny,nx); state(4) = atan2(-column[0](2), sqrt(ny*ny+nx*nx)); state(5) = atan2(column[0](1),column[0](0)); } const MatrixHomogeneous& Device::freeFlyerPose() const { return ffPose_; } Device:: ~Device( ) { for( unsigned int i=0; i<4; ++i ) { delete forcesSOUT[i]; } } Device:: Device( const std::string& n ) :Entity(n) ,state_(6) ,controlSIN( NULL,"Device("+n+")::input(double)::control" ) //,attitudeSIN(NULL,"Device::input(matrixRot)::attitudeIN") ,attitudeSIN(NULL,"Device::input(vector3)::attitudeIN") ,zmpSIN(NULL,"Device::input(vector3)::zmp") ,stateSOUT( "Device("+n+")::output(vector)::state" ) ,attitudeSOUT( "Device("+n+")::output(matrixRot)::attitude" ) ,pseudoTorqueSOUT( "Device::output(vector)::ptorque" ) ,previousControlSOUT( "Device("+n+")::output(vector)::previousControl" ) ,motorcontrolSOUT( "Device("+n+")::output(vector)::motorcontrol" ) ,ZMPPreviousControllerSOUT( "Device("+n+")::output(vector)::zmppreviouscontroller" ), ffPose_() { /* --- SIGNALS --- */ for( int i=0;i<4;++i ){ withForceSignals[i] = false; } forcesSOUT[0] = new Signal<ml::Vector, int>("OpenHRP::output(vector6)::forceRLEG"); forcesSOUT[1] = new Signal<ml::Vector, int>("OpenHRP::output(vector6)::forceLLEG"); forcesSOUT[2] = new Signal<ml::Vector, int>("OpenHRP::output(vector6)::forceRARM"); forcesSOUT[3] = new Signal<ml::Vector, int>("OpenHRP::output(vector6)::forceLARM"); signalRegistration( controlSIN<<stateSOUT<<attitudeSOUT<<attitudeSIN<<zmpSIN <<*forcesSOUT[0]<<*forcesSOUT[1]<<*forcesSOUT[2]<<*forcesSOUT[3] <<previousControlSOUT <<pseudoTorqueSOUT << motorcontrolSOUT << ZMPPreviousControllerSOUT ); state_.fill(.0); stateSOUT.setConstant( state_ ); /* --- Commands --- */ { std::string docstring; /* Command setStateSize. */ docstring = "\n" " Set size of state vector\n" "\n"; addCommand("resize", new command::Setter<Device, unsigned int> (*this, &Device::setStateSize, docstring)); /* Command set. */ docstring = "\n" " Set state vector value\n" "\n"; addCommand("set", new command::Setter<Device, Vector> (*this, &Device::setState, docstring)); void(Device::*setRootPtr)(const ml::Matrix&) = &Device::setRoot; docstring = command::docCommandVoid1("Set the root position.", "matrix homogeneous"); addCommand("setRoot", command::makeCommandVoid1(*this,setRootPtr, docstring)); // Handle commands and signals called in a synchronous way. periodicCallBefore_.addSpecificCommands(*this, commandMap, "before."); periodicCallAfter_.addSpecificCommands(*this, commandMap, "after."); } } void Device:: setStateSize( const unsigned int& size ) { state_.resize(size); state_.fill( .0 ); stateSOUT .setConstant( state_ ); previousControlSOUT.setConstant( state_ ); pseudoTorqueSOUT.setConstant( state_ ); motorcontrolSOUT .setConstant( state_ ); ml::Vector zmp(3); zmp.fill( .0 ); ZMPPreviousControllerSOUT .setConstant( zmp ); } void Device:: setState( const ml::Vector& st ) { state_ = st; stateSOUT .setConstant( state_ ); motorcontrolSOUT .setConstant( state_ ); } void Device:: setRoot( const ml::Matrix & root ) { setRoot( (MatrixHomogeneous) root ); } void Device:: setRoot( const MatrixHomogeneous & worlMwaist ) { MatrixRotation R; worlMwaist.extract(R); VectorRollPitchYaw r; r.fromMatrix(R); ml::Vector q = state_; worlMwaist.extract(q); // abusive ... but working. for( unsigned int i=0;i<3;++i ) q(i+3) = r(i); } void Device:: increment( const double & dt ) { int time = controlSIN.getTime(); sotDEBUG(25) << "Time : " << time << std::endl; /* Position the signals corresponding to sensors. */ stateSOUT .setConstant( state_ ); ml::Vector forceNull(6); forceNull.fill(0); for( int i=0;i<4;++i ){ if( withForceSignals[i] ) forcesSOUT[i]->setConstant(forceNull); } ml::Vector zmp(3); zmp.fill( .0 ); ZMPPreviousControllerSOUT .setConstant( zmp ); // Run Synchronous commands and evaluate signals outside the main // connected component of the graph. periodicCallBefore_.run(time+1); /* Force the recomputation of the control. */ controlSIN( time+1 ); sotDEBUG(25) << "u" <<time<<" = " << controlSIN.accessCopy() << endl; /* Integration of numerical values. This function is virtual. */ integrate( dt ); sotDEBUG(25) << "q" << time << " = " << state_ << endl; // Run Synchronous commands and evaluate signals outside the main // connected component of the graph. periodicCallAfter_.run(time+1); // Others signals. motorcontrolSOUT .setConstant( state_ ); } void Device::integrate( const double & dt ) { const ml::Vector & control = controlSIN.accessCopy(); // If control size is state size - 6, integrate joint angles, // if control and state are of same size, integrate 6 first degrees of // freedom as a translation and roll pitch yaw. unsigned int offset = 6; if (control.size() == state_.size()) { offset = 0; integrateRollPitchYaw(state_, control, dt); } for( unsigned int i=6;i<state_.size();++i ) { state_(i) += (control(i-offset)*dt); } } /* --- DISPLAY ------------------------------------------------------------ */ void Device::display ( std::ostream& os ) const {os <<name<<": "<<state_<<endl; } <commit_msg>Synchronize from the state time rather than the control time.<commit_after>/* * Copyright 2010, * Nicolas Mansard, Olivier Stasse, François Bleibel, Florent Lamiraux * * CNRS * * This file is part of sot-core. * sot-core 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. * sot-core 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 sot-core. If not, see <http://www.gnu.org/licenses/>. */ /* --------------------------------------------------------------------- */ /* --- INCLUDE --------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* jrl-mathtools */ #include <jrl/mathtools/vector3.hh> /* SOT */ #include "sot/core/device.hh" #include "sot/core/debug.hh" using namespace std; #include <dynamic-graph/factory.h> #include <dynamic-graph/all-commands.h> using namespace dynamicgraph::sot; using namespace dynamicgraph; const std::string Device::CLASS_NAME = "Device"; /* --------------------------------------------------------------------- */ /* --- CLASS ----------------------------------------------------------- */ /* --------------------------------------------------------------------- */ void Device::integrateRollPitchYaw(ml::Vector& state, const ml::Vector& control, double dt) { jrlMathTools::Vector3D<double> omega; // Translation part for (unsigned int i=0; i<3; i++) { state(i) += control(i)*dt; ffPose_(i,3) = state(i); omega(i) = control(i+3); } // Rotation part double roll = state(3); double pitch = state(4); double yaw = state(5); std::vector<jrlMathTools::Vector3D<double> > column; // Build rotation matrix as a vector of colums jrlMathTools::Vector3D<double> e1; e1(0) = cos(pitch)*cos(yaw); e1(1) = cos(pitch)*sin(yaw); e1(2) = -sin(pitch); column.push_back(e1); jrlMathTools::Vector3D<double> e2; e2(0) = sin(roll)*sin(pitch)*cos(yaw) - cos(roll)*sin(yaw); e2(1) = sin(roll)*sin(pitch)*sin(yaw) + cos(roll)*cos(yaw); e2(2) = sin(roll)*cos(pitch); column.push_back(e2); jrlMathTools::Vector3D<double> e3; e3(0) = cos(roll)*sin(pitch)*cos(yaw) + sin(roll)*sin(yaw); e3(1) = cos(roll)*sin(pitch)*sin(yaw) - sin(roll)*cos(yaw); e3(2) = cos(roll)*cos(pitch); column.push_back(e3); // Apply Rodrigues (1795–1851) formula for rotation about omega vector double angle = dt*omega.norm(); if (angle == 0) { return; } jrlMathTools::Vector3D<double> k = omega/omega.norm(); // ei <- ei cos(angle) + sin(angle)(k ^ ei) + (k.ei)(1-cos(angle))k for (unsigned int i=0; i<3; i++) { jrlMathTools::Vector3D<double> ei = column[i]; column[i] = ei*cos(angle) + (k^ei)*sin(angle) + k*((k*ei)*(1-cos(angle))); } // Store new position if ffPose_ member. for (unsigned int r = 0; r < 3; r++) { for (unsigned int c = 0; c < 3; c++) { ffPose_(r,c) = column[c](r); } } const double & nx = column[2](2); const double & ny = column[1](2); state(3) = atan2(ny,nx); state(4) = atan2(-column[0](2), sqrt(ny*ny+nx*nx)); state(5) = atan2(column[0](1),column[0](0)); } const MatrixHomogeneous& Device::freeFlyerPose() const { return ffPose_; } Device:: ~Device( ) { for( unsigned int i=0; i<4; ++i ) { delete forcesSOUT[i]; } } Device:: Device( const std::string& n ) :Entity(n) ,state_(6) ,controlSIN( NULL,"Device("+n+")::input(double)::control" ) //,attitudeSIN(NULL,"Device::input(matrixRot)::attitudeIN") ,attitudeSIN(NULL,"Device::input(vector3)::attitudeIN") ,zmpSIN(NULL,"Device::input(vector3)::zmp") ,stateSOUT( "Device("+n+")::output(vector)::state" ) ,attitudeSOUT( "Device("+n+")::output(matrixRot)::attitude" ) ,pseudoTorqueSOUT( "Device::output(vector)::ptorque" ) ,previousControlSOUT( "Device("+n+")::output(vector)::previousControl" ) ,motorcontrolSOUT( "Device("+n+")::output(vector)::motorcontrol" ) ,ZMPPreviousControllerSOUT( "Device("+n+")::output(vector)::zmppreviouscontroller" ), ffPose_() { /* --- SIGNALS --- */ for( int i=0;i<4;++i ){ withForceSignals[i] = false; } forcesSOUT[0] = new Signal<ml::Vector, int>("OpenHRP::output(vector6)::forceRLEG"); forcesSOUT[1] = new Signal<ml::Vector, int>("OpenHRP::output(vector6)::forceLLEG"); forcesSOUT[2] = new Signal<ml::Vector, int>("OpenHRP::output(vector6)::forceRARM"); forcesSOUT[3] = new Signal<ml::Vector, int>("OpenHRP::output(vector6)::forceLARM"); signalRegistration( controlSIN<<stateSOUT<<attitudeSOUT<<attitudeSIN<<zmpSIN <<*forcesSOUT[0]<<*forcesSOUT[1]<<*forcesSOUT[2]<<*forcesSOUT[3] <<previousControlSOUT <<pseudoTorqueSOUT << motorcontrolSOUT << ZMPPreviousControllerSOUT ); state_.fill(.0); stateSOUT.setConstant( state_ ); /* --- Commands --- */ { std::string docstring; /* Command setStateSize. */ docstring = "\n" " Set size of state vector\n" "\n"; addCommand("resize", new command::Setter<Device, unsigned int> (*this, &Device::setStateSize, docstring)); /* Command set. */ docstring = "\n" " Set state vector value\n" "\n"; addCommand("set", new command::Setter<Device, Vector> (*this, &Device::setState, docstring)); void(Device::*setRootPtr)(const ml::Matrix&) = &Device::setRoot; docstring = command::docCommandVoid1("Set the root position.", "matrix homogeneous"); addCommand("setRoot", command::makeCommandVoid1(*this,setRootPtr, docstring)); // Handle commands and signals called in a synchronous way. periodicCallBefore_.addSpecificCommands(*this, commandMap, "before."); periodicCallAfter_.addSpecificCommands(*this, commandMap, "after."); } } void Device:: setStateSize( const unsigned int& size ) { state_.resize(size); state_.fill( .0 ); stateSOUT .setConstant( state_ ); previousControlSOUT.setConstant( state_ ); pseudoTorqueSOUT.setConstant( state_ ); motorcontrolSOUT .setConstant( state_ ); ml::Vector zmp(3); zmp.fill( .0 ); ZMPPreviousControllerSOUT .setConstant( zmp ); } void Device:: setState( const ml::Vector& st ) { state_ = st; stateSOUT .setConstant( state_ ); motorcontrolSOUT .setConstant( state_ ); } void Device:: setRoot( const ml::Matrix & root ) { setRoot( (MatrixHomogeneous) root ); } void Device:: setRoot( const MatrixHomogeneous & worlMwaist ) { MatrixRotation R; worlMwaist.extract(R); VectorRollPitchYaw r; r.fromMatrix(R); ml::Vector q = state_; worlMwaist.extract(q); // abusive ... but working. for( unsigned int i=0;i<3;++i ) q(i+3) = r(i); } void Device:: increment( const double & dt ) { int time = stateSOUT.getTime(); sotDEBUG(25) << "Time : " << time << std::endl; /* Position the signals corresponding to sensors. */ stateSOUT .setConstant( state_ ); ml::Vector forceNull(6); forceNull.fill(0); for( int i=0;i<4;++i ){ if( withForceSignals[i] ) forcesSOUT[i]->setConstant(forceNull); } ml::Vector zmp(3); zmp.fill( .0 ); ZMPPreviousControllerSOUT .setConstant( zmp ); // Run Synchronous commands and evaluate signals outside the main // connected component of the graph. periodicCallBefore_.run(time+1); /* Force the recomputation of the control. */ controlSIN( time+1 ); sotDEBUG(25) << "u" <<time<<" = " << controlSIN.accessCopy() << endl; /* Integration of numerical values. This function is virtual. */ integrate( dt ); sotDEBUG(25) << "q" << time << " = " << state_ << endl; // Run Synchronous commands and evaluate signals outside the main // connected component of the graph. periodicCallAfter_.run(time+1); // Others signals. motorcontrolSOUT .setConstant( state_ ); } void Device::integrate( const double & dt ) { const ml::Vector & control = controlSIN.accessCopy(); // If control size is state size - 6, integrate joint angles, // if control and state are of same size, integrate 6 first degrees of // freedom as a translation and roll pitch yaw. unsigned int offset = 6; if (control.size() == state_.size()) { offset = 0; integrateRollPitchYaw(state_, control, dt); } for( unsigned int i=6;i<state_.size();++i ) { state_(i) += (control(i-offset)*dt); } } /* --- DISPLAY ------------------------------------------------------------ */ void Device::display ( std::ostream& os ) const {os <<name<<": "<<state_<<endl; } <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2008 Sacha Schutz <[email protected]> * Copyright (C) 2008 Olivier Gueudelot <[email protected]> * Copyright (C) 2008 Charles Huet <[email protected]> * Copyright (c) 2010 Arjen Hiemstra <[email protected]> * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "item.h" #include <QtGui/QMatrix4x4> #include <core/debughelper.h> #include "mesh.h" #include "camera.h" #include "frustrum.h" #include "engine.h" #include "math.h" #include "materialinstance.h" #include "material.h" #include "glheaders.h" using namespace GluonGraphics; class Item::ItemPrivate { public: ItemPrivate() { materialInstance = 0; } Mesh* mesh; QMatrix4x4 transform; MaterialInstance* materialInstance; }; Item::Item( QObject* parent ) : QObject( parent ), d( new ItemPrivate ) { d->materialInstance = Engine::instance()->material( "default" )->instance( "default" ); } Item::~Item() { delete d; } Mesh* Item::mesh() { return d->mesh; } QMatrix4x4 Item::transform() { return d->transform; } MaterialInstance* Item::materialInstance() { return d->materialInstance; } void Item::render() { render( d->materialInstance, GL_TRIANGLES ); } void Item::render( MaterialInstance* material, uint mode ) { Camera* activeCam = Engine::instance()->activeCamera(); if( !activeCam ) return; #ifdef __GNUC__ #warning ToDo: Implement view frustum culling. After all, that is what that damn class is for... ;) #endif QMatrix4x4 modelViewProj = Math::calculateModelViewProj( d->transform, activeCam->viewMatrix(), activeCam->frustrum()->projectionMatrix() ); if(!material->bind()) return; material->setModelViewProjectionMatrix( modelViewProj ); d->mesh->render( material, mode ); material->release(); } void Item::setTransform( const QMatrix4x4 transform ) { d->transform = transform; } void Item::setMesh( Mesh* mesh ) { d->mesh = mesh; } void Item::setMaterialInstance( MaterialInstance* instance ) { d->materialInstance = instance; } #include "item.moc" <commit_msg>Don't crash when rendering if the mesh wasn't set.<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2008 Sacha Schutz <[email protected]> * Copyright (C) 2008 Olivier Gueudelot <[email protected]> * Copyright (C) 2008 Charles Huet <[email protected]> * Copyright (c) 2010 Arjen Hiemstra <[email protected]> * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "item.h" #include <QtGui/QMatrix4x4> #include <core/debughelper.h> #include "mesh.h" #include "camera.h" #include "frustrum.h" #include "engine.h" #include "math.h" #include "materialinstance.h" #include "material.h" #include "glheaders.h" using namespace GluonGraphics; class Item::ItemPrivate { public: ItemPrivate() { mesh = 0; materialInstance = 0; } Mesh* mesh; QMatrix4x4 transform; MaterialInstance* materialInstance; }; Item::Item( QObject* parent ) : QObject( parent ), d( new ItemPrivate ) { d->materialInstance = Engine::instance()->material( "default" )->instance( "default" ); } Item::~Item() { delete d; } Mesh* Item::mesh() { return d->mesh; } QMatrix4x4 Item::transform() { return d->transform; } MaterialInstance* Item::materialInstance() { return d->materialInstance; } void Item::render() { render( d->materialInstance, GL_TRIANGLES ); } void Item::render( MaterialInstance* material, uint mode ) { if( !d->mesh ) return; Camera* activeCam = Engine::instance()->activeCamera(); if( !activeCam ) return; #ifdef __GNUC__ #warning ToDo: Implement view frustum culling. After all, that is what that damn class is for... ;) #endif QMatrix4x4 modelViewProj = Math::calculateModelViewProj( d->transform, activeCam->viewMatrix(), activeCam->frustrum()->projectionMatrix() ); if(!material->bind()) return; material->setModelViewProjectionMatrix( modelViewProj ); d->mesh->render( material, mode ); material->release(); } void Item::setTransform( const QMatrix4x4 transform ) { d->transform = transform; } void Item::setMesh( Mesh* mesh ) { d->mesh = mesh; } void Item::setMaterialInstance( MaterialInstance* instance ) { d->materialInstance = instance; } #include "item.moc" <|endoftext|>
<commit_before>/* Copyright (c) 2015-2019, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include "tredisdriver.h" #include "tsystemglobal.h" #include <TApplicationServerBase> #include <QEventLoop> #include <QElapsedTimer> #include <QTcpSocket> #include <QThread> using namespace Tf; constexpr int DEFAULT_PORT = 6379; constexpr int SEND_BUF_SIZE = 128 * 1024; constexpr int RECV_BUF_SIZE = 128 * 1024; TRedisDriver::TRedisDriver() : TKvsDriver() { _buffer.reserve(1023); } TRedisDriver::~TRedisDriver() { close(); delete _client; } bool TRedisDriver::isOpen() const { return (_client) ? (_client->state() == QAbstractSocket::ConnectedState) : false; } bool TRedisDriver::open(const QString &, const QString &, const QString &, const QString &host, quint16 port, const QString &) { if (isOpen()) { return true; } if (! _client) { _client = new QTcpSocket(); } if (_client->state() != QAbstractSocket::UnconnectedState) { return false; } // Sets socket options _client->setSocketOption(QAbstractSocket::LowDelayOption, 1); // Sets buffer size of socket int val = _client->socketOption(QAbstractSocket::SendBufferSizeSocketOption).toInt(); if (val < SEND_BUF_SIZE) { _client->setSocketOption(QAbstractSocket::SendBufferSizeSocketOption, SEND_BUF_SIZE); } val = _client->socketOption(QAbstractSocket::ReceiveBufferSizeSocketOption).toInt(); if (val < RECV_BUF_SIZE) { _client->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption, RECV_BUF_SIZE); } _host = (host.isEmpty()) ? "localhost" : host; _port = (port == 0) ? DEFAULT_PORT : port; return connectToRedisServer(); } bool TRedisDriver::connectToRedisServer() { tSystemDebug("Redis open host:%s port:%d", qPrintable(_host), _port); _client->connectToHost(_host, _port); bool ret = _client->waitForConnected(5000); if (Q_LIKELY(ret)) { tSystemDebug("Redis open successfully"); } else { tSystemError("Redis open failed"); close(); } return ret; } void TRedisDriver::close() { if (_client) { _client->close(); } } bool TRedisDriver::readReply() { if (Q_UNLIKELY(!isOpen())) { tSystemError("Not open Redis session [%s:%d]", __FILE__, __LINE__); return false; } bool ret = _client->waitForReadyRead(5000); if (ret) { _buffer += _client->readAll(); } else { tSystemWarn("Redis response timeout"); } //tSystemDebug("#Redis response length: %d", _buffer.length()); //tSystemDebug("#Redis response data: %s", _buffer.data()); return ret; } bool TRedisDriver::command(const QString &cmd) { QByteArrayList reqcmd = cmd.trimmed().toUtf8().split(' '); reqcmd.removeAll(""); QVariantList response; return request(reqcmd, response); } bool TRedisDriver::request(const QByteArrayList &command, QVariantList &response) { if (Q_UNLIKELY(!isOpen())) { tSystemError("Not open Redis session [%s:%d]", __FILE__, __LINE__); return false; } bool ret = true; bool ok = false; QByteArray str; QByteArray cmd = toMultiBulk(command); tSystemDebug("Redis command: %s", cmd.data()); _client->write(cmd); clearBuffer(); for (;;) { if (! readReply()) { tSystemError("Redis read error pos:%d buflen:%d", _pos, _buffer.length()); break; } switch (_buffer.at(_pos)) { case Error: ret = false; str = getLine(&ok); tSystemError("Redis error response: %s", qPrintable(str)); break; case SimpleString: str = getLine(&ok); tSystemDebug("Redis response: %s", qPrintable(str)); break; case Integer: { _pos++; int num = getNumber(&ok); if (ok) { response << num; } break; } case BulkString: str = parseBulkString(&ok); if (ok) { response << str; } break; case Array: response = parseArray(&ok); if (!ok) { response.clear(); } break; default: tSystemError("Invalid protocol: %c [%s:%d]", _buffer.at(_pos), __FILE__, __LINE__); ret = false; clearBuffer(); goto parse_done; break; } if (ok) { if (_pos < _buffer.length()) { tSystemError("Invalid format [%s:%d]", __FILE__, __LINE__); } clearBuffer(); break; } _pos = 0; // retry to read.. } parse_done: return ret; } QByteArray TRedisDriver::getLine(bool *ok) { int idx = _buffer.indexOf(CRLF, _pos); if (idx < 0) { *ok = false; return QByteArray(); } QByteArray ret = _buffer.mid(_pos, idx); _pos = idx + 2; *ok = true; return ret; } QByteArray TRedisDriver::parseBulkString(bool *ok) { QByteArray str; int startpos = _pos; Q_ASSERT((int)_buffer[_pos] == BulkString); _pos++; int len = getNumber(ok); if (*ok) { if (len < -1) { tSystemError("Invalid length: %d [%s:%d]", len, __FILE__, __LINE__); *ok = false; } else if (len == -1) { // null string tSystemDebug("Null string parsed"); } else { if (_pos + 2 <= _buffer.length()) { str = (len > 0) ? _buffer.mid(_pos, len) : QByteArray(""); _pos += len + 2; } else { *ok = false; } } } if (! *ok) { _pos = startpos; } return str; } QVariantList TRedisDriver::parseArray(bool *ok) { QVariantList lst; int startpos = _pos; *ok = false; Q_ASSERT((int)_buffer[_pos] == Array); _pos++; int count = getNumber(ok); while (*ok) { switch (_buffer[_pos]) { case BulkString: { auto str = parseBulkString(ok); if (*ok) { lst << str; } break; } case Integer: { _pos++; int num = getNumber(ok); if (*ok) { lst << num; } break; } case Array: { auto var = parseArray(ok); if (*ok) { lst << QVariant(var); } break; } default: tSystemError("Bad logic [%s:%d]", __FILE__, __LINE__); *ok = false; break; } if (lst.count() >= count) { break; } } if (! *ok) { _pos = startpos; } return lst; } int TRedisDriver::getNumber(bool *ok) { int idx = _buffer.indexOf(CRLF, _pos); if (idx < 0) { *ok = false; return 0; } int num = _buffer.mid(_pos, idx - _pos).toInt(); _pos = idx + 2; *ok = true; tSystemDebug("getNumber: %d", num); return num; } void TRedisDriver::clearBuffer() { _buffer.resize(0); _pos = 0; } QByteArray TRedisDriver::toBulk(const QByteArray &data) { QByteArray bulk("$"); bulk += QByteArray::number(data.length()); bulk += CRLF; bulk += data; bulk += CRLF; return bulk; } QByteArray TRedisDriver::toMultiBulk(const QByteArrayList &data) { QByteArray mbulk("*"); mbulk += QByteArray::number(data.count()); mbulk += CRLF; for (auto &d : data) { mbulk += toBulk(d); } return mbulk; } void TRedisDriver::moveToThread(QThread *thread) { if (!_client || _client->thread() == thread) { return; } int socket = _client->socketDescriptor(); QAbstractSocket::SocketState state = QAbstractSocket::ConnectedState; if (socket > 0) { socket = TApplicationServerBase::duplicateSocket(socket); state = _client->state(); } delete _client; _client = new QTcpSocket(); if (socket > 0) { _client->setSocketDescriptor(socket, state); } _client->moveToThread(thread); } <commit_msg>bugfixes.<commit_after>/* Copyright (c) 2015-2019, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include "tredisdriver.h" #include "tsystemglobal.h" #include <TApplicationServerBase> #include <QEventLoop> #include <QElapsedTimer> #include <QTcpSocket> #include <QThread> using namespace Tf; constexpr int DEFAULT_PORT = 6379; constexpr int SEND_BUF_SIZE = 128 * 1024; constexpr int RECV_BUF_SIZE = 128 * 1024; TRedisDriver::TRedisDriver() : TKvsDriver() { _buffer.reserve(1023); } TRedisDriver::~TRedisDriver() { close(); delete _client; } bool TRedisDriver::isOpen() const { return (_client) ? (_client->state() == QAbstractSocket::ConnectedState) : false; } bool TRedisDriver::open(const QString &, const QString &, const QString &, const QString &host, quint16 port, const QString &) { if (isOpen()) { return true; } if (! _client) { _client = new QTcpSocket(); } if (_client->state() != QAbstractSocket::UnconnectedState) { return false; } // Sets socket options _client->setSocketOption(QAbstractSocket::LowDelayOption, 1); // Sets buffer size of socket int val = _client->socketOption(QAbstractSocket::SendBufferSizeSocketOption).toInt(); if (val < SEND_BUF_SIZE) { _client->setSocketOption(QAbstractSocket::SendBufferSizeSocketOption, SEND_BUF_SIZE); } val = _client->socketOption(QAbstractSocket::ReceiveBufferSizeSocketOption).toInt(); if (val < RECV_BUF_SIZE) { _client->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption, RECV_BUF_SIZE); } _host = (host.isEmpty()) ? "localhost" : host; _port = (port == 0) ? DEFAULT_PORT : port; return connectToRedisServer(); } bool TRedisDriver::connectToRedisServer() { tSystemDebug("Redis open host:%s port:%d", qPrintable(_host), _port); _client->connectToHost(_host, _port); bool ret = _client->waitForConnected(5000); if (Q_LIKELY(ret)) { tSystemDebug("Redis open successfully"); } else { tSystemError("Redis open failed"); close(); } return ret; } void TRedisDriver::close() { if (_client) { _client->close(); } } bool TRedisDriver::readReply() { if (Q_UNLIKELY(!isOpen())) { tSystemError("Not open Redis session [%s:%d]", __FILE__, __LINE__); return false; } bool ret = _client->waitForReadyRead(5000); if (ret) { _buffer += _client->readAll(); } else { tSystemWarn("Redis response timeout"); } //tSystemDebug("#Redis response length: %d", _buffer.length()); //tSystemDebug("#Redis response data: %s", _buffer.data()); return ret; } bool TRedisDriver::command(const QString &cmd) { QByteArrayList reqcmd = cmd.trimmed().toUtf8().split(' '); reqcmd.removeAll(""); QVariantList response; return request(reqcmd, response); } bool TRedisDriver::request(const QByteArrayList &command, QVariantList &response) { if (Q_UNLIKELY(!isOpen())) { tSystemError("Not open Redis session [%s:%d]", __FILE__, __LINE__); return false; } bool ret = true; bool ok = false; QByteArray str; QByteArray cmd = toMultiBulk(command); tSystemDebug("Redis command: %s", cmd.data()); _client->write(cmd); clearBuffer(); for (;;) { if (! readReply()) { tSystemError("Redis read error pos:%d buflen:%d", _pos, _buffer.length()); break; } switch (_buffer.at(_pos)) { case Error: ret = false; str = getLine(&ok); tSystemError("Redis error response: %s", qPrintable(str)); break; case SimpleString: str = getLine(&ok); tSystemDebug("Redis response: %s", qPrintable(str)); break; case Integer: { _pos++; int num = getNumber(&ok); if (ok) { response << num; } break; } case BulkString: str = parseBulkString(&ok); if (ok) { response << str; } break; case Array: response = parseArray(&ok); if (!ok) { response.clear(); } break; default: tSystemError("Invalid protocol: %c [%s:%d]", _buffer.at(_pos), __FILE__, __LINE__); ret = false; clearBuffer(); goto parse_done; break; } if (ok) { if (_pos < _buffer.length()) { tSystemError("Invalid format [%s:%d]", __FILE__, __LINE__); } clearBuffer(); break; } _pos = 0; // retry to read.. } parse_done: return ret; } QByteArray TRedisDriver::getLine(bool *ok) { int idx = _buffer.indexOf(CRLF, _pos); if (idx < 0) { *ok = false; return QByteArray(); } QByteArray ret = _buffer.mid(_pos, idx); _pos = idx + 2; *ok = true; return ret; } QByteArray TRedisDriver::parseBulkString(bool *ok) { QByteArray str; int startpos = _pos; Q_ASSERT((int)_buffer[_pos] == BulkString); _pos++; int len = getNumber(ok); if (*ok) { if (len < -1) { tSystemError("Invalid length: %d [%s:%d]", len, __FILE__, __LINE__); *ok = false; } else if (len == -1) { // null string tSystemDebug("Null string parsed"); } else { if (_pos + 2 <= _buffer.length()) { str = (len > 0) ? _buffer.mid(_pos, len) : QByteArray(""); _pos += len + 2; } else { *ok = false; } } } if (! *ok) { _pos = startpos; } return str; } QVariantList TRedisDriver::parseArray(bool *ok) { QVariantList lst; int startpos = _pos; *ok = false; Q_ASSERT((int)_buffer[_pos] == Array); _pos++; int count = getNumber(ok); while (*ok) { switch (_buffer[_pos]) { case BulkString: { auto str = parseBulkString(ok); if (*ok) { lst << str; } break; } case Integer: { _pos++; int num = getNumber(ok); if (*ok) { lst << num; } break; } case Array: { auto var = parseArray(ok); if (*ok) { lst << QVariant(var); } break; } default: tSystemError("Bad logic [%s:%d]", __FILE__, __LINE__); *ok = false; break; } if (lst.count() >= count) { break; } } if (! *ok) { _pos = startpos; } return lst; } int TRedisDriver::getNumber(bool *ok) { int idx = _buffer.indexOf(CRLF, _pos); if (idx < 0) { *ok = false; return 0; } int num = _buffer.mid(_pos, idx - _pos).toInt(); _pos = idx + 2; *ok = true; tSystemDebug("getNumber: %d", num); return num; } void TRedisDriver::clearBuffer() { _buffer.resize(0); _pos = 0; } QByteArray TRedisDriver::toBulk(const QByteArray &data) { QByteArray bulk("$"); bulk += QByteArray::number(data.length()); bulk += CRLF; bulk += data; bulk += CRLF; return bulk; } QByteArray TRedisDriver::toMultiBulk(const QByteArrayList &data) { QByteArray mbulk("*"); mbulk += QByteArray::number(data.count()); mbulk += CRLF; for (auto &d : data) { mbulk += toBulk(d); } return mbulk; } void TRedisDriver::moveToThread(QThread *thread) { int socket = 0; QAbstractSocket::SocketState state = QAbstractSocket::ConnectedState; if (_client) { socket = _client->socketDescriptor(); if (socket > 0) { socket = TApplicationServerBase::duplicateSocket(socket); state = _client->state(); } delete _client; } _client = new QTcpSocket; _client->moveToThread(thread); if (socket > 0) { _client->setSocketDescriptor(socket, state); } } <|endoftext|>
<commit_before>#ifndef utf8_iterator_hh_INCLUDED #define utf8_iterator_hh_INCLUDED #include "utf8.hh" #include <iterator> namespace Kakoune { namespace utf8 { // adapter for an iterator on bytes which permits to iterate // on unicode codepoints instead. template<typename BaseIt, typename Sentinel = BaseIt, typename CodepointType = Codepoint, typename DifferenceType = CharCount, typename InvalidPolicy = utf8::InvalidPolicy::Pass> class iterator : public std::iterator<std::bidirectional_iterator_tag, CodepointType, DifferenceType, CodepointType*, CodepointType> { public: iterator() = default; constexpr static bool noexcept_policy = noexcept(InvalidPolicy{}(0)); iterator(BaseIt it, Sentinel begin, Sentinel end) noexcept : m_it{std::move(it)}, m_begin{std::move(begin)}, m_end{std::move(end)} {} template<typename Container> iterator(BaseIt it, const Container& c) noexcept : m_it{std::move(it)}, m_begin{std::begin(c)}, m_end{std::end(c)} {} iterator& operator++() noexcept { utf8::to_next(m_it, m_end); invalidate_value(); return *this; } iterator operator++(int) noexcept { iterator save = *this; ++*this; return save; } iterator& operator--() noexcept { utf8::to_previous(m_it, m_begin); invalidate_value(); return *this; } iterator operator--(int) noexcept { iterator save = *this; --*this; return save; } iterator operator+(DifferenceType count) const noexcept { iterator res = *this; res += count; return res; } iterator& operator+=(DifferenceType count) noexcept { if (count < 0) return operator-=(-count); while (count--) operator++(); return *this; } iterator operator-(DifferenceType count) const noexcept { iterator res = *this; res -= count; return res; } iterator& operator-=(DifferenceType count) noexcept { if (count < 0) return operator+=(-count); while (count--) operator--(); return *this; } bool operator==(const iterator& other) const noexcept { return m_it == other.m_it; } bool operator!=(const iterator& other) const noexcept { return m_it != other.m_it; } bool operator< (const iterator& other) const noexcept { return m_it < other.m_it; } bool operator<= (const iterator& other) const noexcept { return m_it <= other.m_it; } bool operator> (const iterator& other) const noexcept { return m_it > other.m_it; } bool operator>= (const iterator& other) const noexcept { return m_it >= other.m_it; } template<typename T> std::enable_if_t<std::is_same<T, BaseIt>::value or std::is_same<T, Sentinel>::value, bool> operator==(const T& other) const noexcept { return m_it == other; } template<typename T> std::enable_if_t<std::is_same<T, BaseIt>::value or std::is_same<T, Sentinel>::value, bool> operator!=(const T& other) const noexcept { return m_it != other; } bool operator< (const BaseIt& other) const noexcept { return m_it < other; } bool operator<= (const BaseIt& other) const noexcept { return m_it <= other; } bool operator> (const BaseIt& other) const noexcept { return m_it > other; } bool operator>= (const BaseIt& other) const noexcept { return m_it >= other; } DifferenceType operator-(const iterator& other) const noexcept(noexcept_policy) { return (DifferenceType)utf8::distance<InvalidPolicy>(other.m_it, m_it); } CodepointType operator*() const noexcept(noexcept_policy) { return get_value(); } CodepointType read() noexcept(noexcept_policy) { return (CodepointType)utf8::read_codepoint<InvalidPolicy>(m_it, m_end); } const BaseIt& base() const noexcept(noexcept_policy) { return m_it; } private: void invalidate_value() noexcept { m_value = -1; } CodepointType get_value() const noexcept(noexcept_policy) { if (m_value == (CodepointType)-1) m_value = (CodepointType)utf8::codepoint<InvalidPolicy>(m_it, m_end); return m_value; } BaseIt m_it; Sentinel m_begin; Sentinel m_end; mutable CodepointType m_value = -1; }; } } #endif // utf8_iterator_hh_INCLUDED <commit_msg>Remove caching from utf8_iterator<commit_after>#ifndef utf8_iterator_hh_INCLUDED #define utf8_iterator_hh_INCLUDED #include "utf8.hh" #include <iterator> namespace Kakoune { namespace utf8 { // adapter for an iterator on bytes which permits to iterate // on unicode codepoints instead. template<typename BaseIt, typename Sentinel = BaseIt, typename CodepointType = Codepoint, typename DifferenceType = CharCount, typename InvalidPolicy = utf8::InvalidPolicy::Pass> class iterator : public std::iterator<std::bidirectional_iterator_tag, CodepointType, DifferenceType, CodepointType*, CodepointType> { public: iterator() = default; constexpr static bool noexcept_policy = noexcept(InvalidPolicy{}(0)); iterator(BaseIt it, Sentinel begin, Sentinel end) noexcept : m_it{std::move(it)}, m_begin{std::move(begin)}, m_end{std::move(end)} {} template<typename Container> iterator(BaseIt it, const Container& c) noexcept : m_it{std::move(it)}, m_begin{std::begin(c)}, m_end{std::end(c)} {} iterator& operator++() noexcept { utf8::to_next(m_it, m_end); return *this; } iterator operator++(int) noexcept { iterator save = *this; ++*this; return save; } iterator& operator--() noexcept { utf8::to_previous(m_it, m_begin); return *this; } iterator operator--(int) noexcept { iterator save = *this; --*this; return save; } iterator operator+(DifferenceType count) const noexcept { iterator res = *this; res += count; return res; } iterator& operator+=(DifferenceType count) noexcept { if (count < 0) return operator-=(-count); while (count--) operator++(); return *this; } iterator operator-(DifferenceType count) const noexcept { iterator res = *this; res -= count; return res; } iterator& operator-=(DifferenceType count) noexcept { if (count < 0) return operator+=(-count); while (count--) operator--(); return *this; } bool operator==(const iterator& other) const noexcept { return m_it == other.m_it; } bool operator!=(const iterator& other) const noexcept { return m_it != other.m_it; } bool operator< (const iterator& other) const noexcept { return m_it < other.m_it; } bool operator<= (const iterator& other) const noexcept { return m_it <= other.m_it; } bool operator> (const iterator& other) const noexcept { return m_it > other.m_it; } bool operator>= (const iterator& other) const noexcept { return m_it >= other.m_it; } template<typename T> std::enable_if_t<std::is_same<T, BaseIt>::value or std::is_same<T, Sentinel>::value, bool> operator==(const T& other) const noexcept { return m_it == other; } template<typename T> std::enable_if_t<std::is_same<T, BaseIt>::value or std::is_same<T, Sentinel>::value, bool> operator!=(const T& other) const noexcept { return m_it != other; } bool operator< (const BaseIt& other) const noexcept { return m_it < other; } bool operator<= (const BaseIt& other) const noexcept { return m_it <= other; } bool operator> (const BaseIt& other) const noexcept { return m_it > other; } bool operator>= (const BaseIt& other) const noexcept { return m_it >= other; } DifferenceType operator-(const iterator& other) const noexcept(noexcept_policy) { return (DifferenceType)utf8::distance<InvalidPolicy>(other.m_it, m_it); } CodepointType operator*() const noexcept(noexcept_policy) { return (CodepointType)utf8::codepoint<InvalidPolicy>(m_it, m_end); } CodepointType read() noexcept(noexcept_policy) { return (CodepointType)utf8::read_codepoint<InvalidPolicy>(m_it, m_end); } const BaseIt& base() const noexcept(noexcept_policy) { return m_it; } private: BaseIt m_it; Sentinel m_begin; Sentinel m_end; }; } } #endif // utf8_iterator_hh_INCLUDED <|endoftext|>