commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
935ce92a8a1916e612df2274b34b83d0266c78f1
src/_viennacl/sparse_matrix.hpp
src/_viennacl/sparse_matrix.hpp
#ifndef _PYVIENNACL_VECTOR_H #define _PYVIENNACL_VECTOR_H #include "common.hpp" #include <boost/numeric/ublas/matrix_sparse.hpp> #include <boost/numeric/ublas/vector_of_vector.hpp> #include <viennacl/linalg/sparse_matrix_operations.hpp> #include <viennacl/compressed_matrix.hpp> #include <viennacl/compressed_compressed_matrix.hpp> #include <viennacl/coordinate_matrix.hpp> #include <viennacl/ell_matrix.hpp> #include <viennacl/hyb_matrix.hpp> namespace ublas = boost::numeric::ublas; template <class ScalarType> class cpu_compressed_matrix_wrapper { typedef ublas::compressed_matrix<ScalarType, ublas::row_major> ublas_sparse_t; ublas_sparse_t cpu_compressed_matrix; bool _dirty; bp::list* _places; vcl::context _context; public: void update_places() { if (!_dirty) return; typedef typename ublas_sparse_t::iterator1 it1; typedef typename ublas_sparse_t::iterator2 it2; if (_places) delete _places; _places = new bp::list; for (it1 i = cpu_compressed_matrix.begin1(); i != cpu_compressed_matrix.end1(); ++i) { for (it2 j = i.begin(); j != i.end(); ++j) { if (cpu_compressed_matrix(j.index1(), j.index2())) { _places->append(bp::make_tuple(j.index1(), j.index2())); } } } _dirty = false; } bp::list places() { if (_dirty) update_places(); return *_places; } vcl::vcl_size_t nnz() { if (_dirty) update_places(); return bp::len(*_places); } cpu_compressed_matrix_wrapper() { _places = NULL; set_vcl_context(vcl::context()); cpu_compressed_matrix = ublas_sparse_t(0,0,0); } cpu_compressed_matrix_wrapper(vcl::vcl_size_t _size1, vcl::vcl_size_t _size2) { _places = NULL; set_vcl_context(vcl::context()); cpu_compressed_matrix = ublas_sparse_t(_size1, _size2); } cpu_compressed_matrix_wrapper(vcl::vcl_size_t _size1, vcl::vcl_size_t _size2, vcl::vcl_size_t _nnz) { _places = NULL; set_vcl_context(vcl::context()); cpu_compressed_matrix = ublas_sparse_t(_size1, _size2, _nnz); } cpu_compressed_matrix_wrapper(const cpu_compressed_matrix_wrapper& w) : cpu_compressed_matrix(w.cpu_compressed_matrix) { _places = NULL; set_vcl_context(vcl::context()); _dirty = true; } template<class SparseT> cpu_compressed_matrix_wrapper(const SparseT& vcl_sparse_matrix) { cpu_compressed_matrix = ublas_sparse_t(vcl_sparse_matrix.size1(), vcl_sparse_matrix.size2()); vcl::copy(vcl_sparse_matrix, cpu_compressed_matrix); set_vcl_context(vcl::context()); _places = NULL; _dirty = true; } cpu_compressed_matrix_wrapper(const np::ndarray& array) { _places = NULL; set_vcl_context(vcl::context()); int d = array.get_nd(); if (d != 2) { PyErr_SetString(PyExc_TypeError, "Can only create a matrix from a 2-D array!"); bp::throw_error_already_set(); } vcl::vcl_size_t n = array.shape(0); vcl::vcl_size_t m = array.shape(1); cpu_compressed_matrix = ublas_sparse_t(n, m); for (vcl::vcl_size_t i = 0; i < n; ++i) { for (vcl::vcl_size_t j = 0; j < m; ++j) { ScalarType val = bp::extract<ScalarType>(array[i][j]); if (val != 0) set_entry(i, j, val); } } } np::ndarray as_ndarray() { np::dtype dt = np::dtype::get_builtin<ScalarType>(); bp::tuple shape = bp::make_tuple(size1(), size2()); np::ndarray array = np::zeros(shape, dt); typedef typename ublas_sparse_t::iterator1 it1; typedef typename ublas_sparse_t::iterator2 it2; for (it1 i = cpu_compressed_matrix.begin1(); i != cpu_compressed_matrix.end1(); ++i) { for (it2 j = i.begin(); j != i.end(); ++j) { if (cpu_compressed_matrix(j.index1(), j.index2()) != 0) { array[j.index1()][j.index2()] = get_entry(j.index1(), j.index2()); } } } return array; } template<class SparseT> vcl::tools::shared_ptr<SparseT> as_vcl_sparse_matrix() { SparseT* vcl_sparse_matrix = new SparseT(_context); vcl::copy(cpu_compressed_matrix, *vcl_sparse_matrix); return vcl::tools::shared_ptr<SparseT>(vcl_sparse_matrix); } template<class SparseT> vcl::tools::shared_ptr<SparseT> as_vcl_sparse_matrix_with_size() { SparseT* vcl_sparse_matrix = new SparseT(size1(), size2(), nnz(), _context); vcl::copy(cpu_compressed_matrix, *vcl_sparse_matrix); return vcl::tools::shared_ptr<SparseT>(vcl_sparse_matrix); } vcl::vcl_size_t size1() const { return cpu_compressed_matrix.size1(); } vcl::vcl_size_t size2() const { return cpu_compressed_matrix.size2(); } void resize(vcl::vcl_size_t _size1, vcl::vcl_size_t _size2) { if ((_size1 == size1()) && (_size2 == size2())) return; // TODO NB: ublas compressed matrix does not support preserve on resize // so this below is annoyingly hacky... ublas_sparse_t temp(cpu_compressed_matrix); // Incurs a copy of all the data!! cpu_compressed_matrix.resize(_size1, _size2, false); // preserve == false! /* if (_places) delete _places; _places = new bp::list; */ typedef typename ublas_sparse_t::iterator1 it1; typedef typename ublas_sparse_t::iterator2 it2; for (it1 i = temp.begin1(); i != temp.end1(); ++i) { for (it2 j = i.begin(); j != i.end(); ++j) { if ((temp(j.index1(), j.index2()) != 0) && (j.index1() < _size1) && (j.index2() < _size2)) { cpu_compressed_matrix(j.index1(), j.index2()) = temp(j.index1(), j.index2()); //_places->append(bp::make_tuple(j.index1(), j.index2())); } } } _dirty = true; //false; } void set_vcl_context(vcl::context ctx) { _context = ctx; } const vcl::context& get_vcl_context() const { return _context; } void set_entry(vcl::vcl_size_t n, vcl::vcl_size_t m, ScalarType val) { if (n >= size1()) { if (m >= size2()) resize(n+1, m+1); else resize(n+1, size2()); } else { if (m >= size2()) resize(size1(), m+1); } ScalarType old = cpu_compressed_matrix(n, m); if (val != old) { cpu_compressed_matrix(n, m) = val; _dirty = true; } } // Need this because bp cannot deal with operator() ScalarType get_entry(vcl::vcl_size_t n, vcl::vcl_size_t m) const { return cpu_compressed_matrix(n, m); } }; #endif
#ifndef _PYVIENNACL_VECTOR_H #define _PYVIENNACL_VECTOR_H #include "common.hpp" #include <boost/numeric/ublas/matrix_sparse.hpp> #include <boost/numeric/ublas/vector_of_vector.hpp> #include <viennacl/linalg/sparse_matrix_operations.hpp> #include <viennacl/compressed_matrix.hpp> #include <viennacl/compressed_compressed_matrix.hpp> #include <viennacl/coordinate_matrix.hpp> #include <viennacl/ell_matrix.hpp> #include <viennacl/hyb_matrix.hpp> namespace ublas = boost::numeric::ublas; template <class ScalarType> class cpu_compressed_matrix_wrapper { typedef ublas::compressed_matrix<ScalarType, ublas::row_major> ublas_sparse_t; ublas_sparse_t cpu_compressed_matrix; bool _dirty; bp::list* _places; vcl::context _context; public: void update_places() { if (!_dirty) return; typedef typename ublas_sparse_t::iterator1 it1; typedef typename ublas_sparse_t::iterator2 it2; if (_places) delete _places; _places = new bp::list; for (it1 i = cpu_compressed_matrix.begin1(); i != cpu_compressed_matrix.end1(); ++i) { for (it2 j = i.begin(); j != i.end(); ++j) { if (cpu_compressed_matrix(j.index1(), j.index2())) { _places->append(bp::make_tuple(j.index1(), j.index2())); } } } _dirty = false; } bp::list places() { if (_dirty) update_places(); return *_places; } vcl::vcl_size_t nnz() { if (_dirty) update_places(); return bp::len(*_places); } cpu_compressed_matrix_wrapper() : _dirty(true) { _places = NULL; set_vcl_context(vcl::context()); cpu_compressed_matrix = ublas_sparse_t(0,0,0); } cpu_compressed_matrix_wrapper(vcl::vcl_size_t _size1, vcl::vcl_size_t _size2) : _dirty(true) { _places = NULL; set_vcl_context(vcl::context()); cpu_compressed_matrix = ublas_sparse_t(_size1, _size2); } cpu_compressed_matrix_wrapper(vcl::vcl_size_t _size1, vcl::vcl_size_t _size2, vcl::vcl_size_t _nnz) : _dirty(true) { _places = NULL; set_vcl_context(vcl::context()); cpu_compressed_matrix = ublas_sparse_t(_size1, _size2, _nnz); } cpu_compressed_matrix_wrapper(const cpu_compressed_matrix_wrapper& w) : cpu_compressed_matrix(w.cpu_compressed_matrix), _dirty(true) { _places = NULL; set_vcl_context(vcl::context()); } template<class SparseT> cpu_compressed_matrix_wrapper(const SparseT& vcl_sparse_matrix) : _dirty(true) { cpu_compressed_matrix = ublas_sparse_t(vcl_sparse_matrix.size1(), vcl_sparse_matrix.size2()); vcl::copy(vcl_sparse_matrix, cpu_compressed_matrix); set_vcl_context(vcl::context()); _places = NULL; } cpu_compressed_matrix_wrapper(const np::ndarray& array) : _dirty(true) { _places = NULL; set_vcl_context(vcl::context()); int d = array.get_nd(); if (d != 2) { PyErr_SetString(PyExc_TypeError, "Can only create a matrix from a 2-D array!"); bp::throw_error_already_set(); } vcl::vcl_size_t n = array.shape(0); vcl::vcl_size_t m = array.shape(1); cpu_compressed_matrix = ublas_sparse_t(n, m); for (vcl::vcl_size_t i = 0; i < n; ++i) { for (vcl::vcl_size_t j = 0; j < m; ++j) { ScalarType val = bp::extract<ScalarType>(array[i][j]); if (val != 0) set_entry(i, j, val); } } } np::ndarray as_ndarray() { np::dtype dt = np::dtype::get_builtin<ScalarType>(); bp::tuple shape = bp::make_tuple(size1(), size2()); np::ndarray array = np::zeros(shape, dt); typedef typename ublas_sparse_t::iterator1 it1; typedef typename ublas_sparse_t::iterator2 it2; for (it1 i = cpu_compressed_matrix.begin1(); i != cpu_compressed_matrix.end1(); ++i) { for (it2 j = i.begin(); j != i.end(); ++j) { if (cpu_compressed_matrix(j.index1(), j.index2()) != 0) { array[j.index1()][j.index2()] = get_entry(j.index1(), j.index2()); } } } return array; } template<class SparseT> vcl::tools::shared_ptr<SparseT> as_vcl_sparse_matrix() { SparseT* vcl_sparse_matrix = new SparseT(_context); vcl::copy(cpu_compressed_matrix, *vcl_sparse_matrix); return vcl::tools::shared_ptr<SparseT>(vcl_sparse_matrix); } template<class SparseT> vcl::tools::shared_ptr<SparseT> as_vcl_sparse_matrix_with_size() { SparseT* vcl_sparse_matrix = new SparseT(size1(), size2(), nnz(), _context); vcl::copy(cpu_compressed_matrix, *vcl_sparse_matrix); return vcl::tools::shared_ptr<SparseT>(vcl_sparse_matrix); } vcl::vcl_size_t size1() const { return cpu_compressed_matrix.size1(); } vcl::vcl_size_t size2() const { return cpu_compressed_matrix.size2(); } void resize(vcl::vcl_size_t _size1, vcl::vcl_size_t _size2) { if ((_size1 == size1()) && (_size2 == size2())) return; // TODO NB: ublas compressed matrix does not support preserve on resize // so this below is annoyingly hacky... ublas_sparse_t temp(cpu_compressed_matrix); // Incurs a copy of all the data!! cpu_compressed_matrix.resize(_size1, _size2, false); // preserve == false! /* if (_places) delete _places; _places = new bp::list; */ typedef typename ublas_sparse_t::iterator1 it1; typedef typename ublas_sparse_t::iterator2 it2; for (it1 i = temp.begin1(); i != temp.end1(); ++i) { for (it2 j = i.begin(); j != i.end(); ++j) { if ((temp(j.index1(), j.index2()) != 0) && (j.index1() < _size1) && (j.index2() < _size2)) { cpu_compressed_matrix(j.index1(), j.index2()) = temp(j.index1(), j.index2()); //_places->append(bp::make_tuple(j.index1(), j.index2())); } } } _dirty = true; //false; } void set_vcl_context(vcl::context ctx) { _context = ctx; } const vcl::context& get_vcl_context() const { return _context; } void set_entry(vcl::vcl_size_t n, vcl::vcl_size_t m, ScalarType val) { if (n >= size1()) { if (m >= size2()) resize(n+1, m+1); else resize(n+1, size2()); } else { if (m >= size2()) resize(size1(), m+1); } ScalarType old = cpu_compressed_matrix(n, m); if (val != old) { cpu_compressed_matrix(n, m) = val; _dirty = true; } } // Need this because bp cannot deal with operator() ScalarType get_entry(vcl::vcl_size_t n, vcl::vcl_size_t m) const { return cpu_compressed_matrix(n, m); } }; #endif
Fix segfault in sparse matrices
Fix segfault in sparse matrices
C++
mit
opticode/pyviennacl-dev,viennacl/pyviennacl-dev,viennacl/pyviennacl-dev,opticode/pyviennacl-dev
1d3737d453c432bb7f419f639e36aa35c486ad8e
src/aboutapplet/aboutwidget.cpp
src/aboutapplet/aboutwidget.cpp
/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */ /* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */ #include "aboutwidget.h" #include <QGraphicsLinearLayout> #include <MImageWidget> #include <MLabel> #include <QGraphicsLinearLayout> #include <MStylableWidget> #define DEBUG #include "../debug.h" AboutWidget::AboutWidget ( AboutBusinessLogic *aboutBusinessLogic, QGraphicsWidget *parent) : DcpWidget (parent), m_AboutBusinessLogic (aboutBusinessLogic), m_Label1 (0) { connect (aboutBusinessLogic, SIGNAL (ready ()), this, SLOT (dataReady ())); createContent (); aboutBusinessLogic->initiateDataCollection (); } AboutWidget::~AboutWidget () { } void AboutWidget::createContent () { QGraphicsLinearLayout *layout; MImageWidget *logo; QGraphicsLinearLayout *logoLayout; MStylableWidget *stretcher; layout = new QGraphicsLinearLayout (Qt::Vertical); layout->setContentsMargins (0., 0., 0., 0.); /* * A stretcher. */ stretcher = new MStylableWidget (); stretcher->setObjectName ("CommonSpacer"); layout->addItem (stretcher); /* * The first row: a logo */ logoLayout = new QGraphicsLinearLayout (Qt::Horizontal); logo = new MImageWidget ("missing-icon"); logoLayout->addItem (logo); logoLayout->addStretch (); layout->addItem (logoLayout); /* * A stretcher. */ stretcher = new MStylableWidget (); stretcher->setObjectName ("CommonSpacer"); layout->addItem (stretcher); /* * A label... FIXME: This might be wrong, the layout guide seems to define * a stretcher inside the text, so we might want to create two separate * labels... */ m_Label1 = new MLabel; m_Label1->setWordWrap (true); layout->addItem (m_Label1); layout->addStretch (); setLayout (layout); } QString AboutWidget::labelText() { QString retval; retval += "<h3>Name of the product</h3>"; retval += "<h3>" + m_AboutBusinessLogic->osName () + "</h3>"; //% "Version" retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_version")); retval += m_AboutBusinessLogic->osVersion(); //% "WLAN MAC address" retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_wlan_mac_address")); retval += m_AboutBusinessLogic->WiFiAddress (); //% "Bluetooth address" retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_bt_address")); retval += m_AboutBusinessLogic->BluetoothAddress (); //% "IMEI" retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_imei")); retval += m_AboutBusinessLogic->IMEI (); retval += "<hr />"; retval += "<p>This product includes certain free/open source software</p>"; retval += "<p>The exact terms of the licenses, disclaimers, " "aknowledgements and notices are provided in the " "following document/through the following links:" "<a href=\"http://somethink.here\">[insert document/link]</a>. " "You may obtain the source code of the relevant free and open " "source software at " "<a href=\"http://somethink.here\">[insert the URL]</a>. " "Alternatively, Nokia offers to provide such source code to you " "on a CD-ROM upon written request to Nokia at:</p>"; retval += "<p>Maemo Source Code Requests<br>"; retval += "Nokia Corporation<br>"; retval += "P.O.Box 407<br>"; retval += "FI-00045 Nokia Group<br>"; retval += "Finland<br>"; retval += "<p>This offer is valid for a period of three (3) years " "from the date of the distribution of t his product by " "Nokia.</p>"; retval += "<p>The Graphics Interchange Format (c) is the Copyright " "property of CompuServe Incorporated. GIF(sm) is a " "Service Mark property of Compuserve Incorporated.</p>"; retval += "<p>AdobeAE FlashAE Player. Copyright (c) 1996 - 2007 " "Adobe Systems Incorporated. All Rights Reserved. " "Protected by U.S. Patent 6,879,327; Patents Pending in the " "United States and other countries. Adobe and Flas are either " "trademarks or registered trademarks in the United States " "and/or other countries.</p>"; return retval; } void AboutWidget::retranslateUi () { m_Label1->setText (labelText ()); } void AboutWidget::dataReady () { m_Label1->setText (labelText ()); }
/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */ /* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */ #include "aboutwidget.h" #include <QGraphicsLinearLayout> #include <MImageWidget> #include <MLabel> #include <QGraphicsLinearLayout> #include <MStylableWidget> #define DEBUG #include "../debug.h" AboutWidget::AboutWidget ( AboutBusinessLogic *aboutBusinessLogic, QGraphicsWidget *parent) : DcpWidget (parent), m_AboutBusinessLogic (aboutBusinessLogic), m_Label1 (0) { connect (aboutBusinessLogic, SIGNAL (ready ()), this, SLOT (dataReady ())); createContent (); aboutBusinessLogic->initiateDataCollection (); } AboutWidget::~AboutWidget () { } void AboutWidget::createContent () { QGraphicsLinearLayout *layout; MImageWidget *logo; QGraphicsLinearLayout *logoLayout; MStylableWidget *stretcher; layout = new QGraphicsLinearLayout (Qt::Vertical); layout->setContentsMargins (0., 0., 0., 0.); /* * A stretcher. */ stretcher = new MStylableWidget (); stretcher->setObjectName ("CommonSpacer"); layout->addItem (stretcher); /* * The first row: a logo */ logoLayout = new QGraphicsLinearLayout (Qt::Horizontal); logo = new MImageWidget ("icon-l-about-nokia-logo"); logoLayout->addItem (logo); logoLayout->addStretch (); layout->addItem (logoLayout); /* * A stretcher. */ stretcher = new MStylableWidget; stretcher->setObjectName ("CommonSpacer"); layout->addItem (stretcher); /* * A label... FIXME: This might be wrong, the layout guide seems to define * a stretcher inside the text, so we might want to create two separate * labels... */ m_Label1 = new MLabel; m_Label1->setWordWrap (true); layout->addItem (m_Label1); layout->addStretch (); setLayout (layout); } QString AboutWidget::labelText() { QString retval; retval += "<h3>Name of the product</h3>"; retval += "<h3>" + m_AboutBusinessLogic->osName () + "</h3>"; //% "Version" retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_version")); retval += m_AboutBusinessLogic->osVersion(); //% "WLAN MAC address" retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_wlan_mac_address")); retval += m_AboutBusinessLogic->WiFiAddress (); //% "Bluetooth address" retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_bt_address")); retval += m_AboutBusinessLogic->BluetoothAddress (); //% "IMEI" retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_imei")); retval += m_AboutBusinessLogic->IMEI (); retval += "<hr />"; retval += "<p>This product includes certain free/open source software</p>"; retval += "<p>The exact terms of the licenses, disclaimers, " "aknowledgements and notices are provided in the " "following document/through the following links:" "<a href=\"http://somethink.here\">[insert document/link]</a>. " "You may obtain the source code of the relevant free and open " "source software at " "<a href=\"http://somethink.here\">[insert the URL]</a>. " "Alternatively, Nokia offers to provide such source code to you " "on a CD-ROM upon written request to Nokia at:</p>"; retval += "<p>Maemo Source Code Requests<br>"; retval += "Nokia Corporation<br>"; retval += "P.O.Box 407<br>"; retval += "FI-00045 Nokia Group<br>"; retval += "Finland<br>"; retval += "<p>This offer is valid for a period of three (3) years " "from the date of the distribution of t his product by " "Nokia.</p>"; retval += "<p>The Graphics Interchange Format (c) is the Copyright " "property of CompuServe Incorporated. GIF(sm) is a " "Service Mark property of Compuserve Incorporated.</p>"; retval += "<p>AdobeAE FlashAE Player. Copyright (c) 1996 - 2007 " "Adobe Systems Incorporated. All Rights Reserved. " "Protected by U.S. Patent 6,879,327; Patents Pending in the " "United States and other countries. Adobe and Flas are either " "trademarks or registered trademarks in the United States " "and/or other countries.</p>"; return retval; } void AboutWidget::retranslateUi () { m_Label1->setText (labelText ()); } void AboutWidget::dataReady () { m_Label1->setText (labelText ()); }
update the about-applet nokia-logo
Changes: update the about-applet nokia-logo
C++
lgpl-2.1
nemomobile-graveyard/meegotouch-controlpanelapplets,deztructor/meegotouch-controlpanelapplets,deztructor/meegotouch-controlpanelapplets,nemomobile-graveyard/meegotouch-controlpanelapplets,deztructor/meegotouch-controlpanelapplets,nemomobile-graveyard/meegotouch-controlpanelapplets
b4741001fb6604897dc694ee7e9919c67f66ee5b
src/ad/App/AsteroidDefender.cpp
src/ad/App/AsteroidDefender.cpp
#include "ad/Geometry/Converters.h" #include "ad/Geometry/Geometry.h" #include "ad/Geometry/ShaderSourceConverter.h" #include "ad/Sprites/SpriteRenderer.h" #include "ad/World/CameraController.h" #include "ad/World/TopDownCameraController.h" #include "ad/World/World.h" #include "canvas/App.h" #include "canvas/Math/Intersection.h" #include "canvas/Math/Transform.h" #include "canvas/OpenGL.h" #include "canvas/Renderer/LineRenderer.h" #include "elastic/Context.h" #include "elastic/Views/LabelView.h" #include "hive/PhysicalResourceLocator.h" #include "hive/ResourceManager.h" #include "nucleus/Streams/FileInputStream.h" #include "nucleus/Streams/WrappedMemoryInputStream.h" void drawCross(ca::LineRenderer* lineRenderer, const ca::Vec3& position, const ca::Color& color, F32 scale = 1.0f) { lineRenderer->renderLine(position - ca::Vec3{1.0f, 0.0f, 0.0f} * scale, position + ca::Vec3{1.0f, 0.0f, 0.0f} * scale, color); lineRenderer->renderLine(position - ca::Vec3{0.0f, 1.0f, 0.0f} * scale, position + ca::Vec3{0.0f, 1.0f, 0.0f} * scale, color); lineRenderer->renderLine(position - ca::Vec3{0.0f, 0.0f, 1.0f} * scale, position + ca::Vec3{0.0f, 0.0f, 1.0f} * scale, color); } const I8* kCubeVertexShaderSource = R"( #version 330 layout(location = 0) in vec3 inPosition; layout(location = 1) in vec4 inColor; uniform mat4 uTransform; out vec4 vColor; void main() { gl_Position = uTransform * vec4(inPosition, 1.0); vColor = inColor; } )"; const I8* kCubeFragmentShaderSource = R"( #version 330 in vec4 vColor; out vec4 final; void main() { final = vec4(vColor.xyz, 1.0); } )"; class AsteroidDefender : public ca::WindowDelegate { public: AsteroidDefender() : ca::WindowDelegate{"Asteroid Defender"}, m_ray{{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}} {} ~AsteroidDefender() override = default; bool onWindowCreated(ca::Window* window) override { if (!WindowDelegate::onWindowCreated(window)) { return false; } ca::Renderer* renderer = window->getRenderer(); m_lineRenderer.initialize(renderer); #if 0 if (!createCube(&m_cube.model, renderer)) { LOG(Error) << "Could not create cube."; return false; } #endif nu::WrappedMemoryInputStream vertexStream{kCubeVertexShaderSource, nu::StringView{kCubeVertexShaderSource}.getLength()}; auto vss = ca::ShaderSource::from(&vertexStream); nu::WrappedMemoryInputStream fragmentStream{ kCubeFragmentShaderSource, nu::StringView{kCubeFragmentShaderSource}.getLength()}; auto fss = ca::ShaderSource::from(&fragmentStream); // m_cube.programId = renderer->createProgram(vss, fss); // m_cube.transformUniformId = renderer->createUniform("uTransform"); auto assetsPath = nu::getCurrentWorkingDirectory() / "assets"; LOG(Info) << "Assets path: " << assetsPath.getPath(); m_physicalFileResourceLocator.setRootPath(assetsPath); m_resourceManager.addResourceLocatorBack(&m_physicalFileResourceLocator); m_converters.registerConverters(&m_resourceManager, renderer); m_model = m_resourceManager.get<Model>("cursor.dae"); if (!m_ui.initialize(renderer)) { return false; } #if OS(MACOSX) nu::FileInputStream fontStream{nu::FilePath { R"(/Library/Fonts/Arial.ttf)" }}; #else nu::FileInputStream fontStream{nu::FilePath{R"(C:\Windows\Fonts\Arial.ttf)"}}; #endif m_font.load(&fontStream, renderer, 20); if (!createUI(&m_ui, &m_font)) { return false; } if (!m_spriteRenderer.initialize(renderer)) { return false; } if (!m_world.initialize(&m_resourceManager)) { return false; } m_debugCamera.setFarPlane(5000.0f); m_worldCamera.moveTo({0.0f, 0.0f, 5.0f}); m_worldCamera.setNearPlane(0.1f); m_worldCamera.setFarPlane(200.0f); return true; } void onWindowResized(const ca::Size& size) override { WindowDelegate::onWindowResized(size); m_screenSize = size; m_debugCamera.setAspectRatio(Camera::aspectRatioFromScreenSize(m_screenSize)); m_worldCamera.setAspectRatio(Camera::aspectRatioFromScreenSize(m_screenSize)); m_ui.resize(size); } void onMouseMoved(const ca::MouseEvent& event) override { m_topDownCameraController.onMouseMoved( Camera::convertScreenPositionToClipSpace(event.pos, m_screenSize)); m_currentMousePosition = event.pos; } bool onMousePressed(const ca::MouseEvent& event) override { m_topDownCameraController.onMousePressed( event.button, Camera::convertScreenPositionToClipSpace(event.pos, m_screenSize)); return false; } void onMouseReleased(const ca::MouseEvent& event) override { m_topDownCameraController.onMouseReleased( event.button, Camera::convertScreenPositionToClipSpace(event.pos, m_screenSize)); } void onMouseWheel(const ca::MouseWheelEvent& event) override { m_topDownCameraController.onMouseWheel( {static_cast<F32>(event.wheelOffset.x), static_cast<F32>(event.wheelOffset.y)}); } void onKeyPressed(const ca::KeyEvent& event) override { m_topDownCameraController.onKeyPressed(event.key); switch (event.key) { case ca::Key::C: m_useDebugCamera = !m_useDebugCamera; m_cameraLabel->setLabel(m_useDebugCamera ? "debug" : "world"); break; case ca::Key::LBracket: m_fieldOfViewMovement -= 1.0f; break; case ca::Key::RBracket: m_fieldOfViewMovement += 1.0f; break; default: break; } } void onKeyReleased(const ca::KeyEvent& event) override { m_topDownCameraController.onKeyReleased(event.key); switch (event.key) { case ca::Key::LBracket: m_fieldOfViewMovement += 1.0f; break; case ca::Key::RBracket: m_fieldOfViewMovement -= 1.0f; break; default: break; } } void tick(F32 delta) override { m_topDownCameraController.tick(delta); { m_ray = m_worldCamera.createRayForMouse( Camera::convertScreenPositionToClipSpace(m_currentMousePosition, m_screenSize)); ca::Plane worldPlane{-ca::Vec3::forward, 0.0f}; auto result = ca::intersection(worldPlane, m_ray); m_world.setCursorPosition({result.position.x, result.position.y}); } m_world.tick(delta); } void onRender(ca::Renderer* renderer) override { m_lineRenderer.beginFrame(); #if 1 glEnable(GL_DEPTH_TEST); // View (world) ca::Mat4 viewWorld{ca::Mat4::identity}; m_worldCamera.updateViewMatrix(&viewWorld); // Projection ca::Mat4 projection = ca::Mat4::identity; m_debugCamera.updateProjectionMatrix(&projection); // View (debug) m_debugCamera.moveTo({-25.0f, 25.0f, 50.0f}); m_debugCamera.rotateTo( ca::Quaternion::fromEulerAngles(ca::degrees(-30.0f), ca::degrees(-30.0f), ca::Angle::zero)); ca::Mat4 viewDebug{ca::Mat4::identity}; m_debugCamera.updateViewMatrix(&viewDebug); // Final matrix ca::Mat4 finalMatrix = ca::Mat4::identity; if (m_useDebugCamera) { finalMatrix = projection * viewDebug; } else { ca::Mat4 camProjection = ca::Mat4::identity; ca::Mat4 camView = ca::Mat4::identity; m_worldCamera.updateProjectionMatrix(&camProjection); m_worldCamera.updateViewMatrix(&camView); finalMatrix = camProjection * camView; } // Render if (m_useDebugCamera) { drawCamera(&m_worldCamera); } ca::Plane worldPlane{-ca::Vec3::forward, 0.0f}; { ca::Ray mouseRay = m_worldCamera.createRayForMouse( Camera::convertScreenPositionToClipSpace(m_currentMousePosition, m_screenSize)); auto intersection = ca::intersection(worldPlane, mouseRay); drawModel(renderer, intersection.position, ca::Quaternion::fromEulerAngles(ca::degrees(45.0f), ca::degrees(45.0f), ca::degrees(45.0f)), finalMatrix); ca::Vec3 p1 = mouseRay.origin; ca::Vec3 p2 = mouseRay.origin + mouseRay.direction * (m_worldCamera.farPlane() + m_worldCamera.nearPlane()); m_lineRenderer.renderLine(p1, p2, ca::Color::red); m_lineRenderer.renderLine(ca::Vec3::zero, p1, ca::Color::green); m_lineRenderer.renderLine(ca::Vec3::zero, p2, ca::Color::blue); } m_lineRenderer.renderGrid(worldPlane, ca::Vec3::up, ca::Color{1.0f, 1.0f, 1.0f, 0.1f}, 20, 1.0f); m_lineRenderer.render(finalMatrix); glDisable(GL_DEPTH_TEST); #endif // 0 if (m_useDebugCamera) { m_spriteRenderer.beginFrame(&m_debugCamera); } else { m_spriteRenderer.beginFrame(&m_worldCamera); } // m_world.render(&m_spriteRenderer); m_ui.render(renderer); } void drawModel(ca::Renderer* renderer, const ca::Vec3& position, const ca::Quaternion& orientation, const ca::Mat4& finalMatrix) { ca::Mat4 modelTranslation = translationMatrix(position); ca::Mat4 modelRotation{orientation.toRotationMatrix()}; ca::Mat4 modelScale = ca::scaleMatrix(0.5f); ca::Mat4 model = ca::createModelMatrix(modelTranslation, modelRotation, modelScale); ca::Mat4 final = finalMatrix * model; // renderModel(renderer, m_cube.model, final, m_cube.programId, m_cube.transformUniformId); renderModel(renderer, *m_model, final); } void drawCamera(Camera* camera) { // drawModel(renderer, camera->position(), camera->orientation(), finalMatrix); m_lineRenderer.renderLine(camera->position(), camera->position() + camera->forward(), ca::Color::red); m_lineRenderer.renderLine(camera->position(), camera->position() + camera->right(), ca::Color::green); m_lineRenderer.renderLine(camera->position(), camera->position() + camera->up(), ca::Color::blue); // Draw the frustum. ca::Mat4 camProjection = ca::Mat4::identity; ca::Mat4 camView = ca::Mat4::identity; camera->updateProjectionMatrix(&camProjection); camera->updateViewMatrix(&camView); ca::Mat4 camInverse{ca::inverse(camProjection * camView)}; static ca::Vec4 vertices[] = { {-1.0f, -1.0f, -1.0f, 1.0f}, // {+1.0f, -1.0f, -1.0f, 1.0f}, // {+1.0f, +1.0f, -1.0f, 1.0f}, // {-1.0f, +1.0f, -1.0f, 1.0f}, // {-1.0f, -1.0f, +1.0f, 1.0f}, // {+1.0f, -1.0f, +1.0f, 1.0f}, // {+1.0f, +1.0f, +1.0f, 1.0f}, // {-1.0f, +1.0f, +1.0f, 1.0f}, // }; nu::DynamicArray<ca::Vec4> pos; for (ca::Vec4& v : vertices) { auto p = camInverse * v; p /= p.w; pos.emplaceBack(p); } for (MemSize i = 0; i < 4; ++i) { m_lineRenderer.renderLine(pos[0 + i].xyz(), pos[0 + ((i + 1) % 4)].xyz(), ca::Color::white); m_lineRenderer.renderLine(pos[4 + i].xyz(), pos[4 + ((i + 1) % 4)].xyz(), ca::Color::white); m_lineRenderer.renderLine(pos[i].xyz(), pos[4 + i].xyz(), ca::Color::white); } } private: DELETE_COPY_AND_MOVE(AsteroidDefender); bool createUI(el::Context* context, el::Font* font) { m_cameraLabel = new el::LabelView{context, "world camera", font}; context->getRootView()->addChild(m_cameraLabel); m_cameraLabel->setVerticalAlignment(el::Alignment::Top); m_cameraLabel->setHorizontalAlignment(el::Alignment::Left); return true; } hi::ResourceManager m_resourceManager; hi::PhysicalFileResourceLocator m_physicalFileResourceLocator; Model* m_model = nullptr; ca::LineRenderer m_lineRenderer; el::Font m_font; el::Context m_ui; el::LabelView* m_cameraLabel = nullptr; SpriteRenderer m_spriteRenderer; World m_world; F32 m_fieldOfViewMovement = 0.0f; Converters m_converters; Camera m_worldCamera{ca::degrees(60.0f)}; TopDownCameraController m_topDownCameraController{ &m_worldCamera, {ca::Vec3::forward, 0.0f}, 100.0f}; bool m_useDebugCamera = false; Camera m_debugCamera; ca::Ray m_ray; // Client size of the area we're rendering the world into: ca::Size m_screenSize; // Position of the cursor on the screen in range ([0..m_size.width], [0..m_size.height]}. ca::Pos m_currentMousePosition; }; CANVAS_APP(AsteroidDefender)
#include "ad/Geometry/Converters.h" #include "ad/Geometry/Geometry.h" #include "ad/Geometry/ShaderSourceConverter.h" #include "ad/Sprites/SpriteRenderer.h" #include "ad/World/CameraController.h" #include "ad/World/TopDownCameraController.h" #include "ad/World/World.h" #include "canvas/App.h" #include "canvas/Math/Intersection.h" #include "canvas/Math/Transform.h" #include "canvas/OpenGL.h" #include "canvas/Renderer/LineRenderer.h" #include "elastic/Context.h" #include "elastic/Views/LabelView.h" #include "hive/PhysicalResourceLocator.h" #include "hive/ResourceManager.h" #include "nucleus/Streams/FileInputStream.h" #include "nucleus/Streams/WrappedMemoryInputStream.h" void drawCross(ca::LineRenderer* lineRenderer, const ca::Vec3& position, const ca::Color& color, F32 scale = 1.0f) { lineRenderer->renderLine(position - ca::Vec3{1.0f, 0.0f, 0.0f} * scale, position + ca::Vec3{1.0f, 0.0f, 0.0f} * scale, color); lineRenderer->renderLine(position - ca::Vec3{0.0f, 1.0f, 0.0f} * scale, position + ca::Vec3{0.0f, 1.0f, 0.0f} * scale, color); lineRenderer->renderLine(position - ca::Vec3{0.0f, 0.0f, 1.0f} * scale, position + ca::Vec3{0.0f, 0.0f, 1.0f} * scale, color); } const I8* kCubeVertexShaderSource = R"( #version 330 layout(location = 0) in vec3 inPosition; layout(location = 1) in vec4 inColor; uniform mat4 uTransform; out vec4 vColor; void main() { gl_Position = uTransform * vec4(inPosition, 1.0); vColor = inColor; } )"; const I8* kCubeFragmentShaderSource = R"( #version 330 in vec4 vColor; out vec4 final; void main() { final = vec4(vColor.xyz, 1.0); } )"; class AsteroidDefender : public ca::WindowDelegate { public: AsteroidDefender() : ca::WindowDelegate{"Asteroid Defender"}, m_ray{{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}} {} ~AsteroidDefender() override = default; bool onWindowCreated(ca::Window* window) override { if (!WindowDelegate::onWindowCreated(window)) { return false; } ca::Renderer* renderer = window->getRenderer(); m_lineRenderer.initialize(renderer); #if 0 if (!createCube(&m_cube.model, renderer)) { LOG(Error) << "Could not create cube."; return false; } #endif nu::WrappedMemoryInputStream vertexStream{kCubeVertexShaderSource, nu::StringView{kCubeVertexShaderSource}.getLength()}; auto vss = ca::ShaderSource::from(&vertexStream); nu::WrappedMemoryInputStream fragmentStream{ kCubeFragmentShaderSource, nu::StringView{kCubeFragmentShaderSource}.getLength()}; auto fss = ca::ShaderSource::from(&fragmentStream); // m_cube.programId = renderer->createProgram(vss, fss); // m_cube.transformUniformId = renderer->createUniform("uTransform"); auto assetsPath = nu::getCurrentWorkingDirectory() / "assets"; LOG(Info) << "Assets path: " << assetsPath.getPath(); m_physicalFileResourceLocator.setRootPath(assetsPath); m_resourceManager.addResourceLocatorBack(&m_physicalFileResourceLocator); m_converters.registerConverters(&m_resourceManager, renderer); m_model = m_resourceManager.get<Model>("cursor.dae"); if (!m_ui.initialize(renderer)) { return false; } #if OS(POSIX) nu::FileInputStream fontStream{nu::FilePath { "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf" }}; #elif OS(MACOSX) nu::FileInputStream fontStream{nu::FilePath { R"(/Library/Fonts/Arial.ttf)" }}; #else nu::FileInputStream fontStream{nu::FilePath{R"(C:\Windows\Fonts\Arial.ttf)"}}; #endif m_font.load(&fontStream, renderer, 20); if (!createUI(&m_ui, &m_font)) { return false; } if (!m_spriteRenderer.initialize(renderer)) { return false; } if (!m_world.initialize(&m_resourceManager)) { return false; } m_debugCamera.setFarPlane(5000.0f); m_worldCamera.moveTo({0.0f, 0.0f, 5.0f}); m_worldCamera.setNearPlane(0.1f); m_worldCamera.setFarPlane(200.0f); return true; } void onWindowResized(const ca::Size& size) override { WindowDelegate::onWindowResized(size); m_screenSize = size; m_debugCamera.setAspectRatio(Camera::aspectRatioFromScreenSize(m_screenSize)); m_worldCamera.setAspectRatio(Camera::aspectRatioFromScreenSize(m_screenSize)); m_ui.resize(size); } void onMouseMoved(const ca::MouseEvent& event) override { m_topDownCameraController.onMouseMoved( Camera::convertScreenPositionToClipSpace(event.pos, m_screenSize)); m_currentMousePosition = event.pos; } bool onMousePressed(const ca::MouseEvent& event) override { m_topDownCameraController.onMousePressed( event.button, Camera::convertScreenPositionToClipSpace(event.pos, m_screenSize)); return false; } void onMouseReleased(const ca::MouseEvent& event) override { m_topDownCameraController.onMouseReleased( event.button, Camera::convertScreenPositionToClipSpace(event.pos, m_screenSize)); } void onMouseWheel(const ca::MouseWheelEvent& event) override { m_topDownCameraController.onMouseWheel( {static_cast<F32>(event.wheelOffset.x), static_cast<F32>(event.wheelOffset.y)}); } void onKeyPressed(const ca::KeyEvent& event) override { m_topDownCameraController.onKeyPressed(event.key); switch (event.key) { case ca::Key::C: m_useDebugCamera = !m_useDebugCamera; m_cameraLabel->setLabel(m_useDebugCamera ? "debug" : "world"); break; case ca::Key::LBracket: m_fieldOfViewMovement -= 1.0f; break; case ca::Key::RBracket: m_fieldOfViewMovement += 1.0f; break; default: break; } } void onKeyReleased(const ca::KeyEvent& event) override { m_topDownCameraController.onKeyReleased(event.key); switch (event.key) { case ca::Key::LBracket: m_fieldOfViewMovement += 1.0f; break; case ca::Key::RBracket: m_fieldOfViewMovement -= 1.0f; break; default: break; } } void tick(F32 delta) override { m_topDownCameraController.tick(delta); { m_ray = m_worldCamera.createRayForMouse( Camera::convertScreenPositionToClipSpace(m_currentMousePosition, m_screenSize)); ca::Plane worldPlane{-ca::Vec3::forward, 0.0f}; auto result = ca::intersection(worldPlane, m_ray); m_world.setCursorPosition({result.position.x, result.position.y}); } m_world.tick(delta); } void onRender(ca::Renderer* renderer) override { m_lineRenderer.beginFrame(); #if 1 glEnable(GL_DEPTH_TEST); // View (world) ca::Mat4 viewWorld{ca::Mat4::identity}; m_worldCamera.updateViewMatrix(&viewWorld); // Projection ca::Mat4 projection = ca::Mat4::identity; m_debugCamera.updateProjectionMatrix(&projection); // View (debug) m_debugCamera.moveTo({-25.0f, 25.0f, 50.0f}); m_debugCamera.rotateTo( ca::Quaternion::fromEulerAngles(ca::degrees(-30.0f), ca::degrees(-30.0f), ca::Angle::zero)); ca::Mat4 viewDebug{ca::Mat4::identity}; m_debugCamera.updateViewMatrix(&viewDebug); // Final matrix ca::Mat4 finalMatrix = ca::Mat4::identity; if (m_useDebugCamera) { finalMatrix = projection * viewDebug; } else { ca::Mat4 camProjection = ca::Mat4::identity; ca::Mat4 camView = ca::Mat4::identity; m_worldCamera.updateProjectionMatrix(&camProjection); m_worldCamera.updateViewMatrix(&camView); finalMatrix = camProjection * camView; } // Render if (m_useDebugCamera) { drawCamera(&m_worldCamera); } ca::Plane worldPlane{-ca::Vec3::forward, 0.0f}; { ca::Ray mouseRay = m_worldCamera.createRayForMouse( Camera::convertScreenPositionToClipSpace(m_currentMousePosition, m_screenSize)); auto intersection = ca::intersection(worldPlane, mouseRay); drawModel(renderer, intersection.position, ca::Quaternion::fromEulerAngles(ca::degrees(45.0f), ca::degrees(45.0f), ca::degrees(45.0f)), finalMatrix); ca::Vec3 p1 = mouseRay.origin; ca::Vec3 p2 = mouseRay.origin + mouseRay.direction * (m_worldCamera.farPlane() + m_worldCamera.nearPlane()); m_lineRenderer.renderLine(p1, p2, ca::Color::red); m_lineRenderer.renderLine(ca::Vec3::zero, p1, ca::Color::green); m_lineRenderer.renderLine(ca::Vec3::zero, p2, ca::Color::blue); } m_lineRenderer.renderGrid(worldPlane, ca::Vec3::up, ca::Color{1.0f, 1.0f, 1.0f, 0.1f}, 20, 1.0f); m_lineRenderer.render(finalMatrix); glDisable(GL_DEPTH_TEST); #endif // 0 if (m_useDebugCamera) { m_spriteRenderer.beginFrame(&m_debugCamera); } else { m_spriteRenderer.beginFrame(&m_worldCamera); } // m_world.render(&m_spriteRenderer); m_ui.render(renderer); } void drawModel(ca::Renderer* renderer, const ca::Vec3& position, const ca::Quaternion& orientation, const ca::Mat4& finalMatrix) { ca::Mat4 modelTranslation = translationMatrix(position); ca::Mat4 modelRotation{orientation.toRotationMatrix()}; ca::Mat4 modelScale = ca::scaleMatrix(0.5f); ca::Mat4 model = ca::createModelMatrix(modelTranslation, modelRotation, modelScale); ca::Mat4 final = finalMatrix * model; // renderModel(renderer, m_cube.model, final, m_cube.programId, m_cube.transformUniformId); renderModel(renderer, *m_model, final); } void drawCamera(Camera* camera) { // drawModel(renderer, camera->position(), camera->orientation(), finalMatrix); m_lineRenderer.renderLine(camera->position(), camera->position() + camera->forward(), ca::Color::red); m_lineRenderer.renderLine(camera->position(), camera->position() + camera->right(), ca::Color::green); m_lineRenderer.renderLine(camera->position(), camera->position() + camera->up(), ca::Color::blue); // Draw the frustum. ca::Mat4 camProjection = ca::Mat4::identity; ca::Mat4 camView = ca::Mat4::identity; camera->updateProjectionMatrix(&camProjection); camera->updateViewMatrix(&camView); ca::Mat4 camInverse{ca::inverse(camProjection * camView)}; static ca::Vec4 vertices[] = { {-1.0f, -1.0f, -1.0f, 1.0f}, // {+1.0f, -1.0f, -1.0f, 1.0f}, // {+1.0f, +1.0f, -1.0f, 1.0f}, // {-1.0f, +1.0f, -1.0f, 1.0f}, // {-1.0f, -1.0f, +1.0f, 1.0f}, // {+1.0f, -1.0f, +1.0f, 1.0f}, // {+1.0f, +1.0f, +1.0f, 1.0f}, // {-1.0f, +1.0f, +1.0f, 1.0f}, // }; nu::DynamicArray<ca::Vec4> pos; for (ca::Vec4& v : vertices) { auto p = camInverse * v; p /= p.w; pos.emplaceBack(p); } for (MemSize i = 0; i < 4; ++i) { m_lineRenderer.renderLine(pos[0 + i].xyz(), pos[0 + ((i + 1) % 4)].xyz(), ca::Color::white); m_lineRenderer.renderLine(pos[4 + i].xyz(), pos[4 + ((i + 1) % 4)].xyz(), ca::Color::white); m_lineRenderer.renderLine(pos[i].xyz(), pos[4 + i].xyz(), ca::Color::white); } } private: DELETE_COPY_AND_MOVE(AsteroidDefender); bool createUI(el::Context* context, el::Font* font) { m_cameraLabel = new el::LabelView{context, "world camera", font}; context->getRootView()->addChild(m_cameraLabel); m_cameraLabel->setVerticalAlignment(el::Alignment::Top); m_cameraLabel->setHorizontalAlignment(el::Alignment::Left); return true; } hi::ResourceManager m_resourceManager; hi::PhysicalFileResourceLocator m_physicalFileResourceLocator; Model* m_model = nullptr; ca::LineRenderer m_lineRenderer; el::Font m_font; el::Context m_ui; el::LabelView* m_cameraLabel = nullptr; SpriteRenderer m_spriteRenderer; World m_world; F32 m_fieldOfViewMovement = 0.0f; Converters m_converters; Camera m_worldCamera{ca::degrees(60.0f)}; TopDownCameraController m_topDownCameraController{ &m_worldCamera, {ca::Vec3::forward, 0.0f}, 100.0f}; bool m_useDebugCamera = false; Camera m_debugCamera; ca::Ray m_ray; // Client size of the area we're rendering the world into: ca::Size m_screenSize; // Position of the cursor on the screen in range ([0..m_size.width], [0..m_size.height]}. ca::Pos m_currentMousePosition; }; CANVAS_APP(AsteroidDefender)
Set font on linux
Set font on linux
C++
mit
fizixx/AsteroidDefender,tiaanl/AsteroidDefender,tiaanl/AsteroidDefender
571c9c27fcb542e696c81747c979f457a52545c0
lm/game03/main.cpp
lm/game03/main.cpp
#include "StreamLog.hpp" #include "World.hpp" #include <SFML/Graphics.hpp> #include <iostream> #include <sstream> sf::Vector2f processUserInput(float baseSpeed, sf::RenderWindow& window); int main(int /*argc*/, char** /*argv*/) { sf::Vector2i screenSize{800, 600}; sf::RenderWindow mainWindow(sf::VideoMode(screenSize.x, screenSize.y), "myproject"); mainWindow.setVerticalSyncEnabled(true); // std::stringstream s; common::StreamLog slog{std::cout}; lmg03::World w{slog}; sf::Clock frameClock; constexpr float baseSpeed = 50.f; constexpr float frameDuration = 1.f / 60.f; while (mainWindow.isOpen()) { sf::Event event; while (mainWindow.pollEvent(event)) { if (event.type == sf::Event::Closed) { mainWindow.close(); } } const auto duration = frameClock.getElapsedTime(); if (duration.asSeconds() < frameDuration) continue; frameClock.restart(); sf::Vector2f movement{processUserInput(baseSpeed, mainWindow)}; w.advance(duration, movement); w.display_on(mainWindow); mainWindow.display(); } } sf::Vector2f processUserInput(float speed, sf::RenderWindow& window) { auto view = window.getView(); sf::Vector2f movement{0.f, 0.f}; if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift)) { speed *= 2.f; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { view.move(0.f, -5.f); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { view.move(0.f, 5.f); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { view.move(-5.f, 0.f); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { view.move(5.f, 0.f); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { movement.y -= speed; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { movement.y += speed; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { movement.x -= speed; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { movement.x += speed; } window.setView(view); return movement; }
#include "StreamLog.hpp" #include "World.hpp" #include <SFML/Graphics.hpp> #include <chrono> #include <iostream> #include <sstream> #include <thread> sf::Vector2f processUserInput(float baseSpeed, sf::RenderWindow& window); int main(int /*argc*/, char** /*argv*/) { sf::Vector2i screenSize{800, 600}; sf::RenderWindow mainWindow(sf::VideoMode(screenSize.x, screenSize.y), "myproject"); mainWindow.setVerticalSyncEnabled(true); // std::stringstream s; common::StreamLog slog{std::cout}; lmg03::World w{slog}; sf::Clock frameClock; constexpr float baseSpeed = 50.f; constexpr float frameDuration = 1.f / 60.f; while (mainWindow.isOpen()) { sf::Event event; while (mainWindow.pollEvent(event)) { if (event.type == sf::Event::Closed) { mainWindow.close(); } } const auto duration = frameClock.getElapsedTime(); if (duration.asSeconds() < frameDuration) { using namespace std::literals::chrono_literals; std::this_thread::sleep_for(10ms); continue; } frameClock.restart(); sf::Vector2f movement{processUserInput(baseSpeed, mainWindow)}; w.advance(duration, movement); w.display_on(mainWindow); mainWindow.display(); } } sf::Vector2f processUserInput(float speed, sf::RenderWindow& window) { auto view = window.getView(); sf::Vector2f movement{0.f, 0.f}; if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift)) { speed *= 2.f; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { view.move(0.f, -5.f); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { view.move(0.f, 5.f); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { view.move(-5.f, 0.f); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { view.move(5.f, 0.f); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { movement.y -= speed; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { movement.y += speed; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { movement.x -= speed; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { movement.x += speed; } window.setView(view); return movement; }
Use less CPU
Use less CPU
C++
mit
NadzwyczajnaGrupaRobocza/papuc_exercises,NadzwyczajnaGrupaRobocza/papuc_exercises
dc7c8d84acec9cc1eed3e6bb497fd4d3896c59e6
src/appleseed-max-impl/version.cpp
src/appleseed-max-impl/version.cpp
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015-2018 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "version.h" const wchar_t* PluginVersionString = L"0.5.0-beta";
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015-2018 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "version.h" const wchar_t* PluginVersionString = L"1.0.0-beta";
Bump plugin version number to 1.0.0-beta
Bump plugin version number to 1.0.0-beta
C++
mit
dictoon/appleseed-max,usakhelo/appleseed-max,appleseedhq/appleseed-max,dictoon/appleseed-max,appleseedhq/appleseed-max,usakhelo/appleseed-max
f41f951b8e44c0640001d2960c52699358141d57
tests/fe/mapping_q1_eulerian.cc
tests/fe/mapping_q1_eulerian.cc
// mapping_q1_eulerian.cc,v 1.3 2002/06/26 12:28:54 guido Exp // Copyright (C) 2001, 2002, 2005 Michael Stadler, Wolfgang Bangerth // #include "../tests.h" #include <base/quadrature_lib.h> #include <base/logstream.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/grid_generator.h> #include <dofs/dof_handler.h> #include <fe/fe_q.h> #include <fe/fe_system.h> #include <fe/mapping_q1_eulerian.h> #include <fe/fe_values.h> #include <vector> #include <fstream> #include <string> template<int dim> inline void show_values(FiniteElement<dim>& fe, const char* name) { deallog.push (name); Triangulation<dim> tr; GridGenerator::hyper_cube(tr, 2., 5.); // shift one point of the cell // somehow if (dim > 1) tr.begin_active()->vertex(2)(dim-1) += 1./std::sqrt(2.); DoFHandler<dim> dof(tr); dof.distribute_dofs(fe); // construct the MappingQ1Eulerian // object FESystem<dim> mapping_fe(FE_Q<dim>(1), dim); DoFHandler<dim> flowfield_dof_handler(tr); flowfield_dof_handler.distribute_dofs(mapping_fe); Vector<double> map_points(flowfield_dof_handler.n_dofs()); MappingQ1Eulerian<dim> mapping(map_points, flowfield_dof_handler); QGauss2<dim> quadrature_formula; FEValues<dim> fe_values(mapping, fe, quadrature_formula, UpdateFlags(update_values | update_JxW_values | update_gradients | update_second_derivatives)); typename DoFHandler<dim>::cell_iterator c = dof.begin(); fe_values.reinit(c); for (unsigned int k=0; k<quadrature_formula.n_quadrature_points; ++k) { deallog << quadrature_formula.point(k) << std::endl; deallog << "\tJxW " << fe_values.JxW(k); for (unsigned int i=0;i<fe.dofs_per_cell;++i) { deallog << "\tValues " << fe_values.shape_value(i,k); deallog << "\tGrad " << fe_values.shape_grad(i,k); deallog << "\t2nd " << fe_values.shape_2nd_derivative(i,k); deallog << std::endl; } } deallog.pop (); } template<int dim> void show_values() { FE_Q<dim> q1(1); show_values(q1, "DGQ1"); FE_Q<dim> q2(2); show_values(q2, "DGQ2"); } int main() { std::ofstream logfile ("mapping_q1_eulerian.output"); logfile.precision (2); logfile.setf(std::ios::fixed); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); deallog.push ("1d"); show_values<1>(); deallog.pop (); deallog.push ("2d"); show_values<2>(); deallog.pop (); deallog.push ("3d"); show_values<3>(); deallog.pop (); return 0; }
// mapping_q1_eulerian.cc,v 1.3 2002/06/26 12:28:54 guido Exp // Copyright (C) 2001, 2002, 2005 Michael Stadler, Wolfgang Bangerth // #include "../tests.h" #include <base/quadrature_lib.h> #include <base/logstream.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/grid_generator.h> #include <dofs/dof_handler.h> #include <fe/fe_q.h> #include <fe/fe_system.h> #include <fe/mapping_q1_eulerian.h> #include <fe/fe_values.h> #include <vector> #include <fstream> #include <string> template<int dim> inline void show_values(FiniteElement<dim>& fe, const char* name) { deallog.push (name); Triangulation<dim> tr; GridGenerator::hyper_cube(tr, 2., 5.); // shift one point of the cell // somehow if (dim > 1) tr.begin_active()->vertex(2)(dim-1) += 1./std::sqrt(2.); DoFHandler<dim> dof(tr); dof.distribute_dofs(fe); // construct the MappingQ1Eulerian // object FESystem<dim> mapping_fe(FE_Q<dim>(1), dim); DoFHandler<dim> flowfield_dof_handler(tr); flowfield_dof_handler.distribute_dofs(mapping_fe); Vector<double> map_points(flowfield_dof_handler.n_dofs()); MappingQ1Eulerian<dim> mapping(map_points, flowfield_dof_handler); QGauss2<dim> quadrature_formula; FEValues<dim> fe_values(mapping, fe, quadrature_formula, UpdateFlags(update_values | update_JxW_values | update_gradients | update_second_derivatives)); typename DoFHandler<dim>::cell_iterator c = dof.begin(); fe_values.reinit(c); for (unsigned int k=0; k<quadrature_formula.n_quadrature_points; ++k) { deallog << quadrature_formula.point(k) << std::endl; deallog << "JxW: " << fe_values.JxW(k) << std::endl; for (unsigned int i=0;i<fe.dofs_per_cell;++i) { deallog << "Values: " << fe_values.shape_value(i,k); deallog << ", Grad: " << fe_values.shape_grad(i,k); deallog << ", 2nd: " << fe_values.shape_2nd_derivative(i,k); deallog << std::endl; } } deallog.pop (); } template<int dim> void show_values() { FE_Q<dim> q1(1); show_values(q1, "Q1"); FE_Q<dim> q2(2); show_values(q2, "Q2"); } int main() { std::ofstream logfile ("mapping_q1_eulerian.output"); logfile.precision (2); logfile.setf(std::ios::fixed); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); deallog.push ("1d"); show_values<1>(); deallog.pop (); deallog.push ("2d"); show_values<2>(); deallog.pop (); deallog.push ("3d"); show_values<3>(); deallog.pop (); return 0; }
Correct and modify output.
Correct and modify output. git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@10919 0785d39b-7218-0410-832d-ea1e28bc413d
C++
lgpl-2.1
kalj/dealii,nicolacavallini/dealii,danshapero/dealii,natashasharma/dealii,flow123d/dealii,rrgrove6/dealii,mtezzele/dealii,rrgrove6/dealii,adamkosik/dealii,gpitton/dealii,shakirbsm/dealii,lpolster/dealii,pesser/dealii,natashasharma/dealii,natashasharma/dealii,sairajat/dealii,ibkim11/dealii,johntfoster/dealii,msteigemann/dealii,flow123d/dealii,mtezzele/dealii,johntfoster/dealii,andreamola/dealii,mtezzele/dealii,adamkosik/dealii,lue/dealii,msteigemann/dealii,maieneuro/dealii,shakirbsm/dealii,ibkim11/dealii,andreamola/dealii,pesser/dealii,andreamola/dealii,mtezzele/dealii,msteigemann/dealii,lue/dealii,lpolster/dealii,jperryhouts/dealii,maieneuro/dealii,Arezou-gh/dealii,naliboff/dealii,Arezou-gh/dealii,ESeNonFossiIo/dealii,angelrca/dealii,ibkim11/dealii,jperryhouts/dealii,naliboff/dealii,lue/dealii,nicolacavallini/dealii,ESeNonFossiIo/dealii,angelrca/dealii,kalj/dealii,gpitton/dealii,EGP-CIG-REU/dealii,adamkosik/dealii,gpitton/dealii,rrgrove6/dealii,ESeNonFossiIo/dealii,EGP-CIG-REU/dealii,msteigemann/dealii,maieneuro/dealii,naliboff/dealii,andreamola/dealii,JaeryunYim/dealii,spco/dealii,johntfoster/dealii,nicolacavallini/dealii,mtezzele/dealii,johntfoster/dealii,danshapero/dealii,pesser/dealii,jperryhouts/dealii,Arezou-gh/dealii,YongYang86/dealii,ibkim11/dealii,pesser/dealii,kalj/dealii,ESeNonFossiIo/dealii,naliboff/dealii,sriharisundar/dealii,jperryhouts/dealii,gpitton/dealii,natashasharma/dealii,lue/dealii,sairajat/dealii,jperryhouts/dealii,mac-a/dealii,sairajat/dealii,flow123d/dealii,Arezou-gh/dealii,lue/dealii,danshapero/dealii,EGP-CIG-REU/dealii,nicolacavallini/dealii,danshapero/dealii,spco/dealii,maieneuro/dealii,kalj/dealii,angelrca/dealii,ESeNonFossiIo/dealii,angelrca/dealii,flow123d/dealii,lpolster/dealii,naliboff/dealii,shakirbsm/dealii,sairajat/dealii,natashasharma/dealii,Arezou-gh/dealii,angelrca/dealii,pesser/dealii,lpolster/dealii,Arezou-gh/dealii,johntfoster/dealii,Arezou-gh/dealii,gpitton/dealii,mtezzele/dealii,msteigemann/dealii,angelrca/dealii,mac-a/dealii,andreamola/dealii,EGP-CIG-REU/dealii,YongYang86/dealii,lpolster/dealii,shakirbsm/dealii,naliboff/dealii,adamkosik/dealii,pesser/dealii,johntfoster/dealii,nicolacavallini/dealii,ibkim11/dealii,mac-a/dealii,danshapero/dealii,lue/dealii,shakirbsm/dealii,YongYang86/dealii,EGP-CIG-REU/dealii,sriharisundar/dealii,johntfoster/dealii,mac-a/dealii,mac-a/dealii,danshapero/dealii,EGP-CIG-REU/dealii,sairajat/dealii,danshapero/dealii,adamkosik/dealii,andreamola/dealii,ESeNonFossiIo/dealii,msteigemann/dealii,angelrca/dealii,sriharisundar/dealii,natashasharma/dealii,lue/dealii,spco/dealii,gpitton/dealii,adamkosik/dealii,andreamola/dealii,sriharisundar/dealii,rrgrove6/dealii,nicolacavallini/dealii,kalj/dealii,JaeryunYim/dealii,nicolacavallini/dealii,shakirbsm/dealii,flow123d/dealii,maieneuro/dealii,EGP-CIG-REU/dealii,sriharisundar/dealii,shakirbsm/dealii,naliboff/dealii,YongYang86/dealii,maieneuro/dealii,JaeryunYim/dealii,kalj/dealii,rrgrove6/dealii,YongYang86/dealii,ibkim11/dealii,sairajat/dealii,YongYang86/dealii,YongYang86/dealii,sriharisundar/dealii,ESeNonFossiIo/dealii,JaeryunYim/dealii,natashasharma/dealii,jperryhouts/dealii,mac-a/dealii,maieneuro/dealii,lpolster/dealii,spco/dealii,ibkim11/dealii,kalj/dealii,adamkosik/dealii,flow123d/dealii,rrgrove6/dealii,spco/dealii,gpitton/dealii,lpolster/dealii,sairajat/dealii,mac-a/dealii,mtezzele/dealii,spco/dealii,JaeryunYim/dealii,JaeryunYim/dealii,flow123d/dealii,jperryhouts/dealii,pesser/dealii,sriharisundar/dealii,msteigemann/dealii,JaeryunYim/dealii,spco/dealii,rrgrove6/dealii
e76c8a18f3046227c309a1d7f878e98899c9842d
src/autowiring/test/PostConstructTest.cpp
src/autowiring/test/PostConstructTest.cpp
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "TestFixtures/SimpleObject.hpp" #include <autowiring/Autowired.h> #include <autowiring/ContextMember.h> #include THREAD_HEADER class PostConstructTest: public testing::Test {}; using namespace std; class ContextExposer: public CoreContext { public: size_t DeferredCount(void) const { size_t ct = 0; for(const auto& entry : CoreContext::m_typeMemos) for(auto cur = entry.second.pFirst; cur; cur = cur->GetFlink()) ct++; return ct; } }; // Two classes to make up the cyclic dependency: class A: public ContextMember { public: int m_value = 2; int GetValue(void) const {return m_value;} }; // For testing NotifyWhenAutowired with heirarchies class Interface { public: virtual int GetValue() = 0; }; class Implementation : public ContextMember, public Interface { public: virtual int GetValue() override { return 2; } }; class Naive: public ContextMember { public: Naive(void) { if(!m_a) throw exception(); } Autowired<A> m_a; }; class Smarter: public ContextMember { public: Smarter(void) { m_a.NotifyWhenAutowired([this] () { this->value = m_a->GetValue(); }); } int value = 1; Autowired<A> m_a; }; class SmarterInterface { public: SmarterInterface(void) { m_interface.NotifyWhenAutowired([this] () { this->value = m_interface->GetValue(); }); } int value = 1; Autowired<Interface> m_interface; }; class FailedAutowiringInstance { }; TEST_F(PostConstructTest, VerifyNaiveBehavior) { // Create a context and add just the naive class, to verify the problematic behavior: AutoCurrentContext ctxt; ASSERT_THROW(ctxt->Inject<Naive>(), std::exception) << "Naive class didn't throw an exception as expected"; } TEST_F(PostConstructTest, VerifyExpectedDeferrmentCount) { AutoCurrentContext ctxt; // Add the smart class, which should introduce a single deferred count: ctxt->Inject<Smarter>(); // Now test the count: ASSERT_EQ( 1UL, ((ContextExposer&)*ctxt).DeferredCount() ) << "Unexpected number of deferred initializers"; } TEST_F(PostConstructTest, VerifySmartBehavior) { AutoCurrentContext ctxt; // Add the smart class, which has a member that autowired type A ctxt->Inject<Smarter>(); // Check that we can get the item we just injected Autowired<Smarter> smarter; ASSERT_TRUE(smarter.IsAutowired()) << "Slot was not satisfied as expected"; ASSERT_EQ(1, smarter->value) << "Unexpected initial value of SmarterA instance"; // Now inject A, and see if delayed autowiring has taken place: ctxt->Inject<A>(); ASSERT_FALSE(!smarter->m_a.get()) << "Autowired member was not wired as expected"; // Verify the value was updated by the notification routine ASSERT_EQ(2, smarter->value) << "Post-construction notification routine wasn't invoked as expected"; } TEST_F(PostConstructTest, VerifySmartBehaviorWithInheritance) { AutoCurrentContext ctxt; // Add the smart classes, which should succeed ctxt->Inject<SmarterInterface>(); //Initially value should be one, which is the default Autowired<SmarterInterface> smarterI; ASSERT_EQ(1, smarterI->value) << "Unexpected initial value of SmarterA instance"; //Now add Implementation and check the wiring ctxt->Inject<Implementation>(); ASSERT_FALSE(!smarterI->m_interface.get()) << "Autowired subclass was not wired as expected"; ASSERT_EQ(2, smarterI->value) << "Post-construction notification routine wasn't invoked on subclass"; } TEST_F(PostConstructTest, VerifyLoopingFailedAutowiring) { for(size_t i = 10; i--;) { Autowired<FailedAutowiringInstance> ignored; ASSERT_FALSE(ignored.IsAutowired()) << "Successfully autowired an instance that should not have been autowirable"; } } TEST_F(PostConstructTest, VerifyTrivialNotifyWhenAutowired) { // Inject a type first: AutoRequired<SimpleObject>(); // Now autowire, and add a registration: bool called = false; Autowired<SimpleObject> so; so.NotifyWhenAutowired([&called] { called = true; }); ASSERT_TRUE(called) << "An autowiring notification was not invoked on an already-satisfied field as expected"; } TEST_F(PostConstructTest, MultiNotifyWhenAutowired) { // Add multiple notifications on the same space: int field = 0; Autowired<SimpleObject> so; for(size_t i = 10; i--;) so.NotifyWhenAutowired([&field] { field++; }); // Inject the type to trigger the autowiring AutoRequired<SimpleObject>(); // Verify that the notification got hit ten times: ASSERT_EQ(10, field) << "Autowiring lambdas did not run the expected number of times"; } TEST_F(PostConstructTest, NotificationTeardownRace) { std::shared_ptr<CoreContext> pContext; auto quit = false; auto shouldQuit = MakeAtExit([&quit] { quit = true; }); std::atomic<size_t> counter{0}; // This thread sets up the race pathology: std::thread t([&] { while(!quit) { // Barrier until setup time: while(counter != 1) std::this_thread::yield(); if(!pContext) break; // Set the context current, then try to autowire: CurrentContextPusher pshr(pContext); Autowired<SimpleObject> sobj; sobj.NotifyWhenAutowired([] {}); // Now barrier, and then we will try to race against the context // for teardown. counter++; } }); for(size_t i = 0; i < 200; i++) { // Make a new context: AutoCreateContext ctxt; pContext = ctxt; // Wake up the other thread, let it set a notify-when-autowired: counter++; while(counter != 2) std::this_thread::yield(); // Counter goes back to zero before we make the next loop iteration: counter = 0; // Now we reset our pContext pointer, and then tell the thread // to race with us against context teardown: pContext.reset(); } // All done, wait for the thread to back out: quit = true; counter = 1; t.join(); } TEST_F(PostConstructTest, VerifyAllInstancesSatisfied) { // Create all of our slots and bind to them: const size_t ct = 3; Autowired<SimpleObject> aw[ct]; bool hit[ct] = {}; for(size_t i = ct; i--;) aw[i].NotifyWhenAutowired([&hit, i] { hit[i] = true; }); // Now we inject our simple object: AutoRequired<SimpleObject>(); // Verify that everything got hit: for(size_t i = 0; i < ct; i++) { ASSERT_TRUE(aw[i]) << "Autowired slot " << i << " was not post-bound correctly"; ASSERT_TRUE(hit[i]) << "Autowired slot " << i << " did not fire all of its post-construct notifiers as expected"; } } TEST_F(PostConstructTest, ContextNotifyWhenAutowired) { auto called = std::make_shared<bool>(false); AutoCurrentContext ctxt; // Now we'd like to be notified when SimpleObject gets added: ctxt->NotifyWhenAutowired<SimpleObject>( [called] { *called = true; } ); // Should only be two uses, at this point, of the capture of the above lambda: ASSERT_EQ(2L, called.use_count()) << "Unexpected number of references held in a capture lambda"; // Create another entry that will add another slot to the deferred list: Autowired<SimpleObject> sobj; // Insert the SimpleObject, see if the lambda got hit: AutoRequired<SimpleObject>(); ASSERT_TRUE(*called) << "Context-wide autowiring notification was not hit as expected when a matching type was injected into a context"; // Our shared pointer should be unique by this point, because the lambda should have been destroyed ASSERT_TRUE(called.unique()) << "Autowiring notification lambda was not properly cleaned up"; } TEST_F(PostConstructTest, ContextNotifyWhenAutowiredPostConstruct) { auto called = std::make_shared<bool>(false); AutoCurrentContext ctxt; // Create an object that will satisfy subsequent notification call: AutoRequired<SimpleObject> sobj; // Notification should be immediate: ctxt->NotifyWhenAutowired<SimpleObject>( [called] { *called = true; } ); // Insert the SimpleObject, see if the lambda got hit: ASSERT_TRUE(*called) << "Context-wide autowiring notification was not hit as expected when a matching type was injected into a context"; // Our shared pointer should be unique by this point, because the lambda should have been destroyed ASSERT_TRUE(called.unique()) << "Autowiring notification lambda was not properly cleaned up"; } class OtherObject : public SimpleObject {}; TEST_F(PostConstructTest, RecursiveNotificationPreConstruction) { auto called = std::make_shared<bool>(false); AutoCurrentContext ctxt; // Ensure that nested calls do not created deadlock // Notification should be deferred: ctxt->NotifyWhenAutowired<SimpleObject>( [called] { AutoCurrentContext()->NotifyWhenAutowired<OtherObject>( [called] { *called = true; }); }); // Create an object that will satisfy subsequent notification call: AutoRequired<SimpleObject> sobj; AutoRequired<OtherObject> oobj; // Insert the SimpleObject, see if the lambda got hit: ASSERT_TRUE(*called) << "Context-wide autowiring notification was not hit as expected when a matching type was injected into a context"; // Our shared pointer should be unique by this point, because the lambda should have been destroyed ASSERT_TRUE(called.unique()) << "Autowiring notification lambda was not properly cleaned up"; } TEST_F(PostConstructTest, RecursiveNotificationPostConstruction) { auto called = std::make_shared<bool>(false); AutoCurrentContext ctxt; // Create an object that will satisfy subsequent notification call: AutoRequired<SimpleObject> sobj; AutoRequired<OtherObject> oobj; // Ensure that nested calls do not created deadlock // Notification should be immediate: ctxt->NotifyWhenAutowired<SimpleObject>( [called] { AutoCurrentContext()->NotifyWhenAutowired<OtherObject>( [called] { *called = true; }); }); // Insert the SimpleObject, see if the lambda got hit: ASSERT_TRUE(*called) << "Context-wide autowiring notification was not hit as expected when a matching type was injected into a context"; // Our shared pointer should be unique by this point, because the lambda should have been destroyed ASSERT_TRUE(called.unique()) << "Autowiring notification lambda was not properly cleaned up"; } struct ClassWithAutoInit: std::enable_shared_from_this<ClassWithAutoInit> { void AutoInit(void) { ASSERT_TRUE(m_constructed) << "A postconstruct routine was called BEFORE the corresponding constructor"; m_postConstructed = true; auto myself = shared_from_this(); ASSERT_EQ(this, myself.get()) << "Reflexive shared_from_this did not return a shared pointer to this as expected"; } bool m_constructed = true; bool m_postConstructed = false; }; static_assert(has_autoinit<ClassWithAutoInit>::value, "AutoInit-bearing class did not pass a static type check"); TEST_F(PostConstructTest, PostConstructGetsCalled) { AutoRequired<ClassWithAutoInit> cwai; ASSERT_TRUE(cwai->m_constructed) << "Trivial constructor call was not made as expected"; ASSERT_TRUE(cwai->m_postConstructed) << "Auto-initialization routine was not called on an initializable type"; } struct PostConstructThrowsException { void AutoInit(void) const { throw std::runtime_error("Autoinit crashing for no reason"); } }; TEST_F(PostConstructTest, PostConstructCanSafelyThrow) { ASSERT_ANY_THROW(AutoRequired<PostConstructThrowsException>()) << "AutoInit call threw an exception, but it was incorrectly eaten by Autowiring"; Autowired<PostConstructThrowsException> pcte; ASSERT_FALSE(pcte.IsAutowired()) << "A context member which threw an exception post-construction was incorrectly introduced into a context"; } namespace { class EmptyType : public CoreObject {}; } TEST_F(PostConstructTest, StrictNotificationArrangement) { size_t call[3] = {-1, -1, -1}; size_t callIdx = 1; AutoCurrentContext ctxt; Autowired<EmptyType> obj; obj.NotifyWhenAutowired([&] { call[0] = callIdx++; }); ctxt->NotifyWhenAutowired<EmptyType>([&] { call[1] = callIdx++; }); obj.NotifyWhenAutowired([&] { call[2] = callIdx++; }); ctxt->Inject<EmptyType>(); for (size_t i = 0; i < 3; i++) ASSERT_EQ(i + 1, call[i]) << "Registered autowired handler was not called in the correct order"; }
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "TestFixtures/SimpleObject.hpp" #include <autowiring/Autowired.h> #include <autowiring/ContextMember.h> #include THREAD_HEADER class PostConstructTest: public testing::Test {}; using namespace std; class ContextExposer: public CoreContext { public: size_t DeferredCount(void) const { size_t ct = 0; for(const auto& entry : CoreContext::m_typeMemos) for(auto cur = entry.second.pFirst; cur; cur = cur->GetFlink()) ct++; return ct; } }; // Two classes to make up the cyclic dependency: class A: public ContextMember { public: int m_value = 2; int GetValue(void) const {return m_value;} }; // For testing NotifyWhenAutowired with heirarchies class Interface { public: virtual int GetValue() = 0; }; class Implementation : public ContextMember, public Interface { public: virtual int GetValue() override { return 2; } }; class Naive: public ContextMember { public: Naive(void) { if(!m_a) throw exception(); } Autowired<A> m_a; }; class Smarter: public ContextMember { public: Smarter(void) { m_a.NotifyWhenAutowired([this] () { this->value = m_a->GetValue(); }); } int value = 1; Autowired<A> m_a; }; class SmarterInterface { public: SmarterInterface(void) { m_interface.NotifyWhenAutowired([this] () { this->value = m_interface->GetValue(); }); } int value = 1; Autowired<Interface> m_interface; }; class FailedAutowiringInstance { }; TEST_F(PostConstructTest, VerifyNaiveBehavior) { // Create a context and add just the naive class, to verify the problematic behavior: AutoCurrentContext ctxt; ASSERT_THROW(ctxt->Inject<Naive>(), std::exception) << "Naive class didn't throw an exception as expected"; } TEST_F(PostConstructTest, VerifyExpectedDeferrmentCount) { AutoCurrentContext ctxt; // Add the smart class, which should introduce a single deferred count: ctxt->Inject<Smarter>(); // Now test the count: ASSERT_EQ( 1UL, ((ContextExposer&)*ctxt).DeferredCount() ) << "Unexpected number of deferred initializers"; } TEST_F(PostConstructTest, VerifySmartBehavior) { AutoCurrentContext ctxt; // Add the smart class, which has a member that autowired type A ctxt->Inject<Smarter>(); // Check that we can get the item we just injected Autowired<Smarter> smarter; ASSERT_TRUE(smarter.IsAutowired()) << "Slot was not satisfied as expected"; ASSERT_EQ(1, smarter->value) << "Unexpected initial value of SmarterA instance"; // Now inject A, and see if delayed autowiring has taken place: ctxt->Inject<A>(); ASSERT_FALSE(!smarter->m_a.get()) << "Autowired member was not wired as expected"; // Verify the value was updated by the notification routine ASSERT_EQ(2, smarter->value) << "Post-construction notification routine wasn't invoked as expected"; } TEST_F(PostConstructTest, VerifySmartBehaviorWithInheritance) { AutoCurrentContext ctxt; // Add the smart classes, which should succeed ctxt->Inject<SmarterInterface>(); //Initially value should be one, which is the default Autowired<SmarterInterface> smarterI; ASSERT_EQ(1, smarterI->value) << "Unexpected initial value of SmarterA instance"; //Now add Implementation and check the wiring ctxt->Inject<Implementation>(); ASSERT_FALSE(!smarterI->m_interface.get()) << "Autowired subclass was not wired as expected"; ASSERT_EQ(2, smarterI->value) << "Post-construction notification routine wasn't invoked on subclass"; } TEST_F(PostConstructTest, VerifyLoopingFailedAutowiring) { for(size_t i = 10; i--;) { Autowired<FailedAutowiringInstance> ignored; ASSERT_FALSE(ignored.IsAutowired()) << "Successfully autowired an instance that should not have been autowirable"; } } TEST_F(PostConstructTest, VerifyTrivialNotifyWhenAutowired) { // Inject a type first: AutoRequired<SimpleObject>(); // Now autowire, and add a registration: bool called = false; Autowired<SimpleObject> so; so.NotifyWhenAutowired([&called] { called = true; }); ASSERT_TRUE(called) << "An autowiring notification was not invoked on an already-satisfied field as expected"; } TEST_F(PostConstructTest, MultiNotifyWhenAutowired) { // Add multiple notifications on the same space: int field = 0; Autowired<SimpleObject> so; for(size_t i = 10; i--;) so.NotifyWhenAutowired([&field] { field++; }); // Inject the type to trigger the autowiring AutoRequired<SimpleObject>(); // Verify that the notification got hit ten times: ASSERT_EQ(10, field) << "Autowiring lambdas did not run the expected number of times"; } TEST_F(PostConstructTest, NotificationTeardownRace) { std::shared_ptr<CoreContext> pContext; auto quit = false; auto shouldQuit = MakeAtExit([&quit] { quit = true; }); std::atomic<size_t> counter{0}; // This thread sets up the race pathology: std::thread t([&] { while(!quit) { // Barrier until setup time: while(counter != 1) std::this_thread::yield(); if(!pContext) break; // Set the context current, then try to autowire: CurrentContextPusher pshr(pContext); Autowired<SimpleObject> sobj; sobj.NotifyWhenAutowired([] {}); // Now barrier, and then we will try to race against the context // for teardown. counter++; } }); for(size_t i = 0; i < 200; i++) { // Make a new context: AutoCreateContext ctxt; pContext = ctxt; // Wake up the other thread, let it set a notify-when-autowired: counter++; while(counter != 2) std::this_thread::yield(); // Counter goes back to zero before we make the next loop iteration: counter = 0; // Now we reset our pContext pointer, and then tell the thread // to race with us against context teardown: pContext.reset(); } // All done, wait for the thread to back out: quit = true; counter = 1; t.join(); } TEST_F(PostConstructTest, VerifyAllInstancesSatisfied) { // Create all of our slots and bind to them: const size_t ct = 3; Autowired<SimpleObject> aw[ct]; bool hit[ct] = {}; for(size_t i = ct; i--;) aw[i].NotifyWhenAutowired([&hit, i] { hit[i] = true; }); // Now we inject our simple object: AutoRequired<SimpleObject>(); // Verify that everything got hit: for(size_t i = 0; i < ct; i++) { ASSERT_TRUE(aw[i]) << "Autowired slot " << i << " was not post-bound correctly"; ASSERT_TRUE(hit[i]) << "Autowired slot " << i << " did not fire all of its post-construct notifiers as expected"; } } TEST_F(PostConstructTest, ContextNotifyWhenAutowired) { auto called = std::make_shared<bool>(false); AutoCurrentContext ctxt; // Now we'd like to be notified when SimpleObject gets added: ctxt->NotifyWhenAutowired<SimpleObject>( [called] { *called = true; } ); // Should only be two uses, at this point, of the capture of the above lambda: ASSERT_EQ(2L, called.use_count()) << "Unexpected number of references held in a capture lambda"; // Create another entry that will add another slot to the deferred list: Autowired<SimpleObject> sobj; // Insert the SimpleObject, see if the lambda got hit: AutoRequired<SimpleObject>(); ASSERT_TRUE(*called) << "Context-wide autowiring notification was not hit as expected when a matching type was injected into a context"; // Our shared pointer should be unique by this point, because the lambda should have been destroyed ASSERT_TRUE(called.unique()) << "Autowiring notification lambda was not properly cleaned up"; } TEST_F(PostConstructTest, ContextNotifyWhenAutowiredPostConstruct) { auto called = std::make_shared<bool>(false); AutoCurrentContext ctxt; // Create an object that will satisfy subsequent notification call: AutoRequired<SimpleObject> sobj; // Notification should be immediate: ctxt->NotifyWhenAutowired<SimpleObject>( [called] { *called = true; } ); // Insert the SimpleObject, see if the lambda got hit: ASSERT_TRUE(*called) << "Context-wide autowiring notification was not hit as expected when a matching type was injected into a context"; // Our shared pointer should be unique by this point, because the lambda should have been destroyed ASSERT_TRUE(called.unique()) << "Autowiring notification lambda was not properly cleaned up"; } class OtherObject : public SimpleObject {}; TEST_F(PostConstructTest, RecursiveNotificationPreConstruction) { auto called = std::make_shared<bool>(false); AutoCurrentContext ctxt; // Ensure that nested calls do not created deadlock // Notification should be deferred: ctxt->NotifyWhenAutowired<SimpleObject>( [called] { AutoCurrentContext()->NotifyWhenAutowired<OtherObject>( [called] { *called = true; }); }); // Create an object that will satisfy subsequent notification call: AutoRequired<SimpleObject> sobj; AutoRequired<OtherObject> oobj; // Insert the SimpleObject, see if the lambda got hit: ASSERT_TRUE(*called) << "Context-wide autowiring notification was not hit as expected when a matching type was injected into a context"; // Our shared pointer should be unique by this point, because the lambda should have been destroyed ASSERT_TRUE(called.unique()) << "Autowiring notification lambda was not properly cleaned up"; } TEST_F(PostConstructTest, RecursiveNotificationPostConstruction) { auto called = std::make_shared<bool>(false); AutoCurrentContext ctxt; // Create an object that will satisfy subsequent notification call: AutoRequired<SimpleObject> sobj; AutoRequired<OtherObject> oobj; // Ensure that nested calls do not created deadlock // Notification should be immediate: ctxt->NotifyWhenAutowired<SimpleObject>( [called] { AutoCurrentContext()->NotifyWhenAutowired<OtherObject>( [called] { *called = true; }); }); // Insert the SimpleObject, see if the lambda got hit: ASSERT_TRUE(*called) << "Context-wide autowiring notification was not hit as expected when a matching type was injected into a context"; // Our shared pointer should be unique by this point, because the lambda should have been destroyed ASSERT_TRUE(called.unique()) << "Autowiring notification lambda was not properly cleaned up"; } struct ClassWithAutoInit: std::enable_shared_from_this<ClassWithAutoInit> { void AutoInit(void) { ASSERT_TRUE(m_constructed) << "A postconstruct routine was called BEFORE the corresponding constructor"; m_postConstructed = true; auto myself = shared_from_this(); ASSERT_EQ(this, myself.get()) << "Reflexive shared_from_this did not return a shared pointer to this as expected"; } bool m_constructed = true; bool m_postConstructed = false; }; static_assert(has_autoinit<ClassWithAutoInit>::value, "AutoInit-bearing class did not pass a static type check"); TEST_F(PostConstructTest, PostConstructGetsCalled) { AutoRequired<ClassWithAutoInit> cwai; ASSERT_TRUE(cwai->m_constructed) << "Trivial constructor call was not made as expected"; ASSERT_TRUE(cwai->m_postConstructed) << "Auto-initialization routine was not called on an initializable type"; } struct PostConstructThrowsException { void AutoInit(void) const { throw std::runtime_error("Autoinit crashing for no reason"); } }; TEST_F(PostConstructTest, PostConstructCanSafelyThrow) { ASSERT_ANY_THROW(AutoRequired<PostConstructThrowsException>()) << "AutoInit call threw an exception, but it was incorrectly eaten by Autowiring"; Autowired<PostConstructThrowsException> pcte; ASSERT_FALSE(pcte.IsAutowired()) << "A context member which threw an exception post-construction was incorrectly introduced into a context"; } namespace { class EmptyType : public CoreObject {}; } TEST_F(PostConstructTest, StrictNotificationArrangement) { size_t call[3] = {0, 0, 0}; size_t callIdx = 1; AutoCurrentContext ctxt; Autowired<EmptyType> obj; obj.NotifyWhenAutowired([&] { call[0] = callIdx++; }); ctxt->NotifyWhenAutowired<EmptyType>([&] { call[1] = callIdx++; }); obj.NotifyWhenAutowired([&] { call[2] = callIdx++; }); ctxt->Inject<EmptyType>(); for (size_t i = 0; i < 3; i++) ASSERT_EQ(i + 1, call[i]) << "Registered autowired handler was not called in the correct order"; }
fix build on mac
fix build on mac
C++
apache-2.0
leapmotion/autowiring,leapmotion/autowiring,codemercenary/autowiring,codemercenary/autowiring,codemercenary/autowiring,codemercenary/autowiring,codemercenary/autowiring,leapmotion/autowiring,leapmotion/autowiring,leapmotion/autowiring,leapmotion/autowiring,codemercenary/autowiring
3b0471a1725ddd522ca911ccc71b9e1e86c60187
ConcurrentQueues/inc/bk_conq/multi_unbounded_queue.hpp
ConcurrentQueues/inc/bk_conq/multi_unbounded_queue.hpp
/* * File: multi_unbounded_queue.hpp * Author: Barath Kannan * Vector of unbounded queues. Enqueue operations are assigned a subqueue, * which is used for all enqueue operations occuring from that thread. The dequeue * operation maintains a list of subqueues on which a "hit" has occured - pertaining * to the subqueues from which a successful dequeue operation has occured. On a * successful dequeue operation, the queue that is used is pushed to the front of the * list. The "hit lists" allow the queue to adapt fairly well to different usage contexts. * Created on 25 September 2016, 12:04 AM */ #ifndef BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP #define BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP #include <thread> #include <vector> #include <bk_conq/unbounded_queue.hpp> namespace bk_conq { template<typename TT, size_t N> class multi_unbounded_queue; template <template <typename> class Q, typename T, size_t N> class multi_unbounded_queue<Q<T>, N> : public unbounded_queue<T, multi_unbounded_queue<Q<T>, N>>{ friend unbounded_queue<T, multi_unbounded_queue<Q<T>, N>>; public: multi_unbounded_queue(size_t subqueues) : _q(subqueues) { static_assert(std::is_base_of<bk_conq::unbounded_queue_typed_tag<T>, Q<T>>::value, "Q<T> must be an unbounded queue"); } multi_unbounded_queue(const multi_unbounded_queue&) = delete; void operator=(const multi_unbounded_queue&) = delete; protected: template <typename R> void sp_enqueue_impl(R&& input) { thread_local size_t indx = _enqueue_indx.fetch_add(1) % _q.size(); _q[indx].sp_enqueue(std::forward<R>(input)); } template <typename R> void mp_enqueue_impl(R&& input) { thread_local size_t indx = _enqueue_indx.fetch_add(1) % _q.size(); _q[indx].mp_enqueue(std::forward<R>(input)); } bool sc_dequeue_impl(T& output) { thread_local std::vector<size_t> hitlist = hitlist_sequence(); for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].sc_dequeue(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } return false; } bool mc_dequeue_impl(T& output) { thread_local std::vector<size_t> hitlist = hitlist_sequence(); for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].mc_dequeue_uncontended(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].mc_dequeue(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } return false; } bool mc_dequeue_uncontended_impl(T& output) { thread_local std::vector<size_t> hitlist = hitlist_sequence(); for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].mc_dequeue_uncontended(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } return false; } private: inline std::vector<size_t> hitlist_sequence() { std::vector<size_t> hitlist(_q.size()); std::iota(hitlist.begin(), hitlist.end(), 0); return hitlist; } class padded_unbounded_queue : public Q<T>{ char padding[64]; }; std::vector<padded_unbounded_queue> _q; std::atomic<size_t> _enqueue_indx{ 0 }; }; }//namespace bk_conq #endif /* BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP */
/* * File: multi_unbounded_queue.hpp * Author: Barath Kannan * Vector of unbounded queues. Enqueue operations are assigned a subqueue, * which is used for all enqueue operations occuring from that thread. The dequeue * operation maintains a list of subqueues on which a "hit" has occured - pertaining * to the subqueues from which a successful dequeue operation has occured. On a * successful dequeue operation, the queue that is used is pushed to the front of the * list. The "hit lists" allow the queue to adapt fairly well to different usage contexts. * Created on 25 September 2016, 12:04 AM */ #ifndef BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP #define BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP #include <thread> #include <vector> #include <mutex> #include <bk_conq/unbounded_queue.hpp> namespace bk_conq { template<typename TT, size_t N=32> class multi_unbounded_queue; template <template <typename> class Q, typename T, size_t N> class multi_unbounded_queue<Q<T>, N> : public unbounded_queue<T, multi_unbounded_queue<Q<T>, N>>{ friend unbounded_queue<T, multi_unbounded_queue<Q<T>, N>>; public: multi_unbounded_queue(size_t subqueues) : _q(subqueues), _hitlist([&]() {return hitlist_sequence(); }), _enqueue_identifier([&]() { return get_enqueue_index(); }, [&](size_t indx) {return return_enqueue_index(indx); }) { static_assert(std::is_base_of<bk_conq::unbounded_queue_typed_tag<T>, Q<T>>::value, "Q<T> must be an unbounded queue"); } multi_unbounded_queue(const multi_unbounded_queue&) = delete; void operator=(const multi_unbounded_queue&) = delete; protected: template <typename R> void sp_enqueue_impl(R&& input) { size_t indx = _enqueue_identifier.get_tlcl(); _q[indx].sp_enqueue(std::forward<R>(input)); } template <typename R> void mp_enqueue_impl(R&& input) { size_t indx = _enqueue_identifier.get_tlcl(); _q[indx].mp_enqueue(std::forward<R>(input)); } bool sc_dequeue_impl(T& output) { auto& hitlist = _hitlist.get_tlcl(); for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].sc_dequeue(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } return false; } bool mc_dequeue_impl(T& output) { auto& hitlist = _hitlist.get_tlcl(); for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].mc_dequeue_uncontended(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].mc_dequeue(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } return false; } bool mc_dequeue_uncontended_impl(T& output) { auto& hitlist = _hitlist.get_tlcl(); for (auto it = hitlist.begin(); it != hitlist.end(); ++it) { if (_q[*it].mc_dequeue_uncontended(output)) { for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2); return true; } } return false; } private: template <typename U> class tlcl { public: tlcl(std::function<U()> defaultvalfunc = nullptr, std::function<void(U)> defaultdeletefunc = nullptr) : _defaultvalfunc(defaultvalfunc), _defaultdeletefunc(defaultdeletefunc) { std::lock_guard<std::mutex> lock(_m); if (!_available.empty()) { _mycounter = _available.back(); _available.pop_back(); } else { _mycounter = _counter++; } } virtual ~tlcl() { std::lock_guard<std::mutex> lock(_m); _available.push_back(_mycounter); } U& get_tlcl() { thread_local std::vector<std::pair<tlcl<U>*, U>> vec; if (vec.size() <= _mycounter) vec.resize(_mycounter+1); auto& ret = vec[_mycounter]; if (ret.first != this) { //reset to default if (_defaultdeletefunc && ret.first != nullptr) _defaultdeletefunc(ret.second); if (_defaultvalfunc) ret.second = _defaultvalfunc(); ret.first = this; } return ret.second; } private: std::function<U()> _defaultvalfunc; std::function<void(U)> _defaultdeletefunc; size_t _mycounter; static size_t _counter; static std::vector<size_t> _available; static std::mutex _m; }; std::vector<size_t> hitlist_sequence() { std::vector<size_t> hitlist(_q.size()); std::iota(hitlist.begin(), hitlist.end(), 0); return hitlist; } size_t get_enqueue_index() { std::lock_guard<std::mutex> lock(_m); if (_unused_enqueue_indexes.empty()) { return _enqueue_index++; } size_t ret = _unused_enqueue_indexes.back(); _unused_enqueue_indexes.pop_back(); return ret; } void return_enqueue_index(size_t index) { std::lock_guard<std::mutex> lock(_m); _unused_enqueue_indexes.push_back(index); } class padded_unbounded_queue : public Q<T>{ char padding[64]; }; std::vector<padded_unbounded_queue> _q; std::vector<size_t> _unused_enqueue_indexes; size_t _enqueue_index{ 0 }; std::mutex _m; tlcl<std::vector<size_t>> _hitlist; tlcl<size_t> _enqueue_identifier; }; template <template <typename> class Q, typename T, size_t N> template <typename U> size_t multi_unbounded_queue<Q<T>, N>::tlcl<U>::_counter = 0; template <template <typename> class Q, typename T, size_t N> template <typename U> std::vector<size_t> multi_unbounded_queue<Q<T>, N>::tlcl<U>::_available; template <template <typename> class Q, typename T, size_t N> template <typename U> std::mutex multi_unbounded_queue<Q<T>, N>::tlcl<U>::_m; }//namespace bk_conq #endif /* BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP */
correct handling of thread local enqueue/dequeue heuristics across class instances
correct handling of thread local enqueue/dequeue heuristics across class instances
C++
unknown
Barath-Kannan/ConcurrentQueues,Barath-Kannan/MPMCQueue
50aa02a46717f04398dd66f5bf299d4aee2844a1
include/cppurses/painter/detail/is_paintable.hpp
include/cppurses/painter/detail/is_paintable.hpp
#ifndef CPPURSES_PAINTER_DETAIL_IS_PAINTABLE_HPP #define CPPURSES_PAINTER_DETAIL_IS_PAINTABLE_HPP #include <cppurses/widget/widget.hpp> namespace cppurses { namespace detail { // TODO should be protected with mutex, not this but each function that it // calls, since these could be modified while flushing.. and this is used while // flushing. /// A check for whether a widget is in a state that can be painted. inline bool is_paintable(const Widget& w) { return w.enabled() && (w.width() != 0) && (w.height() != 0); } } // namespace detail } // namespace cppurses #endif // CPPURSES_PAINTER_DETAIL_IS_PAINTABLE_HPP
#ifndef CPPURSES_PAINTER_DETAIL_IS_PAINTABLE_HPP #define CPPURSES_PAINTER_DETAIL_IS_PAINTABLE_HPP #include <cppurses/widget/widget.hpp> namespace cppurses { namespace detail { // TODO should be protected with mutex, not this but each function that it // calls, since these could be modified while flushing.. and this is used while // flushing. /// A check for whether a widget is in a state that can be painted. inline bool is_paintable(const Widget& w) { return w.enabled() && (w.outer_width() != 0) && (w.outer_height() != 0); } } // namespace detail } // namespace cppurses #endif // CPPURSES_PAINTER_DETAIL_IS_PAINTABLE_HPP
Fix detail::is_paintable()
Fix detail::is_paintable()
C++
mit
a-n-t-h-o-n-y/CPPurses
c9d82e597952d84ab6898dea4a479b19adc30b81
src/client-async/api/client-async-api.cpp
src/client-async/api/client-async-api.cpp
/* * Copyright (c) 2014-2015 Samsung Electronics Co., Ltd 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 */ /** * @file src/client-async/api/client-async-api.cpp * @author Marcin Niesluchowski <[email protected]> * @author Zofia Abramowska <[email protected]> * @author Oskar Świtalski <[email protected]> * @version 1.0 * @brief Implementation of external libcynara-client-async API */ #include <new> #include <common.h> #include <exceptions/TryCatch.h> #include <log/log.h> #include <types/string_validation.h> #include <api/ApiInterface.h> #include <configuration/Configuration.h> #include <cynara-client-async.h> #include <logic/Logic.h> struct cynara_async { Cynara::ApiInterface *impl; cynara_async(Cynara::ApiInterface *_impl) : impl(_impl) { } ~cynara_async() { delete impl; } }; struct cynara_async_configuration { Cynara::Configuration* impl; cynara_async_configuration(Cynara::Configuration *_impl) : impl(_impl) {} ~cynara_async_configuration() { delete impl; } }; CYNARA_API int cynara_async_configuration_create(cynara_async_configuration **pp_conf) { if (!pp_conf) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { Cynara::ConfigurationUniquePtr ptr(new Cynara::Configuration()); *pp_conf = new cynara_async_configuration(ptr.get()); ptr.release(); LOGD("Cynara configuration initialized"); return CYNARA_API_SUCCESS; }); } CYNARA_API void cynara_async_configuration_destroy(cynara_async_configuration *p_conf) { delete p_conf; } CYNARA_API int cynara_async_configuration_set_cache_size(cynara_async_configuration *p_conf, size_t cache_size) { if (!p_conf || !p_conf->impl) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { p_conf->impl->setCacheSize(cache_size); return CYNARA_API_SUCCESS; }); } CYNARA_API int cynara_async_initialize(cynara_async **pp_cynara, const cynara_async_configuration *p_conf, cynara_status_callback callback, void *user_status_data) { if (!pp_cynara) return CYNARA_API_INVALID_PARAM; init_log(); return Cynara::tryCatch([&]() { Cynara::LogicUniquePtr ptr; if (p_conf && p_conf->impl) { ptr.reset(new Cynara::Logic(callback, user_status_data, *(p_conf->impl))); } else { ptr.reset(new Cynara::Logic(callback, user_status_data)); } *pp_cynara = new cynara_async(ptr.get()); ptr.release(); LOGD("Cynara client async initialized"); return CYNARA_API_SUCCESS; }); } CYNARA_API void cynara_async_finish(cynara_async *p_cynara) { if (!p_cynara->impl->isFinishPermitted()) return; delete p_cynara; } CYNARA_API int cynara_async_check_cache(cynara_async *p_cynara, const char *client, const char *client_session, const char *user, const char *privilege) { if (!p_cynara || !p_cynara->impl) return CYNARA_API_INVALID_PARAM; if (!isStringValid(client) || !isStringValid(client_session)) return CYNARA_API_INVALID_PARAM; if (!isStringValid(user) || !isStringValid(privilege)) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { std::string clientStr; std::string clientSessionStr; std::string userStr; std::string privilegeStr; try { clientStr = client; clientSessionStr = client_session; userStr = user; privilegeStr = privilege; } catch (const std::length_error &e) { LOGE("%s", e.what()); return CYNARA_API_INVALID_PARAM; } return p_cynara->impl->checkCache(clientStr, clientSessionStr, userStr, privilegeStr); }); } CYNARA_API int cynara_async_create_request(cynara_async *p_cynara, const char *client, const char *client_session, const char *user, const char *privilege, cynara_check_id *p_check_id, cynara_response_callback callback, void *user_response_data) { if (!p_cynara || !p_cynara->impl) return CYNARA_API_INVALID_PARAM; if (!isStringValid(client) || !isStringValid(client_session)) return CYNARA_API_INVALID_PARAM; if (!isStringValid(user) || !isStringValid(privilege)) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { std::string clientStr; std::string clientSessionStr; std::string userStr; std::string privilegeStr; try { clientStr = client; clientSessionStr = client_session; userStr = user; privilegeStr = privilege; } catch (const std::length_error &e) { LOGE("%s", e.what()); return CYNARA_API_INVALID_PARAM; } cynara_check_id checkId; int ret = p_cynara->impl->createCheckRequest(clientStr, clientSessionStr, userStr, privilegeStr, checkId, callback, user_response_data); if (p_check_id && ret == CYNARA_API_SUCCESS) *p_check_id = checkId; return ret; }); } CYNARA_API int cynara_async_create_simple_request(cynara_async *p_cynara, const char *client, const char *client_session, const char *user, const char *privilege, cynara_check_id *p_check_id, cynara_response_callback callback, void *user_response_data){ if (!p_cynara || !p_cynara->impl) return CYNARA_API_INVALID_PARAM; if (!isStringValid(client) || !isStringValid(client_session)) return CYNARA_API_INVALID_PARAM; if (!isStringValid(user) || !isStringValid(privilege)) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { std::string clientStr; std::string clientSessionStr; std::string userStr; std::string privilegeStr; try { clientStr = client; clientSessionStr = client_session; userStr = user; privilegeStr = privilege; } catch (const std::length_error &e) { LOGE("%s", e.what()); return CYNARA_API_INVALID_PARAM; } cynara_check_id checkId; int ret = p_cynara->impl->createSimpleRequest(clientStr, clientSessionStr, userStr, privilegeStr, checkId, callback, user_response_data); if (p_check_id && ret == CYNARA_API_SUCCESS) *p_check_id = checkId; return ret; }); } CYNARA_API int cynara_async_process(cynara_async *p_cynara) { if (!p_cynara || !p_cynara->impl) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { return p_cynara->impl->process(); }); } CYNARA_API int cynara_async_cancel_request(cynara_async *p_cynara, cynara_check_id check_id) { if (!p_cynara || !p_cynara->impl) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { return p_cynara->impl->cancelRequest(check_id); }); }
/* * Copyright (c) 2014-2015 Samsung Electronics Co., Ltd 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 */ /** * @file src/client-async/api/client-async-api.cpp * @author Marcin Niesluchowski <[email protected]> * @author Zofia Abramowska <[email protected]> * @author Oskar Świtalski <[email protected]> * @version 1.0 * @brief Implementation of external libcynara-client-async API */ #include <new> #include <common.h> #include <exceptions/TryCatch.h> #include <log/log.h> #include <types/string_validation.h> #include <api/ApiInterface.h> #include <configuration/Configuration.h> #include <cynara-client-async.h> #include <logic/Logic.h> struct cynara_async { Cynara::ApiInterface *impl; cynara_async(Cynara::ApiInterface *_impl) : impl(_impl) { } ~cynara_async() { delete impl; } }; struct cynara_async_configuration { Cynara::Configuration* impl; cynara_async_configuration(Cynara::Configuration *_impl) : impl(_impl) {} ~cynara_async_configuration() { delete impl; } }; CYNARA_API int cynara_async_configuration_create(cynara_async_configuration **pp_conf) { if (!pp_conf) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { Cynara::ConfigurationUniquePtr ptr(new Cynara::Configuration()); *pp_conf = new cynara_async_configuration(ptr.get()); ptr.release(); LOGD("Cynara configuration initialized"); return CYNARA_API_SUCCESS; }); } CYNARA_API void cynara_async_configuration_destroy(cynara_async_configuration *p_conf) { delete p_conf; } CYNARA_API int cynara_async_configuration_set_cache_size(cynara_async_configuration *p_conf, size_t cache_size) { if (!p_conf || !p_conf->impl) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { p_conf->impl->setCacheSize(cache_size); return CYNARA_API_SUCCESS; }); } CYNARA_API int cynara_async_initialize(cynara_async **pp_cynara, const cynara_async_configuration *p_conf, cynara_status_callback callback, void *user_status_data) { if (!pp_cynara) return CYNARA_API_INVALID_PARAM; init_log(); return Cynara::tryCatch([&]() { Cynara::LogicUniquePtr ptr; if (p_conf && p_conf->impl) { ptr.reset(new Cynara::Logic(callback, user_status_data, *(p_conf->impl))); } else { ptr.reset(new Cynara::Logic(callback, user_status_data)); } *pp_cynara = new cynara_async(ptr.get()); ptr.release(); LOGD("Cynara client async initialized"); return CYNARA_API_SUCCESS; }); } CYNARA_API void cynara_async_finish(cynara_async *p_cynara) { if (!p_cynara || !p_cynara->impl->isFinishPermitted()) return; delete p_cynara; } CYNARA_API int cynara_async_check_cache(cynara_async *p_cynara, const char *client, const char *client_session, const char *user, const char *privilege) { if (!p_cynara || !p_cynara->impl) return CYNARA_API_INVALID_PARAM; if (!isStringValid(client) || !isStringValid(client_session)) return CYNARA_API_INVALID_PARAM; if (!isStringValid(user) || !isStringValid(privilege)) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { std::string clientStr; std::string clientSessionStr; std::string userStr; std::string privilegeStr; try { clientStr = client; clientSessionStr = client_session; userStr = user; privilegeStr = privilege; } catch (const std::length_error &e) { LOGE("%s", e.what()); return CYNARA_API_INVALID_PARAM; } return p_cynara->impl->checkCache(clientStr, clientSessionStr, userStr, privilegeStr); }); } CYNARA_API int cynara_async_create_request(cynara_async *p_cynara, const char *client, const char *client_session, const char *user, const char *privilege, cynara_check_id *p_check_id, cynara_response_callback callback, void *user_response_data) { if (!p_cynara || !p_cynara->impl) return CYNARA_API_INVALID_PARAM; if (!isStringValid(client) || !isStringValid(client_session)) return CYNARA_API_INVALID_PARAM; if (!isStringValid(user) || !isStringValid(privilege)) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { std::string clientStr; std::string clientSessionStr; std::string userStr; std::string privilegeStr; try { clientStr = client; clientSessionStr = client_session; userStr = user; privilegeStr = privilege; } catch (const std::length_error &e) { LOGE("%s", e.what()); return CYNARA_API_INVALID_PARAM; } cynara_check_id checkId; int ret = p_cynara->impl->createCheckRequest(clientStr, clientSessionStr, userStr, privilegeStr, checkId, callback, user_response_data); if (p_check_id && ret == CYNARA_API_SUCCESS) *p_check_id = checkId; return ret; }); } CYNARA_API int cynara_async_create_simple_request(cynara_async *p_cynara, const char *client, const char *client_session, const char *user, const char *privilege, cynara_check_id *p_check_id, cynara_response_callback callback, void *user_response_data){ if (!p_cynara || !p_cynara->impl) return CYNARA_API_INVALID_PARAM; if (!isStringValid(client) || !isStringValid(client_session)) return CYNARA_API_INVALID_PARAM; if (!isStringValid(user) || !isStringValid(privilege)) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { std::string clientStr; std::string clientSessionStr; std::string userStr; std::string privilegeStr; try { clientStr = client; clientSessionStr = client_session; userStr = user; privilegeStr = privilege; } catch (const std::length_error &e) { LOGE("%s", e.what()); return CYNARA_API_INVALID_PARAM; } cynara_check_id checkId; int ret = p_cynara->impl->createSimpleRequest(clientStr, clientSessionStr, userStr, privilegeStr, checkId, callback, user_response_data); if (p_check_id && ret == CYNARA_API_SUCCESS) *p_check_id = checkId; return ret; }); } CYNARA_API int cynara_async_process(cynara_async *p_cynara) { if (!p_cynara || !p_cynara->impl) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { return p_cynara->impl->process(); }); } CYNARA_API int cynara_async_cancel_request(cynara_async *p_cynara, cynara_check_id check_id) { if (!p_cynara || !p_cynara->impl) return CYNARA_API_INVALID_PARAM; return Cynara::tryCatch([&]() { return p_cynara->impl->cancelRequest(check_id); }); }
Fix SIGSEGV when passing nullptr to cynara_async_finish
Fix SIGSEGV when passing nullptr to cynara_async_finish cynara_async_finish should check if cynara_async pointer is empty before any other action. Change-Id: Ic9019c274a26f1d6802c31cad3b5f83a86c27c00
C++
apache-2.0
Samsung/cynara,Samsung/cynara,Samsung/cynara
ca6e5d39a8bf4136b11c14af64c3bf8de896bc5f
grantlee_defaultfilters/lists.cpp
grantlee_defaultfilters/lists.cpp
/* This file is part of the Grantlee template system. Copyright (c) 2009 Stephen Kelly <[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 version 3 only, 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 version 3 for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "lists.h" #include <util_p.h> #include <QDateTime> JoinFilter::JoinFilter() { } QVariant JoinFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { QVariantList varList = Util::variantToList( input ); QListIterator<QVariant> i( varList ); QString ret; while ( i.hasNext() ) { QVariant var = i.next(); Grantlee::SafeString s = Util::getSafeString( var ); if ( autoescape ) s = Util::conditionalEscape( s ); ret.append( s ); if ( i.hasNext() ) { SafeString argString = Util::getSafeString( argument ); ret.append( argString ); } } return Util::markSafe( ret ); } LengthFilter::LengthFilter() { } QVariant LengthFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { return Util::variantToList( input ).size(); } LengthIsFilter::LengthIsFilter() { } QVariant LengthIsFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { return Util::variantToList( input ).size() == QVariant( argument ).toInt(); } FirstFilter::FirstFilter() { } QVariant FirstFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { QVariantList varList = Util::variantToList( input ); if ( varList.isEmpty() ) return QString(); return varList.at( 0 ); } LastFilter::LastFilter() { } QVariant LastFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { QVariantList varList = Util::variantToList( input ); if ( varList.isEmpty() ) return QString(); return varList.at( varList.size() - 1 ); } RandomFilter::RandomFilter() { } QVariant RandomFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { QVariantList varList = Util::variantToList( input ); qsrand( QDateTime::currentDateTime().toTime_t() ); int rnd = qrand() % varList.size(); return varList.at( rnd ); } SliceFilter::SliceFilter() { } QVariant SliceFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { SafeString argString = Util::getSafeString( argument ); int splitterIndex = argString.indexOf( ":" ); QString inputString = Util::getSafeString( input ); if ( splitterIndex >= 0 ) { int left = QVariant( argString.left( splitterIndex ) ).toInt(); int right = QVariant( argString.right( splitterIndex ) ).toInt(); if ( right < 0 ) { right = inputString.size() + right; } return inputString.mid( left, right ); } else { return QString( inputString.at( argument.toInt() ) ); } }
/* This file is part of the Grantlee template system. Copyright (c) 2009 Stephen Kelly <[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 version 3 only, 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 version 3 for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "lists.h" #include <util_p.h> #include <QDateTime> JoinFilter::JoinFilter() { } QVariant JoinFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { QVariantList varList = Util::variantToList( input ); QListIterator<QVariant> i( varList ); QString ret; while ( i.hasNext() ) { QVariant var = i.next(); Grantlee::SafeString s = Util::getSafeString( var ); if ( autoescape ) s = Util::conditionalEscape( s ); ret.append( s ); if ( i.hasNext() ) { SafeString argString = Util::getSafeString( argument ); ret.append( argString ); } } return Util::markSafe( ret ); } LengthFilter::LengthFilter() { } QVariant LengthFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { if (input.type() == QVariant::List) return input.toList().size(); if (input.userType() == qMetaTypeId<SafeString>() || input.type() == QVariant::String) return Util::getSafeString( input ).size(); return QVariant(); } LengthIsFilter::LengthIsFilter() { } QVariant LengthIsFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { return Util::variantToList( input ).size() == QVariant( argument ).toInt(); } FirstFilter::FirstFilter() { } QVariant FirstFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { QVariantList varList = Util::variantToList( input ); if ( varList.isEmpty() ) return QString(); return varList.at( 0 ); } LastFilter::LastFilter() { } QVariant LastFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { QVariantList varList = Util::variantToList( input ); if ( varList.isEmpty() ) return QString(); return varList.at( varList.size() - 1 ); } RandomFilter::RandomFilter() { } QVariant RandomFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { QVariantList varList = Util::variantToList( input ); qsrand( QDateTime::currentDateTime().toTime_t() ); int rnd = qrand() % varList.size(); return varList.at( rnd ); } SliceFilter::SliceFilter() { } QVariant SliceFilter::doFilter( const QVariant& input, const QVariant &argument, bool autoescape ) const { SafeString argString = Util::getSafeString( argument ); int splitterIndex = argString.indexOf( ":" ); QString inputString = Util::getSafeString( input ); if ( splitterIndex >= 0 ) { int left = QVariant( argString.left( splitterIndex ) ).toInt(); int right = QVariant( argString.right( splitterIndex ) ).toInt(); if ( right < 0 ) { right = inputString.size() + right; } return inputString.mid( left, right ); } else { return QString( inputString.at( argument.toInt() ) ); } }
Fix the length filter to not return a length of one where it should be 0.
Fix the length filter to not return a length of one where it should be 0.
C++
lgpl-2.1
cutelyst/grantlee,cutelyst/grantlee,simonwagner/grantlee,simonwagner/grantlee,cutelyst/grantlee,simonwagner/grantlee,cutelyst/grantlee,simonwagner/grantlee,simonwagner/grantlee,simonwagner/grantlee,cutelyst/grantlee
bae2915101d53ce885dd0bc6d637d82ace1e2eec
include/hpp/core/continuous-validation/interval-validation.hh
include/hpp/core/continuous-validation/interval-validation.hh
// // Copyright (c) 2014,2015,2016,2018 CNRS // Authors: Florent Lamiraux, Joseph Mirabel, Diane Bury // // This file is part of hpp-core // hpp-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. // // hpp-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 // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #ifndef HPP_CORE_CONTINUOUS_VALIDATION_INTERVAL_VALIDATION_HH #define HPP_CORE_CONTINUOUS_VALIDATION_INTERVAL_VALIDATION_HH #include <limits> #include <iterator> #include <boost/icl/continuous_interval.hpp> #include <boost/icl/interval_set.hpp> #include <hpp/fcl/collision_data.h> #include <hpp/fcl/collision.h> #include <hpp/pinocchio/body.hh> #include <hpp/pinocchio/collision-object.hh> #include <hpp/pinocchio/joint.hh> #include <hpp/core/deprecated.hh> #include <hpp/core/fwd.hh> namespace hpp { namespace core { namespace continuousValidation { /// Computation of collision-free sub-intervals of a path /// /// This class aims at validating a path for the absence of collision /// between two bodies of a robot. /// /// The interval of definition of the path is successively covered /// by intervals where boths bodies are proved to be collision-free. /// Each interval is computed by bounding from above the velocity of /// all points of body 1 in the reference frame of body 2. template <typename ValidationReportTypePtr_t> class IntervalValidation { public: virtual bool validateConfiguration(const value_type &t, interval_t &interval, ValidationReportTypePtr_t &report, pinocchio::DeviceData& data) = 0; /// Set path to validate /// \param path path to validate, /// \param reverse whether path is validated from end to beginning. void path(const PathPtr_t &path, bool reverse) { path_ = path; reverse_ = reverse; valid_ = false; validInterval_ = interval_set(); setupPath(); } /// Get path PathConstPtr_t path() const { return path_; } value_type tolerance() const { return tolerance_; } virtual std::string name () const = 0; virtual std::ostream& print (std::ostream& os) const = 0; protected: typedef boost::icl::continuous_interval<value_type> continuous_interval; typedef boost::icl::interval_set<value_type> interval_set; PathPtr_t path_; value_type tolerance_; bool reverse_; bool refine_; bool valid_; interval_set validInterval_; /// Constructor of interval validation element /// /// \param tolerance allowed penetration should be positive IntervalValidation (value_type tolerance) : tolerance_(tolerance), reverse_(false), refine_(true) { if (tolerance < 0) { throw std::runtime_error ("tolerance should be non-negative."); } } IntervalValidation (const IntervalValidation& other) : tolerance_(other.tolerance_), refine_(true) { if (tolerance_ < 0) { throw std::runtime_error ("tolerance should be non-negative."); } } private: virtual void setupPath() = 0; }; // class IntervalValidation template <typename ValidationReportTypePtr_t> inline std::ostream &operator<<(std::ostream &os, const IntervalValidation<ValidationReportTypePtr_t> &b) { return b.print(os); } } // namespace continuousValidation } // namespace core } // namespace hpp #endif // HPP_CORE_CONTINUOUS_VALIDATION_INTERVAL_VALIDATION_HH
// // Copyright (c) 2014,2015,2016,2018 CNRS // Authors: Florent Lamiraux, Joseph Mirabel, Diane Bury // // This file is part of hpp-core // hpp-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. // // hpp-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 // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #ifndef HPP_CORE_CONTINUOUS_VALIDATION_INTERVAL_VALIDATION_HH #define HPP_CORE_CONTINUOUS_VALIDATION_INTERVAL_VALIDATION_HH #include <limits> #include <iterator> #include <boost/icl/continuous_interval.hpp> #include <boost/icl/interval_set.hpp> #include <hpp/fcl/collision_data.h> #include <hpp/fcl/collision.h> #include <hpp/pinocchio/body.hh> #include <hpp/pinocchio/collision-object.hh> #include <hpp/pinocchio/joint.hh> #include <hpp/core/deprecated.hh> #include <hpp/core/fwd.hh> namespace hpp { namespace core { namespace continuousValidation { /// Computation of collision-free sub-intervals of a path /// /// This class aims at validating a path interval for for a given /// criterion. Up to now the only criterion handled is the collision /// between rigid bodies (robot bodies or obstacles). /// \sa BodyPairCollision. template <typename ValidationReportTypePtr_t> class IntervalValidation { public: virtual bool validateConfiguration(const value_type &t, interval_t &interval, ValidationReportTypePtr_t &report, pinocchio::DeviceData& data) = 0; /// Set path to validate /// \param path path to validate, /// \param reverse whether path is validated from end to beginning. void path(const PathPtr_t &path, bool reverse) { path_ = path; reverse_ = reverse; valid_ = false; validInterval_ = interval_set(); setupPath(); } /// Get path PathConstPtr_t path() const { return path_; } value_type tolerance() const { return tolerance_; } virtual std::string name () const = 0; virtual std::ostream& print (std::ostream& os) const = 0; protected: typedef boost::icl::continuous_interval<value_type> continuous_interval; typedef boost::icl::interval_set<value_type> interval_set; PathPtr_t path_; value_type tolerance_; bool reverse_; bool refine_; bool valid_; interval_set validInterval_; /// Constructor of interval validation element /// /// \param tolerance allowed penetration should be positive IntervalValidation (value_type tolerance) : tolerance_(tolerance), reverse_(false), refine_(true) { if (tolerance < 0) { throw std::runtime_error ("tolerance should be non-negative."); } } IntervalValidation (const IntervalValidation& other) : tolerance_(other.tolerance_), refine_(true) { if (tolerance_ < 0) { throw std::runtime_error ("tolerance should be non-negative."); } } private: virtual void setupPath() = 0; }; // class IntervalValidation template <typename ValidationReportTypePtr_t> inline std::ostream &operator<<(std::ostream &os, const IntervalValidation<ValidationReportTypePtr_t> &b) { return b.print(os); } } // namespace continuousValidation } // namespace core } // namespace hpp #endif // HPP_CORE_CONTINUOUS_VALIDATION_INTERVAL_VALIDATION_HH
Rewrite documentation of class IntervalValidation.
[Doc] Rewrite documentation of class IntervalValidation.
C++
bsd-2-clause
humanoid-path-planner/hpp-core
63f748a2fabec07216cfb2503afd34d852117e13
copasi/output/CNodeO.cpp
copasi/output/CNodeO.cpp
/***************************************************************************** * PROGRAM NAME: CNodeO.cpp * PROGRAMMER: Wei Sun [email protected] * PURPOSE: Implement the node object in user defined function *****************************************************************************/ #include "copasi.h" #include "CDatum.h" #include "CNodeO.h" /** * Default constructor */ CNodeO::CNodeO() { mDatumType = 0; mTitle = ""; mI = ""; mJ = ""; mDatum = NULL; } /** * Constructor for operator * @param "const char" type * @param "const char" subtype */ CNodeO::CNodeO(string title, C_INT32 type, string i_str, string j_str) { mDatumType = type; mTitle = title; mI = i_str; mJ = j_str; mDatum = NULL; } /** * Destructor */ CNodeO::~CNodeO() { // if this is an identifier delete the CDatum if( (getType()==N_IDENTIFIER) && mDatum != NULL ) { delete mDatum; mDatum = NULL; } } /** * Delete */ void CNodeO::cleanup() { } /** * Loads an object with data coming from a CReadConfig object. * (CReadConfig object reads an input stream) * @param pconfigbuffer reference to a CReadConfig object. * @return Fail */ C_INT32 CNodeO::load(CReadConfig & configbuffer) { C_INT32 Fail = 0; char Type, Subtype; C_FLOAT64 Constant; if ((Fail = configbuffer.getVariable("Node", "node", &Type, &Subtype, CReadConfig::SEARCH))) return Fail; setType(Type); setSubtype(Subtype); if (isIdentifier() && getType() != N_IDENTIFIER) { setSubtype(getType()); setType(N_IDENTIFIER); } // leave the Left & Right pointers out // value of the constant if one if (getType() == N_NUMBER) { if ((Fail = configbuffer.getVariable("Value", "C_FLOAT64", &Constant))) return Fail; setConstant(Constant); } else if (getType() == N_IDENTIFIER) { if ((Fail = configbuffer.getVariable("Title", "string", &mTitle))) return Fail; if ((Fail = configbuffer.getVariable("Type", "C_INT32", &mDatumType))) return Fail; switch (mDatumType) { case D_UNDEF: // Fall through as all have no mI and no mJ case D_T: case D_RT: case D_INTS: case D_FEVAL: case D_JEVAL: case D_SSIZE: case D_RTOL: case D_ATOL: case D_SSRES: case D_UFUNC: // D_UFUNC has mI case D_DERIV: case D_ENDT: case D_POINT: case D_EIGMR: case D_EIGMI: case D_EIGPR: case D_EIGNR: case D_EIGR: case D_EIGI: case D_EIGC: case D_EIGZ: case D_THIER: case D_STIFF: break; case D_ICONC: // Fall through as all have mI but no mJ case D_SCONC: case D_TCONC: case D_SFLUX: case D_TFLUX: case D_VOL: case D_MOIT: case D_TT: case D_EIGVR: case D_EIGVI: Fail = configbuffer.getVariable("I", "string", (void *) &mI); if (Fail) return Fail; break; case D_KIN: // Fall through as all have mI and mJ case D_ELAST: case D_CCC: case D_FCC: case D_EIG: Fail = configbuffer.getVariable("I", (string) "string", (void *) &mI); if (Fail) return Fail; Fail = configbuffer.getVariable((string) "J", (string) "string", (void *) &mJ); if (Fail) return Fail; break; default: Fail = 1; // we should never get here! break; } // end of switch } return Fail; } /** * Saves the contents of the object to a CWriteConfig object. * (Which usually has a file attached but may also have socket) * @param pconfigbuffer reference to a CWriteConfig object. * @return Fail */ C_INT32 CNodeO::save(CWriteConfig & configbuffer) const { C_INT32 Fail = 0; char Type, Subtype; Type = getType(); Subtype = getSubtype(); if ((Fail = configbuffer.setVariable("Node", "node", &Type, &Subtype))) return Fail; // leave the Left & Right pointers out // value of the constant if one if (Type==N_NUMBER) { C_FLOAT64 Constant = getConstant(); if ((Fail = configbuffer.setVariable("Value", "C_FLOAT64", &Constant))) return Fail; } else if (isIdentifier()) { // Output Title if ((Fail = configbuffer.setVariable("Title", "string", &mTitle))) return Fail; // Output Type if ((Fail = configbuffer.setVariable("Type", "C_INT32", &mDatumType))) return Fail; // Output Type as well as I String // some types need more output... (mI or mJ) switch (mDatumType) { case D_UNDEF: // Fall through as all have no mI and no mJ case D_T: case D_RT: case D_INTS: case D_FEVAL: case D_JEVAL: case D_SSIZE: case D_RTOL: case D_ATOL: case D_SSRES: case D_UFUNC: // D_UFUNC has mI case D_DERIV: case D_ENDT: case D_POINT: case D_EIGMR: case D_EIGMI: case D_EIGPR: case D_EIGNR: case D_EIGR: case D_EIGI: case D_EIGC: case D_EIGZ: case D_THIER: case D_STIFF: break; case D_ICONC: // Fall through as all have mI but no mJ case D_SCONC: case D_TCONC: case D_SFLUX: case D_TFLUX: case D_VOL: case D_MOIT: case D_TT: case D_EIGVR: case D_EIGVI: Fail = configbuffer.setVariable("I", "string", &mI); if (Fail) return Fail; break; case D_KIN: // Fall through as all have mI and mJ case D_ELAST: case D_CCC: case D_FCC: case D_EIG: Fail = configbuffer.setVariable("I", "string", &mI); if (Fail) return Fail; Fail = configbuffer.setVariable("J", "string", &mJ); if (Fail) return Fail; break; default: Fail = 1; // we should never get here! break; } // end of switch } return Fail; } /** * Retrieving the Title of a node * @return string */ string CNodeO::getTitle() const { return mTitle; } /** * Retrieving I String of a node * @return string */ string CNodeO::getIString() const { return mI; } /** * Retrieving J String of a node * @return string */ string CNodeO::getJString() const { return mJ; } /** * Setting Title of the node * @param "const string" &title */ void CNodeO::setTitle(const string & title) { mTitle = title; } /** * Setting I String of the node * @param "const string" &i_string */ void CNodeO::setIString(const string & i_string) { mI = i_string; } /** * Setting I String of the node * @param "const string" &j_string */ void CNodeO::setJString(const string & j_string) { mJ = j_string; } /** * Get the node's Datum type */ C_INT32 CNodeO::getDatumType() const { return mDatumType; } /** * Calculates the value of this sub-tree */ C_FLOAT64 CNodeO::value() { // if it is a constant or a variable just return its value if(getType() == N_NUMBER) return getConstant(); if(isIdentifier()) { C_INT32 Type; C_INT16 *Value1; C_INT32 *Value2; C_FLOAT32 *Value3; C_FLOAT64 *Value4; C_FLOAT64 Value; Type = mDatum->getType(); switch (Type) { case 1: Value1 = (C_INT16 *)mDatum->getValue(); Value = (C_FLOAT64) *Value1; break; case 2: Value2 = (C_INT32 *)mDatum->getValue(); Value = (C_FLOAT64) *Value2; break; case 3: Value3 = (C_FLOAT32 *)mDatum->getValue(); Value = (C_FLOAT64) *Value3; break; case 4: Value4 = (C_FLOAT64 *)mDatum->getValue(); Value = (C_FLOAT64) *Value4; break; } return Value; } return 0.0; } /** * Retrieving mLeft the left branch of a node * @return CNodeO */ CNodeO & CNodeO::getLeft() const { if (!mLeft) fatalError(); // Call LeftIsValid first to avoid this! return *mLeft; } /** * Retrieving mRight the left branch of a node * @return CNodeO */ CNodeO & CNodeO::getRight() const { if (!mRight) fatalError(); // Call RightIsValid first to avoid this! return *mRight; } /** * Setting mLeft the pointer to the left branch * @param CNodeO &left */ void CNodeO::setLeft(CNodeO & left) { mLeft = &left; } /** * Setting mLeft the pointer to the left branch * @param CNodeO *pleft */ void CNodeO::setLeft(CNodeO * pleft) { mLeft = pleft; } /** * Setting mRight the pointer to the right branch * @param CNodeO &right */ void CNodeO::setRight(CNodeO & right) { mRight = &right; } /** * Setting mRight the pointer to the right branch * @param CNodeO *pright */ void CNodeO::setRight(CNodeO * pright) { mRight = pright; }
/***************************************************************************** * PROGRAM NAME: CNodeO.cpp * PROGRAMMER: Wei Sun [email protected] * PURPOSE: Implement the node object in user defined function *****************************************************************************/ #include <math.h> #include <iostream> #include "copasi.h" #include "CDatum.h" #include "CNodeO.h" /** * Default constructor */ CNodeO::CNodeO() { // mDatumType = 0; // mTitle = ""; // mI = ""; // mJ = ""; mDatum = NULL; } /** * Constructor for operator * @param "const char" type * @param "const char" subtype */ CNodeO::CNodeO(CDatum &datum) { // mDatumType = type; // mTitle = title; // mI = i_str; // mJ = j_str; mDatum = &datum; } /** * Destructor */ CNodeO::~CNodeO() { #if 0 // if this is an identifier delete the CDatum if( (getType()==N_IDENTIFIER) && mDatum != NULL ) { delete mDatum; mDatum = NULL; } #endif } /** * Delete */ void CNodeO::cleanup() { } /** * Loads an object with data coming from a CReadConfig object. * (CReadConfig object reads an input stream) * @param pconfigbuffer reference to a CReadConfig object. * @return Fail */ C_INT32 CNodeO::load(CReadConfig & configbuffer) { C_INT32 Fail = 0; char Type, Subtype; C_FLOAT64 Constant; if ((Fail = configbuffer.getVariable("Node", "node", &Type, &Subtype, CReadConfig::SEARCH))) return Fail; setType(Type); setSubtype(Subtype); if (isIdentifier() && getType() != N_IDENTIFIER) { setSubtype(getType()); setType(N_IDENTIFIER); } // leave the Left & Right pointers out // value of the constant if one if (getType() == N_NUMBER) { if ((Fail = configbuffer.getVariable("Value", "C_FLOAT64", &Constant))) return Fail; setConstant(Constant); } else if (getType() == N_IDENTIFIER) { mDatum = new CDatum; mDatum->load(configbuffer); } return Fail; } /** * Saves the contents of the object to a CWriteConfig object. * (Which usually has a file attached but may also have socket) * @param pconfigbuffer reference to a CWriteConfig object. * @return Fail */ C_INT32 CNodeO::save(CWriteConfig & configbuffer) const { C_INT32 Fail = 0; char Type, Subtype; Type = getType(); Subtype = getSubtype(); if ((Fail = configbuffer.setVariable("Node", "node", &Type, &Subtype))) return Fail; // leave the Left & Right pointers out // value of the constant if one if (Type==N_NUMBER) { C_FLOAT64 Constant = getConstant(); if ((Fail = configbuffer.setVariable("Value", "C_FLOAT64", &Constant))) return Fail; } else if (isIdentifier()) { mDatum->save(configbuffer); } return Fail; } /** * Calculates the value of this sub-tree */ C_FLOAT64 CNodeO::value(CModel *model) { char NodeType, NodeSubtype; NodeType = getType(); NodeSubtype = getSubtype(); // if it is a constant or a variable just return its value if(NodeType == N_NUMBER) return getConstant(); switch (NodeType) { case N_IDENTIFIER : C_INT32 Type; C_INT16 *Value1; C_INT32 *Value2; C_FLOAT32 *Value3; C_FLOAT64 *Value4; C_FLOAT64 Value; mDatum->compileDatum(model, NULL); Type = mDatum->getType(); switch (Type) { case 1: Value1 = (C_INT16 *)mDatum->getValue(); Value = (C_FLOAT64) *Value1; break; case 2: Value2 = (C_INT32 *)mDatum->getValue(); Value = (C_FLOAT64) *Value2; break; case 3: Value3 = (C_FLOAT32 *)mDatum->getValue(); Value = (C_FLOAT64) *Value3; break; case 4: Value4 = (C_FLOAT64 *)mDatum->getValue(); Value = (C_FLOAT64) *Value4; break; } return Value; break; case N_OPERATOR: switch (NodeSubtype) { case '+': return mLeft->value(model) + mRight->value(model); case '-': return mLeft->value(model) - mRight->value(model); case '*': return mLeft->value(model) * mRight->value(model); case '/': return mLeft->value(model) / mRight->value(model); case '^': return pow(mLeft->value(model), mRight->value(model)); default: fatalError(); // THROW EXCEPTION return 0.0; } break; case N_FUNCTION: switch (NodeSubtype) { case '+': return mLeft->value(model); case '-': return - mLeft->value(model); case N_EXP: return exp(mLeft->value(model)); case N_LOG: return log(mLeft->value(model)); case N_LOG10: return log10(mLeft->value(model)); case N_SIN: return sin(mLeft->value(model)); case N_COS: return cos(mLeft->value(model)); default: fatalError(); // THROW EXCEPTION return 0.0; } break; default: fatalError(); // THROW EXCEPTION return 0.0; } fatalError(); // THROW EXCEPTION return 0.0; } /** * Retrieving mLeft the left branch of a node * @return CNodeO */ CNodeO & CNodeO::getLeft() const { if (!mLeft) fatalError(); // Call LeftIsValid first to avoid this! return *mLeft; } /** * Retrieving mRight the left branch of a node * @return CNodeO */ CNodeO & CNodeO::getRight() const { if (!mRight) fatalError(); // Call RightIsValid first to avoid this! return *mRight; } /** * Setting mLeft the pointer to the left branch * @param CNodeO &left */ void CNodeO::setLeft(CNodeO & left) { mLeft = &left; } /** * Setting mLeft the pointer to the left branch * @param CNodeO *pleft */ void CNodeO::setLeft(CNodeO * pleft) { mLeft = pleft; } /** * Setting mRight the pointer to the right branch * @param CNodeO &right */ void CNodeO::setRight(CNodeO & right) { mRight = &right; } /** * Setting mRight the pointer to the right branch * @param CNodeO *pright */ void CNodeO::setRight(CNodeO * pright) { mRight = pright; } /** * Return Datum in each node */ CDatum * CNodeO::getDatum() { return mDatum; } C_INT16 CNodeO::isLeftValid() const {return (C_INT16) mLeft;} C_INT16 CNodeO::isRightValid() const {return (C_INT16) mRight;}
Update calculation of node's value
Update calculation of node's value
C++
artistic-2.0
jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI
53cd0d6d5e721683c69ba5bf7adddeb65e8aae0c
tests/src/vec/tests_MartVec.cpp
tests/src/vec/tests_MartVec.cpp
#include <mart-common/MartVec.h> #include <catch2/catch.hpp> #include <iostream> #include <type_traits> template<class T, int N> std::ostream& operator<<( std::ostream& out, mart::Vec<T, N> vec ) { out << "["; for( int i = 0; i < N; ++i ) { out << vec[i] << ", "; } out << "]"; return out; } namespace { struct Wrapper { int v; friend Wrapper operator*( Wrapper l, int r ) { return {l.v * r}; } friend Wrapper operator*( int l, Wrapper r ) { return {l * r.v}; } friend Wrapper operator*( Wrapper l, Wrapper r ) { return {l.v * r.v}; } friend bool operator==( Wrapper l, Wrapper r ) { return l.v == r.v; } }; } TEST_CASE( "MartVec_some_random_vector_math_code", "[vec]" ) { const mart::Vec3D<Wrapper> expected{{1}, {2}, {-2}}; const mart::Vec3D<Wrapper> base{{1}, {1}, {2}}; const auto r = base * mart::Vec3D<int>{1, 2, -1}; static_assert( std::is_same_v<decltype( expected ), decltype( r )> ); CHECK( expected == r ); } namespace { template<class T, int N> mart::Vec<T, N> generateOnes() { mart::Vec<T, N> v{}; for( int i = 0; i < N; ++i ) { v[i] = 1; } return v; } template<class T, int N> mart::Vec<T, N> generate1() { mart::Vec<T, N> vec{}; T v{-N / 2}; for( int i = 0; i < N; ++i ) { vec[i] = v; v = v + T{1}; } return vec; } template<class T, int N> mart::Vec<T, N> generate2() { mart::Vec<T, N> vec{}; T v{0}; for( int i = 0; i < N; ++i ) { vec[i] = v; v = v + T{1}; } return vec; } template<class T, int N> mart::Vec<T, N> generate3() { mart::Vec<T, N> vec{}; T v{0}; for( int i = 0; i < N; ++i ) { vec[i] = v; v = v * 2; } return vec; } template<class T, int N> void check_addition_subtraction() { auto v1 = generate1<T, N>(); auto v2 = generate2<T, N>(); auto v3 = v1 + v2; CHECK( v1 == v3 - v2 ); } template<class T, int N> void check_multiplication_division() { auto v1 = generate1<T, N>(); auto v2 = generate1<T, N>() * generate1<T, N>() + generateOnes<T, N>(); auto v3 = v1 * v2; CHECK( v1 == v3 / v2 ); } } TEST_CASE( "MartVec_same_type_2d_operations", "[vec]" ) { check_addition_subtraction<int, 1>(); check_addition_subtraction<int, 2>(); check_addition_subtraction<int, 3>(); check_addition_subtraction<int, 4>(); check_addition_subtraction<int, 5>(); check_addition_subtraction<int, 6>(); check_addition_subtraction<int, 7>(); } TEST_CASE( "MartVec_same_type_3d_operations", "[vec]" ) { check_multiplication_division<int, 1>(); check_multiplication_division<int, 2>(); check_multiplication_division<int, 3>(); check_multiplication_division<int, 4>(); check_multiplication_division<int, 5>(); check_multiplication_division<int, 6>(); check_multiplication_division<int, 7>(); } TEST_CASE( "MartVec_element_comparison", "[vec]" ) { using Vec_t = mart::Vec<int, 5>; Vec_t vec1{1, 2, 3, 4, 5}; Vec_t vec2{2, 2, 2, 2, 2}; using BVec_t = mart::Vec<bool, 5>; CHECK( mart::elementLess( vec1, vec2 ) == BVec_t{true, false, false, false, false} ); CHECK( mart::elementLessEqual( vec1, vec2 ) == BVec_t{true, true, false, false, false} ); CHECK( mart::elementGreater( vec1, vec2 ) == BVec_t{false, false, true, true, true} ); CHECK( mart::elementGreaterEqual( vec1, vec2 ) == BVec_t{false, true, true, true, true} ); CHECK( mart::elementNE( vec1, vec2 ) == BVec_t{true, false, true, true, true} ); CHECK( mart::elementEquals( vec1, vec2 ) == BVec_t{false, true, false, false, false} ); } TEST_CASE( "MartVec_element_logic", "[vec]" ) { using BVec_t = mart::Vec<bool, 5>; BVec_t vec1{true, false, true, false, true}; BVec_t vec2{true, true, false, false, false}; CHECK( mart::elementAnd( vec1, vec2 ) == BVec_t{true, false, false, false, false} ); CHECK( mart::elementOr( vec1, vec2 ) == BVec_t{true, true, true, false, true} ); } TEST_CASE( "MartVec_element_min_max", "[vec]" ) { using Vec_t = mart::Vec<int, 5>; Vec_t vec1{1, 4, -2, 3, -10}; Vec_t vec2{2, -4, -2, 3, 5}; CHECK( mart::max( vec1, vec2 ) == Vec_t{2, 4, -2, 3, 5} ); CHECK( mart::min( vec1, vec2 ) == Vec_t{1, -4, -2, 3, -10} ); } TEST_CASE( "MartVec_decimal_to_integral", "[vec]" ) { using DVec_t = mart::Vec<double, 5>; using IVec_t = mart::Vec<int, 5>; DVec_t vec1{2.3, 2.7, 0.0, -2.3, -2.7}; // BVec_t vec2{ true, true, false, false, false }; CHECK( mart::ceil( vec1 ) == DVec_t{3, 3, 0, -2, -2} ); CHECK( mart::floor( vec1 ) == DVec_t{2, 2, 0, -3, -3} ); CHECK( mart::round( vec1 ) == DVec_t{2, 3, 0, -2, -3} ); CHECK( mart::iround( vec1 ) == IVec_t{2, 3, 0, -2, -3} ); CHECK( mart::lround( vec1 ) == mart::Vec<long, 5>{2, 3, 0, -2, -3} ); // CHECK(mart::lround(vec1) == IVec_t{ 2, 3, 0, -2, -3 }); }
#include <mart-common/MartVec.h> #include <catch2/catch.hpp> #include <iostream> #include <type_traits> template<class T, int N> std::ostream& operator<<( std::ostream& out, mart::Vec<T, N> vec ) { out << "["; for( int i = 0; i < N; ++i ) { out << vec[i] << ", "; } out << "]"; return out; } namespace { struct Wrapper { int v; friend Wrapper operator*( Wrapper l, int r ) { return {l.v * r}; } friend Wrapper operator*( int l, Wrapper r ) { return {l * r.v}; } friend Wrapper operator*( Wrapper l, Wrapper r ) { return {l.v * r.v}; } friend bool operator==( Wrapper l, Wrapper r ) { return l.v == r.v; } }; } TEST_CASE( "MartVec_some_random_vector_math_code", "[vec]" ) { const mart::Vec3D<Wrapper> expected{{1}, {2}, {-2}}; const mart::Vec3D<Wrapper> base{{1}, {1}, {2}}; const auto r = base * mart::Vec3D<int>{1, 2, -1}; static_assert( std::is_same_v<decltype( expected ), decltype( r )> ); CHECK( expected == r ); } namespace { #ifdef _MSC_VER #define CONSTEXPR_ON_PROPER_COMPILER // workaround for MSVC ICE #else #define CONSTEXPR_ON_PROPER_COMPILER constexpr #endif template<class T, int N> constexpr mart::Vec<T, N> generateOnes() { mart::Vec<T, N> v{}; for( int i = 0; i < N; ++i ) { v[i] = 1; } return v; } template<class T, int N> constexpr mart::Vec<T, N> generate1() { mart::Vec<T, N> vec{}; T v{-N / 2}; for( int i = 0; i < N; ++i ) { vec[i] = v; v = v + T{1}; } return vec; } template<class T, int N> constexpr mart::Vec<T, N> generate2() { mart::Vec<T, N> vec{}; T v{0}; for( int i = 0; i < N; ++i ) { vec[i] = v; v = v + T{1}; } return vec; } template<class T, int N> constexpr mart::Vec<T, N> generate3() { mart::Vec<T, N> vec{}; T v{0}; for( int i = 0; i < N; ++i ) { vec[i] = v; v = v * 2; } return vec; } template<class T, int N> void check_addition_subtraction() { CONSTEXPR_ON_PROPER_COMPILER auto v1 = generate1<T, N>(); CONSTEXPR_ON_PROPER_COMPILER auto v2 = generate2<T, N>(); CONSTEXPR_ON_PROPER_COMPILER auto v3 = v1 + v2; CHECK( v1 == v3 - v2 ); #ifndef _MSC_VER //MSVC generates ICE static_assert(v1 == v3 - v2); #endif } template<class T, int N> void check_multiplication_division() { CONSTEXPR_ON_PROPER_COMPILER auto v1 = generate1<T, N>(); CONSTEXPR_ON_PROPER_COMPILER auto v2 = generate1<T, N>() * generate1<T, N>() + generateOnes<T, N>(); CONSTEXPR_ON_PROPER_COMPILER auto v3 = v1 * v2; CHECK( v1 == v3 / v2 ); #ifndef _MSC_VER static_assert(v1 == v3 / v2); #endif } } TEST_CASE( "MartVec_same_type_2d_operations", "[vec]" ) { check_addition_subtraction<int, 1>(); check_addition_subtraction<int, 2>(); check_addition_subtraction<int, 3>(); check_addition_subtraction<int, 4>(); check_addition_subtraction<int, 5>(); check_addition_subtraction<int, 6>(); check_addition_subtraction<int, 7>(); } TEST_CASE( "MartVec_same_type_3d_operations", "[vec]" ) { check_multiplication_division<int, 1>(); check_multiplication_division<int, 2>(); check_multiplication_division<int, 3>(); check_multiplication_division<int, 4>(); check_multiplication_division<int, 5>(); check_multiplication_division<int, 6>(); check_multiplication_division<int, 7>(); } TEST_CASE( "MartVec_element_comparison", "[vec]" ) { using Vec_t = mart::Vec<int, 5>; constexpr Vec_t vec1{1, 2, 3, 4, 5}; constexpr Vec_t vec2{2, 2, 2, 2, 2}; using BVec_t = mart::Vec<bool, 5>; CHECK( mart::elementLess( vec1, vec2 ) == BVec_t{true, false, false, false, false} ); CHECK( mart::elementLessEqual( vec1, vec2 ) == BVec_t{true, true, false, false, false} ); CHECK( mart::elementGreater( vec1, vec2 ) == BVec_t{false, false, true, true, true} ); CHECK( mart::elementGreaterEqual( vec1, vec2 ) == BVec_t{false, true, true, true, true} ); CHECK( mart::elementNE( vec1, vec2 ) == BVec_t{true, false, true, true, true} ); CHECK( mart::elementEquals( vec1, vec2 ) == BVec_t{false, true, false, false, false} ); static_assert(mart::elementLess(vec1, vec2) == BVec_t{ true, false, false, false, false }); static_assert(mart::elementLessEqual(vec1, vec2) == BVec_t{ true, true, false, false, false }); static_assert(mart::elementGreater(vec1, vec2) == BVec_t{ false, false, true, true, true }); static_assert(mart::elementGreaterEqual(vec1, vec2) == BVec_t{ false, true, true, true, true }); static_assert(mart::elementNE(vec1, vec2) == BVec_t{ true, false, true, true, true }); static_assert(mart::elementEquals(vec1, vec2) == BVec_t{ false, true, false, false, false }); } TEST_CASE( "MartVec_element_logic", "[vec]" ) { using BVec_t = mart::Vec<bool, 5>; constexpr BVec_t vec1{true, false, true, false, true}; constexpr BVec_t vec2{true, true, false, false, false}; CHECK( mart::elementAnd( vec1, vec2 ) == BVec_t{true, false, false, false, false} ); CHECK( mart::elementOr( vec1, vec2 ) == BVec_t{true, true, true, false, true} ); static_assert(mart::elementAnd(vec1, vec2) == BVec_t{ true, false, false, false, false }); static_assert(mart::elementOr(vec1, vec2) == BVec_t{ true, true, true, false, true }); } TEST_CASE( "MartVec_element_min_max", "[vec]" ) { using Vec_t = mart::Vec<int, 5>; constexpr Vec_t vec1{1, 4, -2, 3, -10}; constexpr Vec_t vec2{2, -4, -2, 3, 5}; CHECK( mart::max( vec1, vec2 ) == Vec_t{2, 4, -2, 3, 5} ); CHECK( mart::min( vec1, vec2 ) == Vec_t{1, -4, -2, 3, -10} ); static_assert(mart::max(vec1, vec2) == Vec_t{ 2, 4, -2, 3, 5 }); static_assert(mart::min(vec1, vec2) == Vec_t{ 1, -4, -2, 3, -10 }); } TEST_CASE( "MartVec_decimal_to_integral", "[vec]" ) { using DVec_t = mart::Vec<double, 5>; using IVec_t = mart::Vec<int, 5>; DVec_t vec1{2.3, 2.7, 0.0, -2.3, -2.7}; // BVec_t vec2{ true, true, false, false, false }; CHECK( mart::ceil( vec1 ) == DVec_t{3, 3, 0, -2, -2} ); CHECK( mart::floor( vec1 ) == DVec_t{2, 2, 0, -3, -3} ); CHECK( mart::round( vec1 ) == DVec_t{2, 3, 0, -2, -3} ); CHECK( mart::iround( vec1 ) == IVec_t{2, 3, 0, -2, -3} ); CHECK( mart::lround( vec1 ) == mart::Vec<long, 5>{2, 3, 0, -2, -3} ); // CHECK(mart::lround(vec1) == IVec_t{ 2, 3, 0, -2, -3 }); } TEST_CASE( "MartVec_equal_unequal", "[vec]" ) { using Vec_t = mart::Vec<int, 5>; constexpr Vec_t v1{1, 2, 3, 4, -5}; constexpr Vec_t v2{1, 2, 3, 4, -5}; constexpr Vec_t v3{1, 2, 3, 4, 5}; CHECK( v1 == v2 ); CHECK( v1 != v3 ); CHECK( v2 == v1 ); CHECK( v2 != v3 ); CHECK( v3 != v1 ); CHECK( v3 != v2 ); static_assert(v1 == v2); static_assert(v1 != v3); static_assert(v2 == v1); static_assert(v2 != v3); static_assert(v3 != v1); static_assert(v3 != v2); }
Add constexpr checks for mart:Vec
[Tests/Vec] Add constexpr checks for mart:Vec
C++
mit
tum-ei-rcs/mart-common,tum-ei-rcs/mart-common
d8418ca0c60a21c8145ee1a60bc6f4910944ee3f
src/modules/LCIOWriter/LCIOWriterModule.cpp
src/modules/LCIOWriter/LCIOWriterModule.cpp
/** * @file * @brief Implementation of [LCIOWriter] module * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "LCIOWriterModule.hpp" #include <fstream> #include <string> #include <utility> #include <vector> #include "core/messenger/Messenger.hpp" #include "core/utils/file.h" #include "core/utils/log.h" #include <Math/RotationZYX.h> #include <IMPL/LCCollectionVec.h> #include <IMPL/LCEventImpl.h> #include <IMPL/LCRunHeaderImpl.h> #include <IMPL/TrackerDataImpl.h> #include <IO/LCWriter.h> #include <IOIMPL/LCFactory.h> #include <UTIL/CellIDEncoder.h> #include <lcio.h> using namespace allpix; using namespace lcio; LCIOWriterModule::LCIOWriterModule(Configuration config, Messenger* messenger, GeometryManager* geo) : Module(std::move(config)), geo_mgr_(geo) { // Bind pixel hits message messenger->bindMulti(this, &LCIOWriterModule::pixel_messages_, MsgFlags::REQUIRED); // get all detector names and assign id. auto detectors = geo_mgr_->getDetectors(); unsigned int i = 0; for(const auto& det : detectors) { detectorIDs_[det->getName()] = i; LOG(DEBUG) << det->getName() << " has ID " << detectorIDs_[det->getName()]; i++; } // Set configuration defaults: config_.setDefault("file_name", "output.slcio"); config_.setDefault("geometry_file", "allpix_squared_gear.xml"); config_.setDefault("pixel_type", 2); config_.setDefault("detector_name", "EUTelescope"); config_.setDefault("output_collection_name", "zsdata_m26"); pixelType_ = config_.get<int>("pixel_type"); DetectorName_ = config_.get<std::string>("detector_name"); OutputCollectionName_ = config_.get<std::string>("output_collection_name"); } void LCIOWriterModule::init() { // Create the output GEAR file for the detector geometry geometry_file_name_ = createOutputFile(allpix::add_file_extension(config_.get<std::string>("geometry_file"), "xml"), true); // Open LCIO file and write run header lcio_file_name_ = createOutputFile(allpix::add_file_extension(config_.get<std::string>("file_name"), "slcio")); lcWriter_ = std::shared_ptr<IO::LCWriter>(LCFactory::getInstance()->createLCWriter()); lcWriter_->open(lcio_file_name_, LCIO::WRITE_NEW); auto run = std::make_unique<LCRunHeaderImpl>(); run->setRunNumber(1); run->setDetectorName(DetectorName_); lcWriter_->writeRunHeader(run.get()); } void LCIOWriterModule::run(unsigned int eventNb) { auto evt = std::make_unique<LCEventImpl>(); // create the event evt->setRunNumber(1); evt->setEventNumber(static_cast<int>(eventNb)); // set the event attributes evt->parameters().setValue("EventType", 2); // Prepare charge vectors std::vector<std::vector<float>> charges; for(unsigned int i = 0; i < detectorIDs_.size(); i++) { std::vector<float> charge; charges.push_back(charge); } // Receive all pixel messages, fill charge vectors for(const auto& hit_msg : pixel_messages_) { LOG(DEBUG) << hit_msg->getDetector()->getName(); for(const auto& hitdata : hit_msg->getData()) { LOG(DEBUG) << "X: " << hitdata.getPixel().getIndex().x() << ", Y:" << hitdata.getPixel().getIndex().y() << ", Signal: " << hitdata.getSignal(); unsigned int detectorID = detectorIDs_[hit_msg->getDetector()->getName()]; switch(pixelType_) { case 1: // EUTelSimpleSparsePixel charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().x())); // x charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().y())); // y charges[detectorID].push_back(static_cast<float>(hitdata.getSignal())); // signal break; case 2: // EUTelGenericSparsePixel default: // EUTelGenericSparsePixel is default charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().x())); // x charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().y())); // y charges[detectorID].push_back(static_cast<float>(hitdata.getSignal())); // signal charges[detectorID].push_back(static_cast<float>(0)); // time break; case 5: // EUTelTimepix3SparsePixel charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().x())); // x charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().y())); // y charges[detectorID].push_back(static_cast<float>(hitdata.getSignal())); // signal charges[detectorID].push_back(static_cast<float>(0)); // time charges[detectorID].push_back(static_cast<float>(0)); // time charges[detectorID].push_back(static_cast<float>(0)); // time charges[detectorID].push_back(static_cast<float>(0)); // time break; } } } // Prepare hitvector LCCollectionVec* hitVec = new LCCollectionVec(LCIO::TRACKERDATA); // Fill hitvector with event data for(unsigned int detectorID = 0; detectorID < detectorIDs_.size(); detectorID++) { auto hit = new TrackerDataImpl(); CellIDEncoder<TrackerDataImpl> sparseDataEncoder("sensorID:7,sparsePixelType:5", hitVec); sparseDataEncoder["sensorID"] = detectorID; sparseDataEncoder["sparsePixelType"] = pixelType_; sparseDataEncoder.setCellID(hit); hit->setChargeValues(charges[detectorID]); hitVec->push_back(hit); } // Add collection to event and write event to LCIO file evt->addCollection(hitVec, OutputCollectionName_); // add the collection with a name lcWriter_->writeEvent(evt.get()); // write the event to the file write_cnt_++; } void LCIOWriterModule::finalize() { lcWriter_->close(); // Print statistics LOG(STATUS) << "Wrote " << write_cnt_ << " events to file:" << std::endl << lcio_file_name_; // Write geometry: std::ofstream geometry_file; if(!geometry_file_name_.empty()) { geometry_file.open(geometry_file_name_, std::ios_base::out | std::ios_base::trunc); if(!geometry_file.good()) { throw ModuleError("Cannot write to GEAR geometry file"); } auto detectors = geo_mgr_->getDetectors(); geometry_file << "<?xml version=\"1.0\" encoding=\"utf-8\"?>" << std::endl << "<!-- ?xml-stylesheet type=\"text/xsl\" href=\"https://cern.ch/allpix-squared/\"? -->" << std::endl << "<gear>" << std::endl; geometry_file << " <global detectorName=\"" << DetectorName_ << "\"/>" << std::endl; geometry_file << " <detectors>" << std::endl; geometry_file << " <detector name=\"SiPlanes\" geartype=\"SiPlanesParameters\">" << std::endl; geometry_file << " <siplanesType type=\"TelescopeWithoutDUT\"/>" << std::endl; geometry_file << " <siplanesNumber number=\"" << detectors.size() << "\"/>" << std::endl; geometry_file << " <siplanesID ID=\"" << 0 << "\"/>" << std::endl; geometry_file << " <layers>" << std::endl; for(auto& detector : detectors) { // Write header for the layer: geometry_file << " <!-- Allpix Squared Detector: " << detector->getName() << " - type: " << detector->getType() << " -->" << std::endl; geometry_file << " <layer>" << std::endl; auto position = detector->getPosition(); auto model = detector->getModel(); auto npixels = model->getNPixels(); auto pitch = model->getPixelSize(); auto total_size = model->getSize(); auto sensitive_size = model->getSensorSize(); // Write ladder geometry_file << " <ladder ID=\"" << detectorIDs_[detector->getName()] << "\"" << std::endl; geometry_file << " positionX=\"" << Units::convert(position.x(), "mm") << "\"\tpositionY=\"" << Units::convert(position.y(), "mm") << "\"\tpositionZ=\"" << Units::convert(position.z(), "mm") << "\"" << std::endl; ROOT::Math::RotationZYX rotations(detector->getOrientation().Inverse()); geometry_file << " rotationZY=\"" << Units::convert(-rotations.Psi(), "deg") << "\" rotationZX=\"" << Units::convert(-rotations.Theta(), "deg") << "\" rotationXY=\"" << Units::convert(-rotations.Phi(), "deg") << "\"" << std::endl; geometry_file << " sizeX=\"" << Units::convert(total_size.x(), "mm") << "\"\tsizeY=\"" << Units::convert(total_size.y(), "mm") << "\"\tthickness=\"" << Units::convert(total_size.z(), "mm") << "\"" << std::endl; geometry_file << " radLength=\"93.65\"" << std::endl; geometry_file << " />" << std::endl; // Write sensitive geometry_file << " <sensitive ID=\"" << detectorIDs_[detector->getName()] << "\"" << std::endl; geometry_file << " positionX=\"" << Units::convert(position.x(), "mm") << "\"\tpositionY=\"" << Units::convert(position.y(), "mm") << "\"\tpositionZ=\"" << Units::convert(position.z(), "mm") << "\"" << std::endl; geometry_file << " sizeX=\"" << Units::convert(npixels.x() * pitch.x(), "mm") << "\"\tsizeY=\"" << Units::convert(npixels.y() * pitch.y(), "mm") << "\"\tthickness=\"" << Units::convert(sensitive_size.z(), "mm") << "\"" << std::endl; geometry_file << " npixelX=\"" << npixels.x() << "\"\tnpixelY=\"" << npixels.y() << "\"" << std::endl; geometry_file << " pitchX=\"" << Units::convert(pitch.x(), "mm") << "\"\tpitchY=\"" << Units::convert(pitch.y(), "mm") << "\"\tresolution=\"" << Units::convert(pitch.x() / std::sqrt(12), "mm") << "\"" << std::endl; geometry_file << " rotation1=\"1.0\"\trotation2=\"0.0\"" << std::endl; geometry_file << " rotation3=\"0.0\"\trotation4=\"1.0\"" << std::endl; geometry_file << " radLength=\"93.65\"" << std::endl; geometry_file << " />" << std::endl; // End the layer: geometry_file << " </layer>" << std::endl; } // Close XML tree: geometry_file << " </layers>" << std::endl << " </detector>" << std::endl << " </detectors>" << std::endl << "</gear>" << std::endl; LOG(STATUS) << "Wrote GEAR geometry to file:" << std::endl << geometry_file_name_; } }
/** * @file * @brief Implementation of [LCIOWriter] module * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "LCIOWriterModule.hpp" #include <fstream> #include <string> #include <utility> #include <vector> #include "core/messenger/Messenger.hpp" #include "core/utils/file.h" #include "core/utils/log.h" #include <Math/RotationZYX.h> #include <IMPL/LCCollectionVec.h> #include <IMPL/LCEventImpl.h> #include <IMPL/LCRunHeaderImpl.h> #include <IMPL/TrackerDataImpl.h> #include <IO/LCWriter.h> #include <IOIMPL/LCFactory.h> #include <UTIL/CellIDEncoder.h> #include <lcio.h> using namespace allpix; using namespace lcio; LCIOWriterModule::LCIOWriterModule(Configuration config, Messenger* messenger, GeometryManager* geo) : Module(std::move(config)), geo_mgr_(geo) { // Bind pixel hits message messenger->bindMulti(this, &LCIOWriterModule::pixel_messages_, MsgFlags::REQUIRED); // get all detector names and assign id. auto detectors = geo_mgr_->getDetectors(); unsigned int i = 0; for(const auto& det : detectors) { detectorIDs_[det->getName()] = i; LOG(DEBUG) << det->getName() << " has ID " << detectorIDs_[det->getName()]; i++; } // Set configuration defaults: config_.setDefault("file_name", "output.slcio"); config_.setDefault("geometry_file", "allpix_squared_gear.xml"); config_.setDefault("pixel_type", 2); config_.setDefault("detector_name", "EUTelescope"); config_.setDefault("output_collection_name", "zsdata_m26"); pixelType_ = config_.get<int>("pixel_type"); DetectorName_ = config_.get<std::string>("detector_name"); OutputCollectionName_ = config_.get<std::string>("output_collection_name"); } void LCIOWriterModule::init() { // Create the output GEAR file for the detector geometry geometry_file_name_ = createOutputFile(allpix::add_file_extension(config_.get<std::string>("geometry_file"), "xml"), true); // Open LCIO file and write run header lcio_file_name_ = createOutputFile(allpix::add_file_extension(config_.get<std::string>("file_name"), "slcio")); lcWriter_ = std::shared_ptr<IO::LCWriter>(LCFactory::getInstance()->createLCWriter()); lcWriter_->open(lcio_file_name_, LCIO::WRITE_NEW); auto run = std::make_unique<LCRunHeaderImpl>(); run->setRunNumber(1); run->setDetectorName(DetectorName_); lcWriter_->writeRunHeader(run.get()); } void LCIOWriterModule::run(unsigned int eventNb) { auto evt = std::make_unique<LCEventImpl>(); // create the event evt->setRunNumber(1); evt->setEventNumber(static_cast<int>(eventNb)); // set the event attributes evt->parameters().setValue("EventType", 2); // Prepare charge vectors std::vector<std::vector<float>> charges; for(unsigned int i = 0; i < detectorIDs_.size(); i++) { std::vector<float> charge; charges.push_back(charge); } // Receive all pixel messages, fill charge vectors for(const auto& hit_msg : pixel_messages_) { LOG(DEBUG) << hit_msg->getDetector()->getName(); for(const auto& hitdata : hit_msg->getData()) { LOG(DEBUG) << "X: " << hitdata.getPixel().getIndex().x() << ", Y:" << hitdata.getPixel().getIndex().y() << ", Signal: " << hitdata.getSignal(); unsigned int detectorID = detectorIDs_[hit_msg->getDetector()->getName()]; switch(pixelType_) { case 1: // EUTelSimpleSparsePixel charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().x())); // x charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().y())); // y charges[detectorID].push_back(static_cast<float>(hitdata.getSignal())); // signal break; case 2: // EUTelGenericSparsePixel default: // EUTelGenericSparsePixel is default charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().x())); // x charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().y())); // y charges[detectorID].push_back(static_cast<float>(hitdata.getSignal())); // signal charges[detectorID].push_back(static_cast<float>(0)); // time break; case 5: // EUTelTimepix3SparsePixel charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().x())); // x charges[detectorID].push_back(static_cast<float>(hitdata.getPixel().getIndex().y())); // y charges[detectorID].push_back(static_cast<float>(hitdata.getSignal())); // signal charges[detectorID].push_back(static_cast<float>(0)); // time charges[detectorID].push_back(static_cast<float>(0)); // time charges[detectorID].push_back(static_cast<float>(0)); // time charges[detectorID].push_back(static_cast<float>(0)); // time break; } } } // Prepare hitvector LCCollectionVec* hitVec = new LCCollectionVec(LCIO::TRACKERDATA); // Fill hitvector with event data for(unsigned int detectorID = 0; detectorID < detectorIDs_.size(); detectorID++) { auto hit = new TrackerDataImpl(); CellIDEncoder<TrackerDataImpl> sparseDataEncoder("sensorID:7,sparsePixelType:5", hitVec); sparseDataEncoder["sensorID"] = detectorID; sparseDataEncoder["sparsePixelType"] = pixelType_; sparseDataEncoder.setCellID(hit); hit->setChargeValues(charges[detectorID]); hitVec->push_back(hit); } // Add collection to event and write event to LCIO file evt->addCollection(hitVec, OutputCollectionName_); // add the collection with a name lcWriter_->writeEvent(evt.get()); // write the event to the file write_cnt_++; } void LCIOWriterModule::finalize() { lcWriter_->close(); // Print statistics LOG(STATUS) << "Wrote " << write_cnt_ << " events to file:" << std::endl << lcio_file_name_; // Write geometry: std::ofstream geometry_file; if(!geometry_file_name_.empty()) { geometry_file.open(geometry_file_name_, std::ios_base::out | std::ios_base::trunc); if(!geometry_file.good()) { throw ModuleError("Cannot write to GEAR geometry file"); } auto detectors = geo_mgr_->getDetectors(); geometry_file << "<?xml version=\"1.0\" encoding=\"utf-8\"?>" << std::endl << "<!-- ?xml-stylesheet type=\"text/xsl\" href=\"https://cern.ch/allpix-squared/\"? -->" << std::endl << "<gear>" << std::endl; geometry_file << " <global detectorName=\"" << DetectorName_ << "\"/>" << std::endl; geometry_file << " <detectors>" << std::endl; geometry_file << " <detector name=\"SiPlanes\" geartype=\"SiPlanesParameters\">" << std::endl; geometry_file << " <siplanesType type=\"TelescopeWithoutDUT\"/>" << std::endl; geometry_file << " <siplanesNumber number=\"" << detectors.size() << "\"/>" << std::endl; geometry_file << " <siplanesID ID=\"" << 0 << "\"/>" << std::endl; geometry_file << " <layers>" << std::endl; for(auto& detector : detectors) { // Write header for the layer: geometry_file << " <!-- Allpix Squared Detector: " << detector->getName() << " - type: " << detector->getType() << " -->" << std::endl; geometry_file << " <layer>" << std::endl; auto position = detector->getPosition(); auto model = detector->getModel(); auto npixels = model->getNPixels(); auto pitch = model->getPixelSize(); auto total_size = model->getSize(); auto sensitive_size = model->getSensorSize(); // Write ladder geometry_file << " <ladder ID=\"" << detectorIDs_[detector->getName()] << "\"" << std::endl; geometry_file << " positionX=\"" << Units::convert(position.x(), "mm") << "\"\tpositionY=\"" << Units::convert(position.y(), "mm") << "\"\tpositionZ=\"" << Units::convert(position.z(), "mm") << "\"" << std::endl; // Use inverse ZYX rotation to retrieve XYZ angles as used in EUTelescope: ROOT::Math::RotationZYX rotations(detector->getOrientation().Inverse()); geometry_file << " rotationZY=\"" << Units::convert(-rotations.Psi(), "deg") << "\" rotationZX=\"" << Units::convert(-rotations.Theta(), "deg") << "\" rotationXY=\"" << Units::convert(-rotations.Phi(), "deg") << "\"" << std::endl; geometry_file << " sizeX=\"" << Units::convert(total_size.x(), "mm") << "\"\tsizeY=\"" << Units::convert(total_size.y(), "mm") << "\"\tthickness=\"" << Units::convert(total_size.z(), "mm") << "\"" << std::endl; geometry_file << " radLength=\"93.65\"" << std::endl; geometry_file << " />" << std::endl; // Write sensitive geometry_file << " <sensitive ID=\"" << detectorIDs_[detector->getName()] << "\"" << std::endl; geometry_file << " positionX=\"" << Units::convert(position.x(), "mm") << "\"\tpositionY=\"" << Units::convert(position.y(), "mm") << "\"\tpositionZ=\"" << Units::convert(position.z(), "mm") << "\"" << std::endl; geometry_file << " sizeX=\"" << Units::convert(npixels.x() * pitch.x(), "mm") << "\"\tsizeY=\"" << Units::convert(npixels.y() * pitch.y(), "mm") << "\"\tthickness=\"" << Units::convert(sensitive_size.z(), "mm") << "\"" << std::endl; geometry_file << " npixelX=\"" << npixels.x() << "\"\tnpixelY=\"" << npixels.y() << "\"" << std::endl; geometry_file << " pitchX=\"" << Units::convert(pitch.x(), "mm") << "\"\tpitchY=\"" << Units::convert(pitch.y(), "mm") << "\"\tresolution=\"" << Units::convert(pitch.x() / std::sqrt(12), "mm") << "\"" << std::endl; geometry_file << " rotation1=\"1.0\"\trotation2=\"0.0\"" << std::endl; geometry_file << " rotation3=\"0.0\"\trotation4=\"1.0\"" << std::endl; geometry_file << " radLength=\"93.65\"" << std::endl; geometry_file << " />" << std::endl; // End the layer: geometry_file << " </layer>" << std::endl; } // Close XML tree: geometry_file << " </layers>" << std::endl << " </detector>" << std::endl << " </detectors>" << std::endl << "</gear>" << std::endl; LOG(STATUS) << "Wrote GEAR geometry to file:" << std::endl << geometry_file_name_; } }
add comment to angles for later reference
LCIOWriter: add comment to angles for later reference
C++
mit
Koensw/allpix-squared,Koensw/allpix-squared,Koensw/allpix-squared,Koensw/allpix-squared
373e0099cf3bcee351c3a7b0052f896034d6f295
scene/scene_string_names.cpp
scene/scene_string_names.cpp
/*************************************************************************/ /* scene_string_names.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "scene_string_names.h" SceneStringNames* SceneStringNames::singleton=NULL; SceneStringNames::SceneStringNames() { resized=StaticCString::create("resized"); dot=StaticCString::create("."); doubledot=StaticCString::create(".."); draw=StaticCString::create("draw"); _draw=StaticCString::create("_draw"); hide=StaticCString::create("hide"); visibility_changed=StaticCString::create("visibility_changed"); input_event=StaticCString::create("input_event"); shader_shader=StaticCString::create("shader/shader"); shader_unshaded=StaticCString::create("shader/unshaded"); shading_mode=StaticCString::create("shader/shading_mode"); tree_entered=StaticCString::create("tree_entered"); tree_exited=StaticCString::create("tree_exited"); item_rect_changed=StaticCString::create("item_rect_changed"); size_flags_changed=StaticCString::create("size_flags_changed"); minimum_size_changed=StaticCString::create("minimum_size_changed"); sleeping_state_changed=StaticCString::create("sleeping_state_changed"); finished=StaticCString::create("finished"); animation_finished=StaticCString::create("animation_finished"); animation_changed=StaticCString::create("animation_changed"); animation_started=StaticCString::create("animation_started"); mouse_entered=StaticCString::create("mouse_entered"); mouse_exited=StaticCString::create("mouse_exited"); focus_entered=StaticCString::create("focus_entered"); focus_exited=StaticCString::create("focus_exited"); sort_children = StaticCString::create("sort_children"); body_shape_entered = StaticCString::create("body_shape_entered"); body_entered = StaticCString::create("body_entered"); body_shape_exited = StaticCString::create("body_shape_exited"); body_exited = StaticCString::create("body_exited"); area_shape_entered = StaticCString::create("area_shape_entered"); area_shape_exited = StaticCString::create("area_shape_exited"); _body_inout = StaticCString::create("_body_inout"); _area_inout = StaticCString::create("_area_inout"); idle=StaticCString::create("idle"); iteration=StaticCString::create("iteration"); update=StaticCString::create("update"); updated=StaticCString::create("updated"); _get_gizmo_geometry=StaticCString::create("_get_gizmo_geometry"); _can_gizmo_scale=StaticCString::create("_can_gizmo_scale"); _fixed_process=StaticCString::create("_fixed_process"); _process=StaticCString::create("_process"); _enter_tree=StaticCString::create("_enter_tree"); _exit_tree=StaticCString::create("_exit_tree"); _enter_world=StaticCString::create("_enter_world"); _exit_world=StaticCString::create("_exit_world"); _ready=StaticCString::create("_ready"); _update_scroll=StaticCString::create("_update_scroll"); _update_xform=StaticCString::create("_update_xform"); _proxgroup_add=StaticCString::create("_proxgroup_add"); _proxgroup_remove=StaticCString::create("_proxgroup_remove"); grouped=StaticCString::create("grouped"); ungrouped=StaticCString::create("ungrouped"); screen_entered=StaticCString::create("screen_entered"); screen_exited=StaticCString::create("screen_exited"); viewport_entered=StaticCString::create("viewport_entered"); viewport_exited=StaticCString::create("viewport_exited"); camera_entered=StaticCString::create("camera_entered"); camera_exited=StaticCString::create("camera_exited"); _body_enter_tree = StaticCString::create("_body_enter_tree"); _body_exit_tree = StaticCString::create("_body_exit_tree"); _area_enter_tree = StaticCString::create("_area_enter_tree"); _area_exit_tree = StaticCString::create("_area_exit_tree"); _input_event=StaticCString::create("_input_event"); gui_input=StaticCString::create("gui_input"); _gui_input=StaticCString::create("_gui_input"); _unhandled_input=StaticCString::create("_unhandled_input"); _unhandled_key_input=StaticCString::create("_unhandled_key_input"); changed=StaticCString::create("changed"); _shader_changed=StaticCString::create("_shader_changed"); _spatial_editor_group=StaticCString::create("_spatial_editor_group"); _request_gizmo=StaticCString::create("_request_gizmo"); offset=StaticCString::create("offset"); unit_offset=StaticCString::create("unit_offset"); rotation_mode=StaticCString::create("rotation_mode"); rotate=StaticCString::create("rotate"); h_offset=StaticCString::create("h_offset"); v_offset=StaticCString::create("v_offset"); transform_pos=StaticCString::create("transform/pos"); transform_rot=StaticCString::create("transform/rot"); transform_scale=StaticCString::create("transform/scale"); _update_remote=StaticCString::create("_update_remote"); _update_pairs=StaticCString::create("_update_pairs"); get_minimum_size=StaticCString::create("get_minimum_size"); area_entered=StaticCString::create("area_entered"); area_exited=StaticCString::create("area_exited"); has_point = StaticCString::create("has_point"); line_separation = StaticCString::create("line_separation"); play_play = StaticCString::create("play/play"); get_drag_data = StaticCString::create("get_drag_data"); drop_data = StaticCString::create("drop_data"); can_drop_data = StaticCString::create("can_drop_data"); _im_update = StaticCString::create("_im_update"); _queue_update = StaticCString::create("_queue_update"); baked_light_changed = StaticCString::create("baked_light_changed"); _baked_light_changed = StaticCString::create("_baked_light_changed"); _mouse_enter=StaticCString::create("_mouse_enter"); _mouse_exit=StaticCString::create("_mouse_exit"); _pressed=StaticCString::create("_pressed"); _toggled=StaticCString::create("_toggled"); frame_changed=StaticCString::create("frame_changed"); playback_speed=StaticCString::create("playback/speed"); playback_active=StaticCString::create("playback/active"); autoplay=StaticCString::create("autoplay"); blend_times=StaticCString::create("blend_times"); speed=StaticCString::create("speed"); node_configuration_warning_changed = StaticCString::create("node_configuration_warning_changed"); path_pp=NodePath(".."); _default=StaticCString::create("default"); for(int i=0;i<MAX_MATERIALS;i++) { mesh_materials[i]="material/"+itos(i); } _mesh_changed=StaticCString::create("_mesh_changed"); }
/*************************************************************************/ /* scene_string_names.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "scene_string_names.h" SceneStringNames* SceneStringNames::singleton=NULL; SceneStringNames::SceneStringNames() { resized=StaticCString::create("resized"); dot=StaticCString::create("."); doubledot=StaticCString::create(".."); draw=StaticCString::create("draw"); _draw=StaticCString::create("_draw"); hide=StaticCString::create("hide"); visibility_changed=StaticCString::create("visibility_changed"); input_event=StaticCString::create("input_event"); shader_shader=StaticCString::create("shader/shader"); shader_unshaded=StaticCString::create("shader/unshaded"); shading_mode=StaticCString::create("shader/shading_mode"); tree_entered=StaticCString::create("tree_entered"); tree_exited=StaticCString::create("tree_exited"); item_rect_changed=StaticCString::create("item_rect_changed"); size_flags_changed=StaticCString::create("size_flags_changed"); minimum_size_changed=StaticCString::create("minimum_size_changed"); sleeping_state_changed=StaticCString::create("sleeping_state_changed"); finished=StaticCString::create("finished"); animation_finished=StaticCString::create("animation_finished"); animation_changed=StaticCString::create("animation_changed"); animation_started=StaticCString::create("animation_started"); mouse_entered=StaticCString::create("mouse_entered"); mouse_exited=StaticCString::create("mouse_exited"); focus_entered=StaticCString::create("focus_entered"); focus_exited=StaticCString::create("focus_exited"); sort_children = StaticCString::create("sort_children"); body_shape_entered = StaticCString::create("body_shape_entered"); body_entered = StaticCString::create("body_entered"); body_shape_exited = StaticCString::create("body_shape_exited"); body_exited = StaticCString::create("body_exited"); area_shape_entered = StaticCString::create("area_shape_entered"); area_shape_exited = StaticCString::create("area_shape_exited"); _body_inout = StaticCString::create("_body_inout"); _area_inout = StaticCString::create("_area_inout"); idle=StaticCString::create("idle"); iteration=StaticCString::create("iteration"); update=StaticCString::create("update"); updated=StaticCString::create("updated"); _get_gizmo_geometry=StaticCString::create("_get_gizmo_geometry"); _can_gizmo_scale=StaticCString::create("_can_gizmo_scale"); _fixed_process=StaticCString::create("_fixed_process"); _process=StaticCString::create("_process"); _enter_tree=StaticCString::create("_enter_tree"); _exit_tree=StaticCString::create("_exit_tree"); _enter_world=StaticCString::create("_enter_world"); _exit_world=StaticCString::create("_exit_world"); _ready=StaticCString::create("_ready"); _update_scroll=StaticCString::create("_update_scroll"); _update_xform=StaticCString::create("_update_xform"); _proxgroup_add=StaticCString::create("_proxgroup_add"); _proxgroup_remove=StaticCString::create("_proxgroup_remove"); grouped=StaticCString::create("grouped"); ungrouped=StaticCString::create("ungrouped"); screen_entered=StaticCString::create("screen_entered"); screen_exited=StaticCString::create("screen_exited"); viewport_entered=StaticCString::create("viewport_entered"); viewport_exited=StaticCString::create("viewport_exited"); camera_entered=StaticCString::create("camera_entered"); camera_exited=StaticCString::create("camera_exited"); _body_enter_tree = StaticCString::create("_body_enter_tree"); _body_exit_tree = StaticCString::create("_body_exit_tree"); _area_enter_tree = StaticCString::create("_area_enter_tree"); _area_exit_tree = StaticCString::create("_area_exit_tree"); _input = StaticCString::create("_input"); _input_event=StaticCString::create("_input_event"); gui_input=StaticCString::create("gui_input"); _gui_input=StaticCString::create("_gui_input"); _unhandled_input=StaticCString::create("_unhandled_input"); _unhandled_key_input=StaticCString::create("_unhandled_key_input"); changed=StaticCString::create("changed"); _shader_changed=StaticCString::create("_shader_changed"); _spatial_editor_group=StaticCString::create("_spatial_editor_group"); _request_gizmo=StaticCString::create("_request_gizmo"); offset=StaticCString::create("offset"); unit_offset=StaticCString::create("unit_offset"); rotation_mode=StaticCString::create("rotation_mode"); rotate=StaticCString::create("rotate"); h_offset=StaticCString::create("h_offset"); v_offset=StaticCString::create("v_offset"); transform_pos=StaticCString::create("transform/pos"); transform_rot=StaticCString::create("transform/rot"); transform_scale=StaticCString::create("transform/scale"); _update_remote=StaticCString::create("_update_remote"); _update_pairs=StaticCString::create("_update_pairs"); get_minimum_size=StaticCString::create("get_minimum_size"); area_entered=StaticCString::create("area_entered"); area_exited=StaticCString::create("area_exited"); has_point = StaticCString::create("has_point"); line_separation = StaticCString::create("line_separation"); play_play = StaticCString::create("play/play"); get_drag_data = StaticCString::create("get_drag_data"); drop_data = StaticCString::create("drop_data"); can_drop_data = StaticCString::create("can_drop_data"); _im_update = StaticCString::create("_im_update"); _queue_update = StaticCString::create("_queue_update"); baked_light_changed = StaticCString::create("baked_light_changed"); _baked_light_changed = StaticCString::create("_baked_light_changed"); _mouse_enter=StaticCString::create("_mouse_enter"); _mouse_exit=StaticCString::create("_mouse_exit"); _pressed=StaticCString::create("_pressed"); _toggled=StaticCString::create("_toggled"); frame_changed=StaticCString::create("frame_changed"); playback_speed=StaticCString::create("playback/speed"); playback_active=StaticCString::create("playback/active"); autoplay=StaticCString::create("autoplay"); blend_times=StaticCString::create("blend_times"); speed=StaticCString::create("speed"); node_configuration_warning_changed = StaticCString::create("node_configuration_warning_changed"); path_pp=NodePath(".."); _default=StaticCString::create("default"); for(int i=0;i<MAX_MATERIALS;i++) { mesh_materials[i]="material/"+itos(i); } _mesh_changed=StaticCString::create("_mesh_changed"); }
Fix auto-enable of _input processing when _input() method is set.
Fix auto-enable of _input processing when _input() method is set. Since f3f4a11c processing of callbacks such as `_process`, `_fixed_process`, etc will be automatically enabled when the corresponding method is found in the script. However, for _input() this wasn't working. That's simply because `_input` wasn't initialized in `SceneStringNames` ^^
C++
mit
pkowal1982/godot,okamstudio/godot,guilhermefelipecgs/godot,groud/godot,exabon/godot,ficoos/godot,Paulloz/godot,Valentactive/godot,NateWardawg/godot,vnen/godot,Max-Might/godot,mcanders/godot,Marqin/godot,NateWardawg/godot,n-pigeon/godot,josempans/godot,Marqin/godot,ex/godot,honix/godot,MarianoGnu/godot,Brickcaster/godot,guilhermefelipecgs/godot,akien-mga/godot,ageazrael/godot,vnen/godot,ZuBsPaCe/godot,MrMaidx/godot,Shockblast/godot,okamstudio/godot,ageazrael/godot,Faless/godot,FateAce/godot,ex/godot,pkowal1982/godot,Shockblast/godot,ageazrael/godot,Max-Might/godot,vnen/godot,Paulloz/godot,NateWardawg/godot,MrMaidx/godot,NateWardawg/godot,josempans/godot,akien-mga/godot,vkbsb/godot,sanikoyes/godot,ZuBsPaCe/godot,mcanders/godot,Shockblast/godot,groud/godot,MarianoGnu/godot,FateAce/godot,guilhermefelipecgs/godot,josempans/godot,vkbsb/godot,zicklag/godot,BastiaanOlij/godot,okamstudio/godot,Paulloz/godot,Shockblast/godot,jejung/godot,Max-Might/godot,BastiaanOlij/godot,mcanders/godot,ficoos/godot,groud/godot,akien-mga/godot,sanikoyes/godot,okamstudio/godot,Brickcaster/godot,Marqin/godot,Shockblast/godot,ficoos/godot,ex/godot,MrMaidx/godot,vkbsb/godot,ZuBsPaCe/godot,Shockblast/godot,BastiaanOlij/godot,RandomShaper/godot,Marqin/godot,sanikoyes/godot,godotengine/godot,ageazrael/godot,ageazrael/godot,RandomShaper/godot,n-pigeon/godot,ex/godot,MarianoGnu/godot,honix/godot,RebelliousX/Go_Dot,Faless/godot,guilhermefelipecgs/godot,firefly2442/godot,tomreyn/godot,Marqin/godot,firefly2442/godot,godotengine/godot,ZuBsPaCe/godot,godotengine/godot,vnen/godot,Brickcaster/godot,exabon/godot,jejung/godot,Zylann/godot,zicklag/godot,RebelliousX/Go_Dot,Valentactive/godot,n-pigeon/godot,Valentactive/godot,ZuBsPaCe/godot,pkowal1982/godot,tomreyn/godot,Max-Might/godot,RebelliousX/Go_Dot,DmitriySalnikov/godot,groud/godot,firefly2442/godot,mcanders/godot,honix/godot,RandomShaper/godot,Zylann/godot,NateWardawg/godot,ageazrael/godot,pkowal1982/godot,Paulloz/godot,DmitriySalnikov/godot,Brickcaster/godot,morrow1nd/godot,firefly2442/godot,Valentactive/godot,tomreyn/godot,okamstudio/godot,RandomShaper/godot,ZuBsPaCe/godot,vnen/godot,groud/godot,akien-mga/godot,NateWardawg/godot,godotengine/godot,FateAce/godot,BastiaanOlij/godot,guilhermefelipecgs/godot,ex/godot,sanikoyes/godot,n-pigeon/godot,honix/godot,Brickcaster/godot,MarianoGnu/godot,jejung/godot,BastiaanOlij/godot,Shockblast/godot,Zylann/godot,groud/godot,Zylann/godot,MarianoGnu/godot,Paulloz/godot,josempans/godot,ficoos/godot,NateWardawg/godot,Faless/godot,godotengine/godot,pkowal1982/godot,Zylann/godot,firefly2442/godot,okamstudio/godot,okamstudio/godot,DmitriySalnikov/godot,morrow1nd/godot,morrow1nd/godot,exabon/godot,zicklag/godot,vkbsb/godot,zicklag/godot,n-pigeon/godot,ex/godot,exabon/godot,FateAce/godot,honix/godot,sanikoyes/godot,Valentactive/godot,firefly2442/godot,NateWardawg/godot,MrMaidx/godot,BastiaanOlij/godot,okamstudio/godot,Max-Might/godot,MarianoGnu/godot,zicklag/godot,okamstudio/godot,akien-mga/godot,Valentactive/godot,BastiaanOlij/godot,pkowal1982/godot,MrMaidx/godot,morrow1nd/godot,BastiaanOlij/godot,Brickcaster/godot,ficoos/godot,RebelliousX/Go_Dot,okamstudio/godot,n-pigeon/godot,josempans/godot,pkowal1982/godot,Faless/godot,honix/godot,Paulloz/godot,DmitriySalnikov/godot,sanikoyes/godot,Faless/godot,Zylann/godot,Marqin/godot,morrow1nd/godot,FateAce/godot,vkbsb/godot,RebelliousX/Go_Dot,RandomShaper/godot,ageazrael/godot,akien-mga/godot,Paulloz/godot,mcanders/godot,RandomShaper/godot,guilhermefelipecgs/godot,Faless/godot,Shockblast/godot,Valentactive/godot,godotengine/godot,godotengine/godot,DmitriySalnikov/godot,tomreyn/godot,DmitriySalnikov/godot,vkbsb/godot,tomreyn/godot,firefly2442/godot,Faless/godot,MrMaidx/godot,guilhermefelipecgs/godot,vnen/godot,exabon/godot,Brickcaster/godot,exabon/godot,josempans/godot,RandomShaper/godot,jejung/godot,akien-mga/godot,ficoos/godot,Valentactive/godot,FateAce/godot,pkowal1982/godot,ZuBsPaCe/godot,jejung/godot,ex/godot,josempans/godot,morrow1nd/godot,n-pigeon/godot,sanikoyes/godot,vnen/godot,Zylann/godot,vnen/godot,jejung/godot,josempans/godot,RebelliousX/Go_Dot,vkbsb/godot,MarianoGnu/godot,firefly2442/godot,godotengine/godot,vkbsb/godot,ZuBsPaCe/godot,Faless/godot,NateWardawg/godot,MarianoGnu/godot,Max-Might/godot,Zylann/godot,zicklag/godot,akien-mga/godot,DmitriySalnikov/godot,ex/godot,guilhermefelipecgs/godot,sanikoyes/godot,mcanders/godot
a9a858c2216f637aa5132e615518bb0ed2340447
include/mos/gfx/material.hpp
include/mos/gfx/material.hpp
#pragma once #include <glm/glm.hpp> #include <string> #include <memory> #include <mos/gfx/texture_2d.hpp> namespace mos::gfx { class Assets; /** Physically based material. */ class Material final { public: template<class T> struct Slot { explicit Slot(const T &value) : value(value) {} explicit Slot(const Shared_texture_2D &texture) : texture(texture) {} Slot(const T &value, const Shared_texture_2D &texture) : value(value), texture(texture) {} T value = T(); Shared_texture_2D texture = Shared_texture_2D(); }; struct Normal { Shared_texture_2D texture; }; static auto load(Assets &assets, const std::string &path) -> Material; using Albedo = Slot<glm::vec3>; using Roughness = Slot<float>; using Metallic = Slot<float>; using Emission = Slot<glm::vec3>; using Ambient_occlusion = Slot<float>; Albedo albedo{glm::vec3(0.0f)}; Metallic metallic{0.0f}; Roughness roughness{1.0f}; Emission emission{glm::vec3(0.0f)}; Ambient_occlusion ambient_occlusion{1.0f}; Normal normal{}; float alpha{1.0f}; float index_of_refraction{1.5f}; float transmission{0.0f}; }; }
#pragma once #include <glm/glm.hpp> #include <string> #include <memory> #include <mos/gfx/texture_2d.hpp> namespace mos::gfx { class Assets; /** Physically based material. */ class Material final { public: template<class T> struct Slot { Slot(const T &value) : value(value) {} Slot(const Shared_texture_2D &texture) : texture(texture) {} Slot(const T &value, const Shared_texture_2D &texture) : value(value), texture(texture) {} T value = T(); Shared_texture_2D texture = Shared_texture_2D(); }; struct Normal { Shared_texture_2D texture; }; static auto load(Assets &assets, const std::string &path) -> Material; using Albedo = Slot<glm::vec3>; using Roughness = Slot<float>; using Metallic = Slot<float>; using Emission = Slot<glm::vec3>; using Ambient_occlusion = Slot<float>; Albedo albedo{glm::vec3(0.0f)}; Metallic metallic{0.0f}; Roughness roughness{1.0f}; Emission emission{glm::vec3(0.0f)}; Ambient_occlusion ambient_occlusion{1.0f}; Normal normal{}; float alpha{1.0f}; float index_of_refraction{1.5f}; float transmission{0.0f}; }; }
Remove explicit
Remove explicit
C++
mit
morganbengtsson/mos
56e301ea64aa94aa0a976db5be89bd1eb67352b8
include/observable/value.hpp
include/observable/value.hpp
#pragma once #include <algorithm> #include <functional> #include <memory> #include <type_traits> #include <utility> #include "observable/subject.hpp" #include "observable/subscription.hpp" #include "observable/detail/type_traits.hpp" namespace observable { template <typename ValueType, typename EqualityComparator=std::equal_to<>, typename ...> class value; template <typename ValueType> class value_updater; //! Observable values provide a way to get notified when a value-type changes. //! //! When setting a new value, if the new value is different than the existing one, //! any subscribed observers will be notified. //! //! \warning None of the methods in this class can be safely called concurrently. //! //! \tparam ValueType The value-type that will be stored inside the observable. //! This type will need to be at least movable. //! \tparam EqualityComparator A comparator to use when checking if new values //! are different than the stored value. template <typename ValueType, typename EqualityComparator> class value<ValueType, EqualityComparator> { public: //! The observable value's stored value type. using value_type = ValueType; //! Create a default-constructed observable value. //! //! Depending on the value type, the stored value will be either uninitialized //! or it will be default constructed. value() =default; //! Create an initialized observable value. //! //! \param initial_value The observable's initial value. explicit value(ValueType initial_value); //! Create an initialized value that will be updated by the provided updater. //! //! \param A value updater that will be stored by the value. template <typename UpdaterType> explicit value(std::unique_ptr<UpdaterType> && updater) : updater_ { std::move(updater) } { using namespace std::placeholders; updater_->set_value_notifier(std::bind(&value<ValueType, EqualityComparator>::set<ValueType>, this, _1)); set(updater_->get()); } //! Convert the observable value to its stored value type. explicit operator ValueType const &() const noexcept; //! Retrieve the stored value. auto get() const noexcept -> ValueType const &; //! Subscribe to changes to the observable value. //! //! These subscriptions will be triggered whenever the stored value changes. //! //! \tparam Callable A callable taking no parameters or a callable taking one //! parameter that will be called with the new value: //! - ``void()`` -- will be called when the value changes but //! will not receive the new value. //! - ``void(T const &)`` or ``void(T)`` -- will be called //! with the new value. The expression //! ``T { value.get() }`` must be correct. //! //! \see subject::subscribe() template <typename Callable> auto subscribe(Callable && callable) -> unique_subscription; //! Set a new value, possibly notifying any subscribed observers. //! //! If the new value compares equal to the existing value, this method has no //! effect. The comparison is performed using the EqualityComparator. //! //! \param new_value The new value to set. //! \tparam ValueType_ The new value's actual type. Must be convertible to //! the value's ValueType. //! \see subject::notify() template <typename ValueType_> auto set(ValueType_ && new_value) -> void; //! Set a new value. Will just call set(). //! //! \see set() template <typename ValueType_> auto operator=(ValueType_ && new_value) -> value &; public: //! Observable values are **not** copy-constructible. value(value const &) =delete; //! Observable values are **not** copy-assignable. auto operator=(value const &) -> value & =delete; //! Observable values are move-constructible. template <typename OtherEqualityComparator> value(value<ValueType, OtherEqualityComparator> && other) noexcept(std::is_nothrow_move_constructible<ValueType>::value); //! Observable values are move-assignable. template <typename OtherEqualityComparator> auto operator=(value<ValueType, OtherEqualityComparator> && other) noexcept(std::is_nothrow_move_assignable<ValueType>::value) -> value &; private: using void_subject = subject<void()>; using value_subject = subject<void(ValueType const &)>; template <typename Callable> auto subscribe_impl(Callable && observer) -> std::enable_if_t<detail::is_compatible_with_subject<Callable, void_subject>::value, unique_subscription> { return void_observers_.subscribe(std::forward<Callable>(observer)); } template <typename Callable> auto subscribe_impl(Callable && observer) -> std::enable_if_t<detail::is_compatible_with_subject<Callable, value_subject>::value, unique_subscription> { return value_observers_.subscribe(std::forward<Callable>(observer)); } private: ValueType value_; void_subject void_observers_; value_subject value_observers_; std::unique_ptr<value_updater<ValueType>> updater_; }; //! Observable values provide a way to get notified when a value-type changes. //! //! \see value<ValueType, EqualityComparator> //! //! This specialization is exactly the same as the main value specialization, but //! its setters are only accessible from inside the EnclosingType. //! //! \tparam ValueType The value-type that will be stored inside the observable. //! \tparam EqualityComparator A comparator to use when checking if new values //! are different than the stored value. //! \tparam EnclosingType A type that will have access to the value's setters. template <typename ValueType, typename EqualityComparator, typename EnclosingType> class value<ValueType, EqualityComparator, EnclosingType> : public value<ValueType, EqualityComparator> { public: using value<ValueType, EqualityComparator>::value; private: using value<ValueType, EqualityComparator>::set; using value<ValueType, EqualityComparator>::operator=; friend EnclosingType; }; //! Interface used to update a value when something happens. template <typename ValueType> class value_updater { public: //! Set a functor that can be used to notify the value to be updated of a //! change. //! //! \param[in] notifier Functor that will notify the value of a change. virtual void set_value_notifier(std::function<void(ValueType &&)> const & notifier) =0; //! Retrieve the current value. virtual auto get() const -> ValueType =0; //! Destructor. virtual ~value_updater() { } }; //! Convenience alias. template <typename ValueType, typename EnclosingType, typename EqualityComparator=std::equal_to<>> using property = value<ValueType, EqualityComparator, EnclosingType>; // Implementation template <typename ValueType, typename EqualityComparator> inline value<ValueType, EqualityComparator>::value(ValueType initial_value) : value_ { std::move(initial_value) } { } template <typename ValueType, typename EqualityComparator> inline value<ValueType, EqualityComparator>::operator ValueType const &() const noexcept { return value_; } template <typename ValueType, typename EqualityComparator> inline auto value<ValueType, EqualityComparator>::get() const noexcept -> ValueType const & { return value_; } template <typename ValueType, typename EqualityComparator> template <typename ValueType_> inline auto value<ValueType, EqualityComparator>::set(ValueType_ && new_value) -> void { if(EqualityComparator { }(new_value, value_)) return; value_ = std::forward<ValueType_>(new_value); void_observers_.notify(); value_observers_.notify(value_); } template <typename ValueType, typename EqualityComparator> template <typename ValueType_> inline auto value<ValueType, EqualityComparator>::operator=(ValueType_ && new_value) -> value & { set(std::forward<ValueType_>(new_value)); return *this; } template <typename ValueType, typename EqualityComparator> template <typename Callable> inline auto value<ValueType, EqualityComparator>::subscribe(Callable && callable) -> unique_subscription { static_assert(detail::is_compatible_with_subject<Callable, void_subject>::value || detail::is_compatible_with_subject<Callable, value_subject>::value, "Observer is not valid. Please provide a void observer or an " "observer that takes a ValueType as its only argument."); return subscribe_impl(std::forward<Callable>(callable)); } template <typename ValueType, typename EqualityComparator> template <typename OtherEqualityComparator> inline value<ValueType, EqualityComparator>::value(value<ValueType, OtherEqualityComparator> && other) noexcept(std::is_nothrow_move_constructible<ValueType>::value) : value_ { std::move(other.value_) }, void_observers_ { std::move(other.void_observers_) }, value_observers_ { std::move(other.value_observers_) }, updater_ { std::move(other.updater_) } { using namespace std::placeholders; if(updater_) updater_->set_value_notifier(std::bind(&value<ValueType, EqualityComparator>::set<ValueType>, this, _1)); } template <typename ValueType, typename EqualityComparator> template <typename OtherEqualityComparator> inline auto value<ValueType, EqualityComparator>::operator=(value<ValueType, OtherEqualityComparator> && other) noexcept(std::is_nothrow_move_assignable<ValueType>::value) -> value<ValueType, EqualityComparator> & { using namespace std::placeholders; value_ = std::move(other.value_); void_observers_ = std::move(other.void_observers_); value_observers_ = std::move(other.value_observers_); updater_ = std::move(other.updater_); if(updater_) updater_->set_value_notifier(std::bind(&value<ValueType, EqualityComparator>::set<ValueType>, this, _1)); } }
#pragma once #include <algorithm> #include <functional> #include <memory> #include <type_traits> #include <utility> #include "observable/subject.hpp" #include "observable/subscription.hpp" #include "observable/detail/type_traits.hpp" namespace observable { template <typename ValueType, typename EqualityComparator=std::equal_to<>, typename ...> class value; template <typename ValueType> class value_updater; //! Observable values provide a way to get notified when a value-type changes. //! //! When setting a new value, if the new value is different than the existing one, //! any subscribed observers will be notified. //! //! \warning None of the methods in this class can be safely called concurrently. //! //! \tparam ValueType The value-type that will be stored inside the observable. //! This type will need to be at least movable. //! \tparam EqualityComparator A comparator to use when checking if new values //! are different than the stored value. template <typename ValueType, typename EqualityComparator> class value<ValueType, EqualityComparator> { public: //! The observable value's stored value type. using value_type = ValueType; //! Create a default-constructed observable value. //! //! Depending on the value type, the stored value will be either uninitialized //! or it will be default constructed. value() =default; //! Create an initialized observable value. //! //! \param initial_value The observable's initial value. explicit value(ValueType initial_value); //! Create an initialized value that will be updated by the provided updater. //! //! \param A value updater that will be stored by the value. template <typename UpdaterType> explicit value(std::unique_ptr<UpdaterType> && updater) : updater_ { std::move(updater) } { using namespace std::placeholders; updater_->set_value_notifier(std::bind(&value<ValueType, EqualityComparator>::set<ValueType>, this, _1)); set(updater_->get()); } //! Convert the observable value to its stored value type. explicit operator ValueType const &() const noexcept; //! Retrieve the stored value. auto get() const noexcept -> ValueType const &; //! Subscribe to changes to the observable value. //! //! These subscriptions will be triggered whenever the stored value changes. //! //! \tparam Callable A callable taking no parameters or a callable taking one //! parameter that will be called with the new value: //! - ``void()`` -- will be called when the value changes but //! will not receive the new value. //! - ``void(T const &)`` or ``void(T)`` -- will be called //! with the new value. The expression //! ``T { value.get() }`` must be correct. //! //! \see subject::subscribe() template <typename Callable> auto subscribe(Callable && callable) -> unique_subscription; //! Set a new value, possibly notifying any subscribed observers. //! //! If the new value compares equal to the existing value, this method has no //! effect. The comparison is performed using the EqualityComparator. //! //! \param new_value The new value to set. //! \tparam ValueType_ The new value's actual type. Must be convertible to //! the value's ValueType. //! \see subject::notify() template <typename ValueType_> auto set(ValueType_ && new_value) -> void; //! Set a new value. Will just call set(). //! //! \see set() template <typename ValueType_> auto operator=(ValueType_ && new_value) -> value &; public: //! Observable values are **not** copy-constructible. value(value const &) =delete; //! Observable values are **not** copy-assignable. auto operator=(value const &) -> value & =delete; //! Observable values are move-constructible. template <typename OtherEqualityComparator> value(value<ValueType, OtherEqualityComparator> && other) noexcept(std::is_nothrow_move_constructible<ValueType>::value); //! Observable values are move-assignable. template <typename OtherEqualityComparator> auto operator=(value<ValueType, OtherEqualityComparator> && other) noexcept(std::is_nothrow_move_assignable<ValueType>::value) -> value &; private: using void_subject = subject<void()>; using value_subject = subject<void(ValueType const &)>; template <typename Callable> auto subscribe_impl(Callable && observer) -> std::enable_if_t<detail::is_compatible_with_subject<Callable, void_subject>::value, unique_subscription> { return void_observers_.subscribe(std::forward<Callable>(observer)); } template <typename Callable> auto subscribe_impl(Callable && observer) -> std::enable_if_t<detail::is_compatible_with_subject<Callable, value_subject>::value, unique_subscription> { return value_observers_.subscribe(std::forward<Callable>(observer)); } private: ValueType value_; void_subject void_observers_; value_subject value_observers_; std::unique_ptr<value_updater<ValueType>> updater_; }; //! Observable values provide a way to get notified when a value-type changes. //! //! \see value<ValueType, EqualityComparator> //! //! This specialization is exactly the same as the main value specialization, but //! its setters are only accessible from inside the EnclosingType. //! //! \tparam ValueType The value-type that will be stored inside the observable. //! \tparam EqualityComparator A comparator to use when checking if new values //! are different than the stored value. //! \tparam EnclosingType A type that will have access to the value's setters. template <typename ValueType, typename EqualityComparator, typename EnclosingType> class value<ValueType, EqualityComparator, EnclosingType> : public value<ValueType, EqualityComparator> { public: using value<ValueType, EqualityComparator>::value; private: using value<ValueType, EqualityComparator>::set; using value<ValueType, EqualityComparator>::operator=; friend EnclosingType; }; //! Interface used to update a value when something happens. template <typename ValueType> class value_updater { public: //! Set a functor that can be used to notify the value to be updated of a //! change. //! //! \param[in] notifier Functor that will notify the value of a change. virtual void set_value_notifier(std::function<void(ValueType &&)> const & notifier) =0; //! Retrieve the current value. virtual auto get() const -> ValueType =0; //! Destructor. virtual ~value_updater() { } }; //! Convenience alias. template <typename ValueType, typename EnclosingType, typename EqualityComparator=std::equal_to<>> using property = value<ValueType, EqualityComparator, EnclosingType>; // Implementation template <typename ValueType, typename EqualityComparator> inline value<ValueType, EqualityComparator>::value(ValueType initial_value) : value_ { std::move(initial_value) } { } template <typename ValueType, typename EqualityComparator> inline value<ValueType, EqualityComparator>::operator ValueType const &() const noexcept { return value_; } template <typename ValueType, typename EqualityComparator> inline auto value<ValueType, EqualityComparator>::get() const noexcept -> ValueType const & { return value_; } template <typename ValueType, typename EqualityComparator> template <typename ValueType_> inline auto value<ValueType, EqualityComparator>::set(ValueType_ && new_value) -> void { if(EqualityComparator { }(new_value, value_)) return; value_ = std::forward<ValueType_>(new_value); void_observers_.notify(); value_observers_.notify(value_); } template <typename ValueType, typename EqualityComparator> template <typename ValueType_> inline auto value<ValueType, EqualityComparator>::operator=(ValueType_ && new_value) -> value & { set(std::forward<ValueType_>(new_value)); return *this; } template <typename ValueType, typename EqualityComparator> template <typename Callable> inline auto value<ValueType, EqualityComparator>::subscribe(Callable && callable) -> unique_subscription { static_assert(detail::is_compatible_with_subject<Callable, void_subject>::value || detail::is_compatible_with_subject<Callable, value_subject>::value, "Observer is not valid. Please provide a void observer or an " "observer that takes a ValueType as its only argument."); return subscribe_impl(std::forward<Callable>(callable)); } template <typename ValueType, typename EqualityComparator> template <typename OtherEqualityComparator> inline value<ValueType, EqualityComparator>::value(value<ValueType, OtherEqualityComparator> && other) noexcept(std::is_nothrow_move_constructible<ValueType>::value) : value_ { std::move(other.value_) }, void_observers_ { std::move(other.void_observers_) }, value_observers_ { std::move(other.value_observers_) }, updater_ { std::move(other.updater_) } { using namespace std::placeholders; if(updater_) updater_->set_value_notifier(std::bind(&value<ValueType, EqualityComparator>::set<ValueType>, this, _1)); } template <typename ValueType, typename EqualityComparator> template <typename OtherEqualityComparator> inline auto value<ValueType, EqualityComparator>::operator=(value<ValueType, OtherEqualityComparator> && other) noexcept(std::is_nothrow_move_assignable<ValueType>::value) -> value<ValueType, EqualityComparator> & { using namespace std::placeholders; value_ = std::move(other.value_); void_observers_ = std::move(other.void_observers_); value_observers_ = std::move(other.value_observers_); updater_ = std::move(other.updater_); if(updater_) updater_->set_value_notifier(std::bind(&value<ValueType, EqualityComparator>::set<ValueType>, this, _1)); return *this; } }
Fix value assignment operator.
Fix value assignment operator.
C++
apache-2.0
ddinu/observable
c0ac2398967aacaab68966530d505a1aee4c2d2b
Modules/QtWidgetsExt/src/QmitkNumberPropertySlider.cpp
Modules/QtWidgetsExt/src/QmitkNumberPropertySlider.cpp
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <QmitkNumberPropertySlider.h> #include <mitkPropertyObserver.h> #include <mitkProperties.h> #include <mitkRenderingManager.h> #define DT_SHORT 1 #define DT_INT 2 #define DT_FLOAT 3 #define DT_DOUBLE 4 #define ROUND(x) (((x) > 0) ? int((x) + 0.5) : int((x) - 0.5)) #define ROUND_SHORT(x) (((x) > 0) ? short((x) + 0.5) : short((x) - 0.5)) class QmitkNumberPropertySlider::Impl { public: Impl(QmitkNumberPropertySlider* q); void DisplayNumber(); void adjustFactors(short, bool); class Editor : public mitk::PropertyEditor { public: Editor(mitk::IntProperty*, Impl* impl); Editor(mitk::FloatProperty*, Impl* impl); Editor(mitk::DoubleProperty*, Impl* impl); virtual void PropertyChanged(); virtual void PropertyRemoved(); void BeginModifyProperty() { mitk::PropertyEditor::BeginModifyProperty(); } void EndModifyProperty() { mitk::PropertyEditor::EndModifyProperty(); } union { mitk::GenericProperty<int>* m_IntProperty; mitk::GenericProperty<float>* m_FloatProperty; mitk::GenericProperty<double>* m_DoubleProperty; }; const int m_DataType; private: Impl* m_Impl; }; std::auto_ptr<Editor> m_PropEditor; short m_DecimalPlaces; // how many decimal places are shown double m_FactorPropertyToSlider; // internal conversion factor. neccessary because slider ranges work only with ints double m_FactorSliderToDisplay; // internal conversion factor. neccessary because slider ranges work only with ints bool m_ShowPercents; // whether values are given in percent (0.5 -> 50%) bool m_SelfChangeLock; private: void initialize(); QmitkNumberPropertySlider* q; }; QmitkNumberPropertySlider::Impl::Editor::Editor(mitk::IntProperty* property, Impl* impl) : mitk::PropertyEditor(property) , m_IntProperty(property) , m_DataType(DT_INT) , m_Impl(impl) { } QmitkNumberPropertySlider::Impl::Editor::Editor(mitk::FloatProperty* property, Impl* impl) : mitk::PropertyEditor( property ) , m_FloatProperty(property) , m_DataType(DT_FLOAT) , m_Impl(impl) { } QmitkNumberPropertySlider::Impl::Editor::Editor(mitk::DoubleProperty* property, Impl* impl) : mitk::PropertyEditor( property ) , m_DoubleProperty(property) , m_DataType(DT_DOUBLE) , m_Impl(impl) { } QmitkNumberPropertySlider::~QmitkNumberPropertySlider() { } void QmitkNumberPropertySlider::SetProperty(mitk::IntProperty* property) { if (property == NULL) { d->m_PropEditor->PropertyRemoved(); d->m_PropEditor.reset(); this->setEnabled(false); } else { d->m_PropEditor.reset(new Impl::Editor(property, d.get())); d->m_PropEditor->PropertyChanged(); this->setEnabled(true); } } void QmitkNumberPropertySlider::SetProperty(mitk::FloatProperty* property) { if (property == NULL) { d->m_PropEditor->PropertyRemoved(); d->m_PropEditor.reset(); this->setEnabled(false); } else { d->m_PropEditor.reset(new Impl::Editor(property, d.get())); d->m_PropEditor->PropertyChanged(); this->setEnabled(true); } } void QmitkNumberPropertySlider::SetProperty(mitk::DoubleProperty* property) { if (property == NULL) { d->m_PropEditor->PropertyRemoved(); d->m_PropEditor.reset(); this->setEnabled(false); } else { d->m_PropEditor.reset(new Impl::Editor(property, d.get())); d->m_PropEditor->PropertyChanged(); this->setEnabled(true); } } QmitkNumberPropertySlider::Impl::Impl(QmitkNumberPropertySlider* q) : m_DecimalPlaces(0) , m_FactorPropertyToSlider(1.0) , m_FactorSliderToDisplay(1.0) , m_ShowPercents(false) , m_SelfChangeLock(false) , q(q) { } QmitkNumberPropertySlider::QmitkNumberPropertySlider(QWidget *parent) : QSlider(parent) , d(new Impl(this)) { connect( this, SIGNAL(valueChanged(int)), this, SLOT(onValueChanged(int)) ); this->setEnabled(false); } void QmitkNumberPropertySlider::Impl::adjustFactors(short newDecimalPlaces, bool newShowPercents) { int oldMax = q->maxValue(); int oldMin = q->minValue(); m_DecimalPlaces = newDecimalPlaces; m_ShowPercents = newShowPercents; m_FactorPropertyToSlider = pow(10.0,m_DecimalPlaces); m_FactorSliderToDisplay = 1.0 / m_FactorPropertyToSlider; if ( m_ShowPercents ) m_FactorPropertyToSlider *= 100.0; q->setMinimum(oldMin); q->setMaximum(oldMax); } short QmitkNumberPropertySlider::getDecimalPlaces() const { return d->m_DecimalPlaces; } void QmitkNumberPropertySlider::setDecimalPlaces(short places) { if (d->m_PropEditor.get() == NULL) return; switch (d->m_PropEditor->m_DataType) { case DT_FLOAT: case DT_DOUBLE: { d->adjustFactors( places, d->m_ShowPercents ); d->DisplayNumber(); break; } default: break; } } bool QmitkNumberPropertySlider::getShowPercent() const { return d->m_ShowPercents; } void QmitkNumberPropertySlider::setShowPercent(bool showPercent) { if ( showPercent == d->m_ShowPercents ) return; // nothing to change if (d->m_PropEditor.get() == NULL) return; switch (d->m_PropEditor->m_DataType) { case DT_FLOAT: case DT_DOUBLE: { d->adjustFactors(d->m_DecimalPlaces, showPercent); break; } default: { break; } } d->DisplayNumber(); } int QmitkNumberPropertySlider::minValue() const { return ROUND( QSlider::minimum() / d->m_FactorPropertyToSlider ); } void QmitkNumberPropertySlider::setMinValue(int value) { QSlider::setMinimum( ROUND(value * d->m_FactorPropertyToSlider ) ); } int QmitkNumberPropertySlider::maxValue() const { return ROUND( QSlider::maximum() / d->m_FactorPropertyToSlider ); } void QmitkNumberPropertySlider::setMaxValue(int value) { QSlider::setMaximum( ROUND( value * d->m_FactorPropertyToSlider ) ); } double QmitkNumberPropertySlider::doubleValue() const { return static_cast<double>((QSlider::value()) / d->m_FactorPropertyToSlider ); } void QmitkNumberPropertySlider::setDoubleValue(double value) { QSlider::setValue( ROUND( value * d->m_FactorPropertyToSlider ) ); } void QmitkNumberPropertySlider::onValueChanged(int value) { if (d->m_PropEditor.get() == NULL) return; if (d->m_SelfChangeLock) return; // valueChanged is even emitted, when this widget initiates a change to its value // this may be useful some times, but in this use, it would be wrong: // (A) is an editor with 3 decimal places // (B) is an editor with 2 decimal places // User changes A's displayed value to 4.002 // A's onValueChanged gets called, sets the associated Property to 4.002 // B's onPropertyChanged gets called, sets its display to 4.00 // B's onValueChanged gets called and sets the associated Property to 4.00 // A's onPropertyChanged gets called, sets its display to 4.000 d->m_PropEditor->BeginModifyProperty(); double newValue( value / d->m_FactorPropertyToSlider ); switch (d->m_PropEditor->m_DataType) { case DT_INT: { d->m_PropEditor->m_IntProperty->SetValue(ROUND(newValue)); break; } case DT_FLOAT: { d->m_PropEditor->m_FloatProperty->SetValue(newValue); break; } case DT_DOUBLE: { d->m_PropEditor->m_DoubleProperty->SetValue(newValue); break; } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); d->m_PropEditor->EndModifyProperty(); } void QmitkNumberPropertySlider::Impl::Editor::PropertyChanged() { m_Impl->DisplayNumber(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkNumberPropertySlider::Impl::Editor::PropertyRemoved() { this->m_Property = NULL; } void QmitkNumberPropertySlider::Impl::DisplayNumber() { if (m_PropEditor.get() == NULL) return; m_SelfChangeLock = true; switch (m_PropEditor->m_DataType) { case DT_INT: { int i = m_PropEditor->m_IntProperty->GetValue(); q->setValue( i ); break; } case DT_FLOAT: { float f = m_PropEditor->m_FloatProperty->GetValue(); q->setDoubleValue( f ); break; } case DT_DOUBLE: { double d = m_PropEditor->m_DoubleProperty->GetValue(); q->setDoubleValue( d ); break; } default: break; } m_SelfChangeLock = false; }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <QmitkNumberPropertySlider.h> #include <mitkPropertyObserver.h> #include <mitkProperties.h> #include <mitkRenderingManager.h> #define DT_SHORT 1 #define DT_INT 2 #define DT_FLOAT 3 #define DT_DOUBLE 4 #define ROUND(x) (((x) > 0) ? int((x) + 0.5) : int((x) - 0.5)) #define ROUND_SHORT(x) (((x) > 0) ? short((x) + 0.5) : short((x) - 0.5)) class QmitkNumberPropertySlider::Impl { public: Impl(QmitkNumberPropertySlider* q); void DisplayNumber(); void adjustFactors(short, bool); class Editor : public mitk::PropertyEditor { public: Editor(mitk::IntProperty*, Impl* impl); Editor(mitk::FloatProperty*, Impl* impl); Editor(mitk::DoubleProperty*, Impl* impl); virtual void PropertyChanged(); virtual void PropertyRemoved(); void BeginModifyProperty() { mitk::PropertyEditor::BeginModifyProperty(); } void EndModifyProperty() { mitk::PropertyEditor::EndModifyProperty(); } union { mitk::GenericProperty<int>* m_IntProperty; mitk::GenericProperty<float>* m_FloatProperty; mitk::GenericProperty<double>* m_DoubleProperty; }; const int m_DataType; private: Impl* m_Impl; }; std::auto_ptr<Editor> m_PropEditor; short m_DecimalPlaces; // how many decimal places are shown double m_FactorPropertyToSlider; // internal conversion factor. neccessary because slider ranges work only with ints double m_FactorSliderToDisplay; // internal conversion factor. neccessary because slider ranges work only with ints bool m_ShowPercents; // whether values are given in percent (0.5 -> 50%) bool m_SelfChangeLock; private: void initialize(); QmitkNumberPropertySlider* q; }; QmitkNumberPropertySlider::Impl::Editor::Editor(mitk::IntProperty* property, Impl* impl) : mitk::PropertyEditor(property) , m_IntProperty(property) , m_DataType(DT_INT) , m_Impl(impl) { } QmitkNumberPropertySlider::Impl::Editor::Editor(mitk::FloatProperty* property, Impl* impl) : mitk::PropertyEditor( property ) , m_FloatProperty(property) , m_DataType(DT_FLOAT) , m_Impl(impl) { } QmitkNumberPropertySlider::Impl::Editor::Editor(mitk::DoubleProperty* property, Impl* impl) : mitk::PropertyEditor( property ) , m_DoubleProperty(property) , m_DataType(DT_DOUBLE) , m_Impl(impl) { } QmitkNumberPropertySlider::~QmitkNumberPropertySlider() { } void QmitkNumberPropertySlider::SetProperty(mitk::IntProperty* property) { if (property == NULL) { d->m_PropEditor.reset(); this->setEnabled(false); } else { d->m_PropEditor.reset(new Impl::Editor(property, d.get())); d->m_PropEditor->PropertyChanged(); this->setEnabled(true); } } void QmitkNumberPropertySlider::SetProperty(mitk::FloatProperty* property) { if (property == NULL) { d->m_PropEditor.reset(); this->setEnabled(false); } else { d->m_PropEditor.reset(new Impl::Editor(property, d.get())); d->m_PropEditor->PropertyChanged(); this->setEnabled(true); } } void QmitkNumberPropertySlider::SetProperty(mitk::DoubleProperty* property) { if (property == NULL) { d->m_PropEditor.reset(); this->setEnabled(false); } else { d->m_PropEditor.reset(new Impl::Editor(property, d.get())); d->m_PropEditor->PropertyChanged(); this->setEnabled(true); } } QmitkNumberPropertySlider::Impl::Impl(QmitkNumberPropertySlider* q) : m_DecimalPlaces(0) , m_FactorPropertyToSlider(1.0) , m_FactorSliderToDisplay(1.0) , m_ShowPercents(false) , m_SelfChangeLock(false) , q(q) { } QmitkNumberPropertySlider::QmitkNumberPropertySlider(QWidget *parent) : QSlider(parent) , d(new Impl(this)) { connect( this, SIGNAL(valueChanged(int)), this, SLOT(onValueChanged(int)) ); this->setEnabled(false); } void QmitkNumberPropertySlider::Impl::adjustFactors(short newDecimalPlaces, bool newShowPercents) { int oldMax = q->maxValue(); int oldMin = q->minValue(); m_DecimalPlaces = newDecimalPlaces; m_ShowPercents = newShowPercents; m_FactorPropertyToSlider = pow(10.0,m_DecimalPlaces); m_FactorSliderToDisplay = 1.0 / m_FactorPropertyToSlider; if ( m_ShowPercents ) m_FactorPropertyToSlider *= 100.0; q->setMinimum(oldMin); q->setMaximum(oldMax); } short QmitkNumberPropertySlider::getDecimalPlaces() const { return d->m_DecimalPlaces; } void QmitkNumberPropertySlider::setDecimalPlaces(short places) { if (d->m_PropEditor.get() == NULL) return; switch (d->m_PropEditor->m_DataType) { case DT_FLOAT: case DT_DOUBLE: { d->adjustFactors( places, d->m_ShowPercents ); d->DisplayNumber(); break; } default: break; } } bool QmitkNumberPropertySlider::getShowPercent() const { return d->m_ShowPercents; } void QmitkNumberPropertySlider::setShowPercent(bool showPercent) { if ( showPercent == d->m_ShowPercents ) return; // nothing to change if (d->m_PropEditor.get() == NULL) return; switch (d->m_PropEditor->m_DataType) { case DT_FLOAT: case DT_DOUBLE: { d->adjustFactors(d->m_DecimalPlaces, showPercent); break; } default: { break; } } d->DisplayNumber(); } int QmitkNumberPropertySlider::minValue() const { return ROUND( QSlider::minimum() / d->m_FactorPropertyToSlider ); } void QmitkNumberPropertySlider::setMinValue(int value) { QSlider::setMinimum( ROUND(value * d->m_FactorPropertyToSlider ) ); } int QmitkNumberPropertySlider::maxValue() const { return ROUND( QSlider::maximum() / d->m_FactorPropertyToSlider ); } void QmitkNumberPropertySlider::setMaxValue(int value) { QSlider::setMaximum( ROUND( value * d->m_FactorPropertyToSlider ) ); } double QmitkNumberPropertySlider::doubleValue() const { return static_cast<double>((QSlider::value()) / d->m_FactorPropertyToSlider ); } void QmitkNumberPropertySlider::setDoubleValue(double value) { QSlider::setValue( ROUND( value * d->m_FactorPropertyToSlider ) ); } void QmitkNumberPropertySlider::onValueChanged(int value) { if (d->m_PropEditor.get() == NULL) return; if (d->m_SelfChangeLock) return; // valueChanged is even emitted, when this widget initiates a change to its value // this may be useful some times, but in this use, it would be wrong: // (A) is an editor with 3 decimal places // (B) is an editor with 2 decimal places // User changes A's displayed value to 4.002 // A's onValueChanged gets called, sets the associated Property to 4.002 // B's onPropertyChanged gets called, sets its display to 4.00 // B's onValueChanged gets called and sets the associated Property to 4.00 // A's onPropertyChanged gets called, sets its display to 4.000 d->m_PropEditor->BeginModifyProperty(); double newValue( value / d->m_FactorPropertyToSlider ); switch (d->m_PropEditor->m_DataType) { case DT_INT: { d->m_PropEditor->m_IntProperty->SetValue(ROUND(newValue)); break; } case DT_FLOAT: { d->m_PropEditor->m_FloatProperty->SetValue(newValue); break; } case DT_DOUBLE: { d->m_PropEditor->m_DoubleProperty->SetValue(newValue); break; } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); d->m_PropEditor->EndModifyProperty(); } void QmitkNumberPropertySlider::Impl::Editor::PropertyChanged() { m_Impl->DisplayNumber(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkNumberPropertySlider::Impl::Editor::PropertyRemoved() { this->m_Property = NULL; } void QmitkNumberPropertySlider::Impl::DisplayNumber() { if (m_PropEditor.get() == NULL) return; m_SelfChangeLock = true; switch (m_PropEditor->m_DataType) { case DT_INT: { int i = m_PropEditor->m_IntProperty->GetValue(); q->setValue( i ); break; } case DT_FLOAT: { float f = m_PropEditor->m_FloatProperty->GetValue(); q->setDoubleValue( f ); break; } case DT_DOUBLE: { double d = m_PropEditor->m_DoubleProperty->GetValue(); q->setDoubleValue( d ); break; } default: break; } m_SelfChangeLock = false; }
undo PropertyRemoved calls
undo PropertyRemoved calls
C++
bsd-3-clause
iwegner/MITK,iwegner/MITK,fmilano/mitk,MITK/MITK,iwegner/MITK,iwegner/MITK,RabadanLab/MITKats,RabadanLab/MITKats,fmilano/mitk,RabadanLab/MITKats,RabadanLab/MITKats,MITK/MITK,NifTK/MITK,MITK/MITK,NifTK/MITK,NifTK/MITK,fmilano/mitk,MITK/MITK,fmilano/mitk,MITK/MITK,fmilano/mitk,fmilano/mitk,fmilano/mitk,RabadanLab/MITKats,iwegner/MITK,MITK/MITK,iwegner/MITK,NifTK/MITK,NifTK/MITK,RabadanLab/MITKats,NifTK/MITK
ee8772e500eaf5d0fceb6880cd5f429f2d3f30c4
iree/compiler/Conversion/LinalgToLLVM/Passes.cpp
iree/compiler/Conversion/LinalgToLLVM/Passes.cpp
// Copyright 2020 Google LLC // // 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 // // https://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 "iree/compiler/Conversion/Common/Passes.h" #include "iree/compiler/Conversion/HLOToHLO/Passes.h" #include "iree/compiler/Conversion/LinalgToLLVM/Passes.h" #include "iree/compiler/Dialect/Shape/Transforms/Passes.h" #include "mlir/Conversion/SCFToStandard/SCFToStandard.h" #include "mlir/Dialect/Linalg/Passes.h" #include "mlir/Dialect/StandardOps/Transforms/Passes.h" #include "mlir/Pass/PassManager.h" #include "mlir/Transforms/Passes.h" namespace mlir { namespace iree_compiler { void addLinalgToLLVMPasses(OpPassManager &passManager, LLVMCodegenOptions options) { OpPassManager &nestedModulePM = passManager.nest<ModuleOp>(); // Tile and vectorize linalg ops. nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass()); nestedModulePM.addNestedPass<FuncOp>( createLinalgTileAndVectorizeWorkgroupsPass()); nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass()); nestedModulePM.addNestedPass<FuncOp>(createForOpCanonicalizationPass()); nestedModulePM.addNestedPass<FuncOp>(createPlanConvLoopOrderPass()); // Linalg -> SCF nestedModulePM.addNestedPass<FuncOp>(createConvertLinalgToLoopsPass()); nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass()); nestedModulePM.addNestedPass<FuncOp>(createCSEPass()); // SCF -> STD nestedModulePM.addNestedPass<FuncOp>(createLowerToCFGPass()); nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass()); nestedModulePM.addNestedPass<FuncOp>(createCSEPass()); // Handled tensor-type constants. nestedModulePM.addPass(createTensorConstantBufferizePass()); nestedModulePM.addPass(createFoldTensorExtractOpPass()); // (HAL, IREE, Linalg, STD) -> LLVM nestedModulePM.addPass(createConvertToLLVMPass(options)); nestedModulePM.addPass(createCanonicalizerPass()); nestedModulePM.addPass(createCSEPass()); } void buildLLVMTransformPassPipeline(OpPassManager &passManager, LLVMCodegenOptions options) { passManager.addPass(createMaterializeCPULaunchConfigurationPass()); OpPassManager &nestedModulePM = passManager.nest<ModuleOp>(); nestedModulePM.addPass(createCanonicalizerPass()); nestedModulePM.addNestedPass<FuncOp>(createPadLinalgWorkgroupTilesPass()); // TODO(ataei): We want to enable when tensor -> vector pass is fully // supported which requires first moving vector-tiling before this step. if (options.useLinalgOnTensorsToVectors) { nestedModulePM.addNestedPass<FuncOp>(createLinalgVectorizePass()); } // Use stack allocation on CPU side. WorkgroupMemoryAllocationFn allocationFn = [](OpBuilder &builder, Location loc, ArrayRef<int64_t> staticShape, Type elementType, ArrayRef<Value> dynamicSizes) { MemRefType allocType = MemRefType::get(staticShape, elementType); return builder.create<memref::AllocaOp>(loc, allocType, dynamicSizes); }; addLinalgBufferizePasses(nestedModulePM, allocationFn); nestedModulePM.addPass(createPromoteBuffersToStackPass( /*maxAllocSizeInBytes=*/1 << 10, /*bitwidthOfIndexType=*/64, /*maxRankOfAllocatedMemRef=*/10)); // Linalg -> LLVM passes. addLinalgToLLVMPasses(passManager, options); } static PassPipelineRegistration<> linalgLLVMVPipeline( "iree-codegen-linalg-to-llvm-pipeline", "Runs the progressive lowering pipeline from Linalg to LLVM", [](OpPassManager &passManager) { buildLLVMTransformPassPipeline(passManager, getLLVMCodegenOptionsFromClOptions()); }); static PassPipelineRegistration<> hloToLinalgLLVMVPipeline( "iree-codegen-hlo-to-llvm-pipeline", "Runs the progressive lowering pipeline from XLA HLO to Linalg to LLVM", [](OpPassManager &passManager) { buildLLVMTransformPassPipeline(passManager, getLLVMCodegenOptionsFromClOptions()); }); } // namespace iree_compiler } // namespace mlir
// Copyright 2020 Google LLC // // 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 // // https://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 "iree/compiler/Conversion/Common/Passes.h" #include "iree/compiler/Conversion/HLOToHLO/Passes.h" #include "iree/compiler/Conversion/LinalgToLLVM/Passes.h" #include "iree/compiler/Dialect/Shape/Transforms/Passes.h" #include "mlir/Conversion/SCFToStandard/SCFToStandard.h" #include "mlir/Dialect/Linalg/Passes.h" #include "mlir/Dialect/StandardOps/Transforms/Passes.h" #include "mlir/Pass/PassManager.h" #include "mlir/Transforms/Passes.h" namespace mlir { namespace iree_compiler { void addLinalgToLLVMPasses(OpPassManager &passManager, LLVMCodegenOptions options) { OpPassManager &nestedModulePM = passManager.nest<ModuleOp>(); // Tile and vectorize linalg ops. nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass()); nestedModulePM.addNestedPass<FuncOp>( createLinalgTileAndVectorizeWorkgroupsPass()); nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass()); nestedModulePM.addNestedPass<FuncOp>(createForOpCanonicalizationPass()); nestedModulePM.addNestedPass<FuncOp>(createPlanConvLoopOrderPass()); // Linalg -> SCF nestedModulePM.addNestedPass<FuncOp>(createConvertLinalgToLoopsPass()); nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass()); nestedModulePM.addNestedPass<FuncOp>(createCSEPass()); // SCF -> STD nestedModulePM.addNestedPass<FuncOp>(createLowerToCFGPass()); nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass()); nestedModulePM.addNestedPass<FuncOp>(createCSEPass()); // Handled tensor-type constants. nestedModulePM.addPass(createTensorConstantBufferizePass()); nestedModulePM.addPass(createFoldTensorExtractOpPass()); // (HAL, IREE, Linalg, STD) -> LLVM nestedModulePM.addPass(createConvertToLLVMPass(options)); nestedModulePM.addPass(createCanonicalizerPass()); nestedModulePM.addPass(createCSEPass()); } void buildLLVMTransformPassPipeline(OpPassManager &passManager, LLVMCodegenOptions options) { passManager.addPass(createMaterializeCPULaunchConfigurationPass()); OpPassManager &nestedModulePM = passManager.nest<ModuleOp>(); nestedModulePM.addPass(createCanonicalizerPass()); // TODO(ataei): This causes segmentation fault on Android. Fix it and // re-enable. // nestedModulePM.addNestedPass<FuncOp>(createPadLinalgWorkgroupTilesPass()); // TODO(ataei): We want to enable when tensor -> vector pass is fully // supported which requires first moving vector-tiling before this step. if (options.useLinalgOnTensorsToVectors) { nestedModulePM.addNestedPass<FuncOp>(createLinalgVectorizePass()); } // Use stack allocation on CPU side. WorkgroupMemoryAllocationFn allocationFn = [](OpBuilder &builder, Location loc, ArrayRef<int64_t> staticShape, Type elementType, ArrayRef<Value> dynamicSizes) { MemRefType allocType = MemRefType::get(staticShape, elementType); return builder.create<memref::AllocaOp>(loc, allocType, dynamicSizes); }; addLinalgBufferizePasses(nestedModulePM, allocationFn); nestedModulePM.addPass(createPromoteBuffersToStackPass( /*maxAllocSizeInBytes=*/1 << 10, /*bitwidthOfIndexType=*/64, /*maxRankOfAllocatedMemRef=*/10)); // Linalg -> LLVM passes. addLinalgToLLVMPasses(passManager, options); } static PassPipelineRegistration<> linalgLLVMVPipeline( "iree-codegen-linalg-to-llvm-pipeline", "Runs the progressive lowering pipeline from Linalg to LLVM", [](OpPassManager &passManager) { buildLLVMTransformPassPipeline(passManager, getLLVMCodegenOptionsFromClOptions()); }); static PassPipelineRegistration<> hloToLinalgLLVMVPipeline( "iree-codegen-hlo-to-llvm-pipeline", "Runs the progressive lowering pipeline from XLA HLO to Linalg to LLVM", [](OpPassManager &passManager) { buildLLVMTransformPassPipeline(passManager, getLLVMCodegenOptionsFromClOptions()); }); } // namespace iree_compiler } // namespace mlir
Disable CPU workgroup padding (#5884)
Disable CPU workgroup padding (#5884) This causes segfault on Android devices: https://buildkite.com/iree/iree-android-arm64-v8a/builds/4235
C++
apache-2.0
google/iree,google/iree,iree-org/iree,iree-org/iree,iree-org/iree,iree-org/iree,google/iree,google/iree,iree-org/iree,iree-org/iree,iree-org/iree,google/iree,google/iree,google/iree
217ef537f2d9de582680a061a04393c552690391
include/VFSPP/memory.hpp
include/VFSPP/memory.hpp
#pragma once #include <VFSPP/core.hpp> #include <boost/unordered_map.hpp> #include <boost/shared_array.hpp> #include <boost/shared_ptr.hpp> namespace vfspp { namespace memory { class MemoryFileSystem; class VFSPP_EXPORT MemoryFileEntry : public IFileSystemEntry { private: EntryType type; std::vector<boost::shared_ptr<MemoryFileEntry> > fileEntries; boost::unordered_map<string_type, size_t> indexMapping; size_t dataSize; boost::shared_array<char> data; time_t writeTime; MemoryFileEntry(const string_type& path) : IFileSystemEntry(path), dataSize(0), writeTime(0), type(UNKNOWN) {} FileEntryPointer getChildInternal(const string_type& path); public: virtual ~MemoryFileEntry() {} virtual FileEntryPointer getChild(const string_type& path) VFSPP_OVERRIDE; virtual size_t numChildren() VFSPP_OVERRIDE; virtual void listChildren(std::vector<FileEntryPointer>& outVector) VFSPP_OVERRIDE; virtual boost::shared_ptr<std::streambuf> open(int mode = MODE_READ) VFSPP_OVERRIDE; virtual EntryType getType() const VFSPP_OVERRIDE; virtual bool deleteChild(const string_type& name) VFSPP_OVERRIDE; virtual FileEntryPointer createEntry(EntryType type, const string_type& name) VFSPP_OVERRIDE; virtual void rename(const string_type& newPath) VFSPP_OVERRIDE; virtual time_t lastWriteTime() VFSPP_OVERRIDE { return writeTime; } boost::shared_ptr<MemoryFileEntry> addChild(const string_type& name, EntryType type, time_t write_time = 0, void* data = 0, size_t dataSize = 0); friend class MemoryFileSystem; }; class VFSPP_EXPORT MemoryFileSystem : public IFileSystem { private: boost::scoped_ptr<MemoryFileEntry> rootEntry; public: MemoryFileSystem(); virtual ~MemoryFileSystem() {} virtual MemoryFileEntry* getRootEntry() VFSPP_OVERRIDE { return rootEntry.get(); } virtual int supportedOperations() const VFSPP_OVERRIDE { return OP_READ; } }; } }
#pragma once #include <VFSPP/core.hpp> #include <boost/unordered_map.hpp> #include <boost/shared_array.hpp> #include <boost/shared_ptr.hpp> namespace vfspp { namespace memory { class MemoryFileSystem; class VFSPP_EXPORT MemoryFileEntry : public IFileSystemEntry { private: EntryType type; std::vector<boost::shared_ptr<MemoryFileEntry> > fileEntries; boost::unordered_map<string_type, size_t> indexMapping; size_t dataSize; boost::shared_array<char> data; time_t writeTime; MemoryFileEntry(const string_type& path) : IFileSystemEntry(path), dataSize(0), writeTime(0), type(UNKNOWN) {} FileEntryPointer getChildInternal(const string_type& path); public: virtual ~MemoryFileEntry() {} virtual FileEntryPointer getChild(const string_type& path) VFSPP_OVERRIDE; virtual size_t numChildren() VFSPP_OVERRIDE; virtual void listChildren(std::vector<FileEntryPointer>& outVector) VFSPP_OVERRIDE; virtual boost::shared_ptr<std::streambuf> open(int mode = MODE_READ) VFSPP_OVERRIDE; virtual EntryType getType() const VFSPP_OVERRIDE; virtual bool deleteChild(const string_type& name) VFSPP_OVERRIDE; virtual FileEntryPointer createEntry(EntryType type, const string_type& name) VFSPP_OVERRIDE; virtual void rename(const string_type& newPath) VFSPP_OVERRIDE; virtual time_t lastWriteTime() VFSPP_OVERRIDE { return writeTime; } boost::shared_ptr<MemoryFileEntry> addChild(const string_type& name, EntryType type, time_t write_time = 0, void* data = 0, size_t dataSize = 0); friend class MemoryFileSystem; }; class VFSPP_EXPORT MemoryFileSystem : public IFileSystem { private: boost::scoped_ptr<MemoryFileEntry> rootEntry; public: MemoryFileSystem(); virtual ~MemoryFileSystem() {} virtual MemoryFileEntry* getRootEntry() VFSPP_OVERRIDE { return rootEntry.get(); } virtual int supportedOperations() const VFSPP_OVERRIDE{ return OP_READ; } virtual string_type getName() const { return "Memory filesystem"; }; }; } }
Add missing implementation
Add missing implementation
C++
mit
asarium/vfspp,asarium/vfspp,asarium/vfspp,asarium/vfspp
338da9c41b942fec1a6cc384e060f89a9f4f318d
src/bin/cli/karabiner_cli/main.cpp
src/bin/cli/karabiner_cli/main.cpp
#include "configuration_monitor.hpp" #include "constants.hpp" #include "cxxopts/cxxopts.hpp" #include <iostream> namespace { class logger final { public: static spdlog::logger& get_logger(void) { static std::shared_ptr<spdlog::logger> logger; if (!logger) { logger = spdlog::stdout_logger_mt("karabiner_cli", true); logger->set_pattern("[%l] %v"); logger->set_level(spdlog::level::err); } return *logger; } }; } int main(int argc, char* argv[]) { krbn::thread_utility::register_main_thread(); cxxopts::Options options("karabiner_cli", "A command line utility of Karabiner-Elements."); options.add_options()("select-profile", "Select a profile by name.", cxxopts::value<std::string>()); options.add_options()("copy-current-profile-to-system-default-profile", "Copy the current profile to system default profile."); options.add_options()("remove-system-default-profile", "Remove the system default profile."); options.add_options()("help", "Print help."); try { options.parse(argc, argv); { std::string key = "select-profile"; if (options.count(key)) { auto& name = options[key].as<std::string>(); krbn::configuration_monitor monitor(logger::get_logger(), krbn::constants::get_user_core_configuration_file_path(), [&name](std::shared_ptr<krbn::core_configuration> core_configuration) { auto& profiles = core_configuration->get_profiles(); for (size_t i = 0; i < profiles.size(); ++i) { if (profiles[i].get_name() == name) { core_configuration->select_profile(i); core_configuration->save_to_file(krbn::constants::get_user_core_configuration_file_path()); exit(0); } } logger::get_logger().error("`{0}` is not found.", name); exit(2); }); CFRunLoopRun(); } } { std::string key = "copy-current-profile-to-system-default-profile"; if (options.count(key)) { if (getuid() != 0) { logger::get_logger().error("--{0} requires root privilege.", key); return 1; } krbn::filesystem::create_directory_with_intermediate_directories(krbn::constants::get_system_configuration_directory(), 0755); std::ifstream ifstream(krbn::constants::get_user_core_configuration_file_path()); if (!ifstream) { logger::get_logger().error("Failed to open {0}", krbn::constants::get_user_core_configuration_file_path()); return 1; } std::ofstream ofstream(krbn::constants::get_system_core_configuration_file_path()); if (!ofstream) { logger::get_logger().error("Failed to open {0}", krbn::constants::get_system_core_configuration_file_path()); return 1; } ofstream << ifstream.rdbuf(); return 0; } } { std::string key = "remove-system-default-profile"; if (options.count(key)) { if (getuid() != 0) { logger::get_logger().error("--{0} requires root privilege.", key); return 1; } if (!krbn::filesystem::exists(krbn::constants::get_system_core_configuration_file_path())) { logger::get_logger().error("{0} is not found.", krbn::constants::get_system_core_configuration_file_path()); return 1; } if (unlink(krbn::constants::get_system_core_configuration_file_path()) != 0) { logger::get_logger().error("Failed to unlink {0}."); return 1; } return 0; } } } catch (const cxxopts::OptionException& e) { std::cout << "error parsing options: " << e.what() << std::endl; return 2; } std::cout << options.help() << std::endl; std::cout << "Examples:" << std::endl; std::cout << " karabiner_cli --select-profile 'Default profile'" << std::endl; std::cout << std::endl; return 1; }
#include "configuration_monitor.hpp" #include "constants.hpp" #include "cxxopts/cxxopts.hpp" #include <iostream> namespace { class logger final { public: static spdlog::logger& get_logger(void) { static std::shared_ptr<spdlog::logger> logger; if (!logger) { logger = spdlog::stdout_logger_mt("karabiner_cli", true); logger->set_pattern("[%l] %v"); logger->set_level(spdlog::level::err); } return *logger; } }; } int main(int argc, char* argv[]) { krbn::thread_utility::register_main_thread(); cxxopts::Options options("karabiner_cli", "A command line utility of Karabiner-Elements."); options.add_options()("select-profile", "Select a profile by name.", cxxopts::value<std::string>()); options.add_options()("copy-current-profile-to-system-default-profile", "Copy the current profile to system default profile."); options.add_options()("remove-system-default-profile", "Remove the system default profile."); options.add_options()("help", "Print help."); try { options.parse(argc, argv); { std::string key = "select-profile"; if (options.count(key)) { auto& name = options[key].as<std::string>(); krbn::configuration_monitor monitor(logger::get_logger(), krbn::constants::get_user_core_configuration_file_path(), [&name](std::shared_ptr<krbn::core_configuration> core_configuration) { auto& profiles = core_configuration->get_profiles(); for (size_t i = 0; i < profiles.size(); ++i) { if (profiles[i].get_name() == name) { core_configuration->select_profile(i); core_configuration->save_to_file(krbn::constants::get_user_core_configuration_file_path()); return; } } logger::get_logger().error("`{0}` is not found.", name); }); return 0; } } { std::string key = "copy-current-profile-to-system-default-profile"; if (options.count(key)) { if (getuid() != 0) { logger::get_logger().error("--{0} requires root privilege.", key); return 1; } krbn::filesystem::create_directory_with_intermediate_directories(krbn::constants::get_system_configuration_directory(), 0755); std::ifstream ifstream(krbn::constants::get_user_core_configuration_file_path()); if (!ifstream) { logger::get_logger().error("Failed to open {0}", krbn::constants::get_user_core_configuration_file_path()); return 1; } std::ofstream ofstream(krbn::constants::get_system_core_configuration_file_path()); if (!ofstream) { logger::get_logger().error("Failed to open {0}", krbn::constants::get_system_core_configuration_file_path()); return 1; } ofstream << ifstream.rdbuf(); return 0; } } { std::string key = "remove-system-default-profile"; if (options.count(key)) { if (getuid() != 0) { logger::get_logger().error("--{0} requires root privilege.", key); return 1; } if (!krbn::filesystem::exists(krbn::constants::get_system_core_configuration_file_path())) { logger::get_logger().error("{0} is not found.", krbn::constants::get_system_core_configuration_file_path()); return 1; } if (unlink(krbn::constants::get_system_core_configuration_file_path()) != 0) { logger::get_logger().error("Failed to unlink {0}."); return 1; } return 0; } } } catch (const cxxopts::OptionException& e) { std::cout << "error parsing options: " << e.what() << std::endl; return 2; } std::cout << options.help() << std::endl; std::cout << "Examples:" << std::endl; std::cout << " karabiner_cli --select-profile 'Default profile'" << std::endl; std::cout << std::endl; return 1; }
improve --select-profile
improve --select-profile
C++
unlicense
tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,jrolfs/Karabiner-Elements,jrolfs/Karabiner-Elements,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,jrolfs/Karabiner-Elements,jrolfs/Karabiner-Elements
650eb26f663b2beec06f92083e5722ff277f4e4e
src/body_angle_visualizer_node.cpp
src/body_angle_visualizer_node.cpp
#include <cmath> #include <string> #include <ros/ros.h> #include <geometry_msgs/Point.h> #include <rviz_visual_tools/rviz_visual_tools.h> #include <tf2_eigen/tf2_eigen.h> #include <tf2_ros/transform_listener.h> #include <Eigen/Geometry> int main(int argc, char** argv) { ros::init(argc, argv, "body_angle_visualizer"); ros::NodeHandle n {}; ros::Publisher pub {n.advertise<geometry_msgs::Point>("body_direction", 1)}; ros::Rate r {5}; tf2_ros::Buffer tfBuffer {}; tf2_ros::TransformListener tfListener {tfBuffer}; rviz_visual_tools::RvizVisualTools rvt {"openni_depth_frame", "rviz_visual_markers"}; while (ros::ok()) { try { const auto head_pos {tf2::transformToEigen(tfBuffer.lookupTransform("openni_depth_frame", "head_1", ros::Time {0}))}; const auto torso_pos {tf2::transformToEigen(tfBuffer.lookupTransform("openni_depth_frame", "torso_1", ros::Time {0}))}; const auto stand_vec {head_pos.translation() - torso_pos.translation()}; const auto stand_quaternion {Eigen::Quaterniond::FromTwoVectors(Eigen::Vector3d::UnitX(), stand_vec)}; pub.publish(tf2::toMsg(stand_vec)); rvt.deleteAllMarkers(); rvt.publishArrow(Eigen::Affine3d{stand_quaternion}); Eigen::Affine3d text_pos {}; text_pos.translation() = stand_vec; rvt.publishText(text_pos, std::to_string(stand_vec.normalized()(1)), rviz_visual_tools::WHITE, rviz_visual_tools::XLARGE); rvt.trigger(); } catch (tf2::TransformException &e) { ROS_WARN("%s", e.what()); } r.sleep(); } }
#include <cmath> #include <string> #include <ros/ros.h> #include <geometry_msgs/Point.h> #include <rviz_visual_tools/rviz_visual_tools.h> #include <tf2_eigen/tf2_eigen.h> #include <tf2_ros/transform_listener.h> #include <Eigen/Geometry> int main(int argc, char** argv) { ros::init(argc, argv, "body_angle_visualizer"); ros::NodeHandle n {}; ros::Publisher pub {n.advertise<geometry_msgs::Point>("body_direction", 1)}; ros::Rate r {5}; tf2_ros::Buffer tfBuffer {}; tf2_ros::TransformListener tfListener {tfBuffer}; rviz_visual_tools::RvizVisualTools rvt {"openni_depth_frame", "rviz_visual_markers"}; ros::NodeHandle pn {"~"}; int target_number {0}; pn.param("target_number", target_number); const auto head_name {"head_" + std::to_string(target_number)}; const auto torso_name {"torso_" + std::to_string(target_number)}; while (ros::ok()) { try { const auto head_pos {tf2::transformToEigen(tfBuffer.lookupTransform("openni_depth_frame", head_name, ros::Time{0}))}; const auto torso_pos {tf2::transformToEigen(tfBuffer.lookupTransform("openni_depth_frame", torso_name, ros::Time{0}))}; const auto stand_vec {head_pos.translation() - torso_pos.translation()}; const auto stand_quaternion {Eigen::Quaterniond::FromTwoVectors(Eigen::Vector3d::UnitX(), stand_vec)}; pub.publish(tf2::toMsg(stand_vec)); rvt.deleteAllMarkers(); rvt.publishArrow(Eigen::Affine3d{stand_quaternion}); Eigen::Affine3d text_pos {}; text_pos.translation() = stand_vec; rvt.publishText(text_pos, std::to_string(stand_vec.normalized()(1)), rviz_visual_tools::WHITE, rviz_visual_tools::XLARGE); rvt.trigger(); } catch (tf2::TransformException &e) { ROS_WARN("%s", e.what()); } r.sleep(); } }
Add param for target_number
Add param for target_number
C++
bsd-3-clause
forno/body_angle_visualizer
046c055b2b7c4ad07d21e8a3d600ad697efb0e2e
include/config_third.hpp
include/config_third.hpp
//======================================================================= // Copyright Baptiste Wicht 2015. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef WORD_SPOTTER_CONFIG_THIRD_HPP #define WORD_SPOTTER_CONFIG_THIRD_HPP namespace third { //#define CRBM_PMP_1 //One layer of CRBM with Probabilistic Max Pooling (C1) #define CRBM_PMP_2 //Two layers of CRBM with Probabilistic Max Pooling (C1/C2) //#define CRBM_PMP_3 //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3) //#define CRBM_MP_1 //One layers of CRBM with Max Pooling after each layer (C1) //#define CRBM_MP_2 //Two layers of CRBM with Max Pooling after each layer (C1/C2) //#define CRBM_MP_3 //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3) constexpr const std::size_t height = 40; //Should not be changed constexpr const std::size_t width = 220; //Should not be changed constexpr const std::size_t patch_height = 40; //Should not be changed constexpr const std::size_t patch_width = 20; constexpr const std::size_t epochs = 25; constexpr const std::size_t patch_stride = 10; constexpr const std::size_t NF1 = 9; constexpr const std::size_t K1 = 24; constexpr const std::size_t C1 = 2; constexpr const std::size_t B1 = 25; constexpr const dll::unit_type HT1 = dll::unit_type::BINARY; constexpr const dll::decay_type DT1 = dll::decay_type::L2; constexpr const dll::sparsity_method SM1 = dll::sparsity_method::LEE; constexpr const std::size_t NF2 = 3; constexpr const std::size_t K2 = 24; constexpr const std::size_t C2 = 2; constexpr const std::size_t B2 = 25; constexpr const dll::unit_type HT2 = dll::unit_type::BINARY; constexpr const dll::decay_type DT2 = dll::decay_type::L2; constexpr const dll::sparsity_method SM2 = dll::sparsity_method::LEE; constexpr const std::size_t NF3 = 3; constexpr const std::size_t K3 = 48; constexpr const std::size_t C3 = 2; constexpr const std::size_t B3 = 25; constexpr const dll::unit_type HT3 = dll::unit_type::BINARY; constexpr const dll::decay_type DT3 = dll::decay_type::L2; constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE; const auto rate_0 = [](double& value){ value = 0.5 * value; }; const auto rate_1 = [](double& value){ value = 0.5 * value; }; const auto rate_2 = [](double& value){ value = 1.0 * value; }; const auto momentum_0 = [](double& ini, double& fin){ ini = 0.88; fin = 0.88;}; const auto momentum_1 = [](double& ini, double& fin){ ini = 0.88; fin = 0.88;}; const auto momentum_2 = [](double& ini, double& fin){ ini = 1.0 * ini; fin = 1.0 * fin;}; const auto wd_l1_0 = [](double& value){ value = 1.0 * value; }; const auto wd_l1_1 = [](double& value){ value = 1.0 * value; }; const auto wd_l1_2 = [](double& value){ value = 1.0 * value; }; const auto wd_l2_0 = [](double& value){ value = 1.0 * value; }; const auto wd_l2_1 = [](double& value){ value = 1.0 * value; }; const auto wd_l2_2 = [](double& value){ value = 1.0 * value; }; const auto pbias_0 = [](double& value){ value = 1.0 * value; }; const auto pbias_1 = [](double& value){ value = 1.0 * value; }; const auto pbias_2 = [](double& value){ value = 1.0 * value; }; const auto pbias_lambda_0 = [](double& value){ value = 2.0 * value; }; const auto pbias_lambda_1 = [](double& value){ value = 2.0 * value; }; const auto pbias_lambda_2 = [](double& value){ value = 1.0 * value; }; } // end of namespace third #endif
//======================================================================= // Copyright Baptiste Wicht 2015. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef WORD_SPOTTER_CONFIG_THIRD_HPP #define WORD_SPOTTER_CONFIG_THIRD_HPP namespace third { //#define CRBM_PMP_1 //One layer of CRBM with Probabilistic Max Pooling (C1) #define CRBM_PMP_2 //Two layers of CRBM with Probabilistic Max Pooling (C1/C2) //#define CRBM_PMP_3 //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3) //#define CRBM_MP_1 //One layers of CRBM with Max Pooling after each layer (C1) //#define CRBM_MP_2 //Two layers of CRBM with Max Pooling after each layer (C1/C2) //#define CRBM_MP_3 //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3) constexpr const std::size_t height = 40; //Should not be changed constexpr const std::size_t width = 220; //Should not be changed constexpr const std::size_t patch_height = 40; //Should not be changed constexpr const std::size_t patch_width = 20; constexpr const std::size_t epochs = 50; constexpr const std::size_t patch_stride = 10; constexpr const std::size_t NF1 = 9; constexpr const std::size_t K1 = 24; constexpr const std::size_t C1 = 2; constexpr const std::size_t B1 = 25; constexpr const dll::unit_type HT1 = dll::unit_type::BINARY; constexpr const dll::decay_type DT1 = dll::decay_type::L2; constexpr const dll::sparsity_method SM1 = dll::sparsity_method::LEE; constexpr const std::size_t NF2 = 3; constexpr const std::size_t K2 = 24; constexpr const std::size_t C2 = 2; constexpr const std::size_t B2 = 25; constexpr const dll::unit_type HT2 = dll::unit_type::BINARY; constexpr const dll::decay_type DT2 = dll::decay_type::L2; constexpr const dll::sparsity_method SM2 = dll::sparsity_method::LEE; constexpr const std::size_t NF3 = 3; constexpr const std::size_t K3 = 48; constexpr const std::size_t C3 = 2; constexpr const std::size_t B3 = 25; constexpr const dll::unit_type HT3 = dll::unit_type::BINARY; constexpr const dll::decay_type DT3 = dll::decay_type::L2; constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE; const auto rate_0 = [](double& value){ value = 0.25 * value; }; const auto rate_1 = [](double& value){ value = 0.25 * value; }; const auto rate_2 = [](double& value){ value = 1.0 * value; }; const auto momentum_0 = [](double& ini, double& fin){ ini = 0.88; fin = 0.88;}; const auto momentum_1 = [](double& ini, double& fin){ ini = 0.88; fin = 0.88;}; const auto momentum_2 = [](double& ini, double& fin){ ini = 1.0 * ini; fin = 1.0 * fin;}; const auto wd_l1_0 = [](double& value){ value = 1.0 * value; }; const auto wd_l1_1 = [](double& value){ value = 1.0 * value; }; const auto wd_l1_2 = [](double& value){ value = 1.0 * value; }; const auto wd_l2_0 = [](double& value){ value = 1.0 * value; }; const auto wd_l2_1 = [](double& value){ value = 1.0 * value; }; const auto wd_l2_2 = [](double& value){ value = 1.0 * value; }; const auto pbias_0 = [](double& value){ value = 1.0 * value; }; const auto pbias_1 = [](double& value){ value = 1.0 * value; }; const auto pbias_2 = [](double& value){ value = 1.0 * value; }; const auto pbias_lambda_0 = [](double& value){ value = 2.0 * value; }; const auto pbias_lambda_1 = [](double& value){ value = 2.0 * value; }; const auto pbias_lambda_2 = [](double& value){ value = 1.0 * value; }; } // end of namespace third #endif
Change standard
Change standard
C++
mit
wichtounet/word_spotting,wichtounet/word_spotting,wichtounet/word_spotting
2fe1532926ec3ab17715e927045e88e7ae70b316
unittest/heap_test.cc
unittest/heap_test.cc
// (C) Copyright 2017, 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 <string> #include <utility> #include "doubleptr.h" #include "genericheap.h" #include <tesseract/genericvector.h> #include "kdpair.h" #include "include_gunit.h" namespace tesseract { int test_data[] = {8, 1, 2, -4, 7, 9, 65536, 4, 9, 0}; // The fixture for testing GenericHeap and DoublePtr. class HeapTest : public testing::Test { protected: void SetUp() { std::locale::global(std::locale("")); } public: virtual ~HeapTest(); // Pushes the test data onto both the heap and the KDVector. void PushTestData(GenericHeap<IntKDPair>* heap, KDVector* v) { for (size_t i = 0; i < ARRAYSIZE(test_data); ++i) { IntKDPair pair(test_data[i], i); heap->Push(&pair); v->push_back(pair); } } // Verifies that the data in the heap matches the vector (after sorting) by // popping everything off the heap. void VerifyHeapVectorMatch(GenericHeap<IntKDPair>* heap, KDVector* v) { EXPECT_FALSE(heap->empty()); EXPECT_EQ(heap->size(), v->size()); // Sort the vector and check that the keys come out of the heap in the same // order as v. // Also check that the indices match, except for 9, which is duplicated. v->sort(); // Check that we have increasing order. EXPECT_LT((*v)[0].key, v->back().key); for (int i = 0; i < v->size(); ++i) { EXPECT_EQ((*v)[i].key, heap->PeekTop().key); // Indices don't necessarily match for equal keys, so don't test them. if (i + 1 < v->size() && (*v)[i + 1].key == (*v)[i].key) { while (i + 1 < v->size() && (*v)[i + 1].key == (*v)[i].key) { heap->Pop(nullptr); ++i; EXPECT_FALSE(heap->empty()); EXPECT_EQ((*v)[i].key, heap->PeekTop().key); } } else { // The indices must also match if the key is unique. EXPECT_EQ((*v)[i].data, heap->PeekTop().data); } EXPECT_FALSE(heap->empty()); EXPECT_TRUE(heap->Pop(nullptr)); } EXPECT_TRUE(heap->empty()); } }; // Destructor. // It is defined here, so the compiler can create a single vtable // instead of a weak vtable (fixes compiler warning). HeapTest::~HeapTest() = default; // Tests that a sort using a GenericHeap matches the result of a sort using // a KDVector. TEST_F(HeapTest, SortTest) { GenericHeap<IntKDPair> heap; EXPECT_TRUE(heap.empty()); KDVector v; EXPECT_EQ(heap.size(), v.size()); // Push the test data onto both the heap and the KDVector. PushTestData(&heap, &v); VerifyHeapVectorMatch(&heap, &v); } // Tests that pushing some stuff, popping some stuff, and then pushing more // stuff results in output that matches the sort using a KDVector. // a KDVector. TEST_F(HeapTest, MixedTest) { GenericHeap<IntKDPair> heap; KDVector v; // Push the test data onto both the heap and the KDVector. PushTestData(&heap, &v); // Sort the vector and remove the first 5 values from both heap and v. v.sort(); for (int i = 0; i < 5; ++i) { heap.Pop(nullptr); v.remove(0); } // Push the test data onto both the heap and the KDVector. PushTestData(&heap, &v); // Heap and vector should still match! VerifyHeapVectorMatch(&heap, &v); } // Tests that PopWorst still leaves the heap in a state such that it still // matches a sorted KDVector. TEST_F(HeapTest, PopWorstTest) { GenericHeap<IntKDPair> heap; KDVector v; // Push the test data onto both the heap and the KDVector. PushTestData(&heap, &v); // Get the worst element off the heap. IntKDPair pair; heap.PopWorst(&pair); EXPECT_EQ(pair.key, 65536); EXPECT_EQ(pair.data, 6); // Sort and remove the worst element from the vector. v.sort(); v.truncate(v.size() - 1); // After that they should still match! VerifyHeapVectorMatch(&heap, &v); } // Tests that Reshuffle works and the heap still matches a KDVector with the // same value changed. Doubles up as a test of DoublePtr. TEST_F(HeapTest, RevalueTest) { // Here the data element of the pair is a DoublePtr, which links the entries // in the vector and heap, and we test a MAX heap. typedef KDPairDec<int, DoublePtr> PtrPair; GenericHeap<PtrPair> heap; GenericVector<PtrPair> v; // Push the test data onto both the heap and the vector. for (size_t i = 0; i < ARRAYSIZE(test_data); ++i) { PtrPair h_pair; h_pair.key = test_data[i]; PtrPair v_pair; v_pair.key = test_data[i]; h_pair.data.Connect(&v_pair.data); heap.Push(&h_pair); v.push_back(v_pair); } // Test changes both ways. Index 0 is 8, so change it to -1. v[0].key = -1; // v[0].data.OtherEnd() is a pointer to the data element in the appropriate // heap entry, wherever it may be. We can change its value via that pointer. // Without Reshuffle, that would be a terribly bad thing to do, as it violates // the heap invariant, making the heap corrupt. PtrPair* pair_ptr = PtrPair::RecastDataPointer(v[0].data.OtherEnd()); pair_ptr->key = v[0].key; heap.Reshuffle(pair_ptr); // Index 1 is 1. Change to 32767. v[1].key = 32767; pair_ptr = PtrPair::RecastDataPointer(v[1].data.OtherEnd()); pair_ptr->key = v[1].key; heap.Reshuffle(pair_ptr); // After the changes, popping the heap should still match the sorted order // of the vector. v.sort(); EXPECT_GT(v[0].key, v.back().key); for (int i = 0; i < v.size(); ++i) { EXPECT_EQ(v[i].key, heap.PeekTop().key); EXPECT_FALSE(heap.empty()); heap.Pop(nullptr); } EXPECT_TRUE(heap.empty()); } #if 0 // Helper checks that the compiler rejects use of a copy constructor with // a const argument and the default copy constructor is properly hidden by // the non-const version. static void ConstRefTest(const DoublePtr& ptr1) { DoublePtr ptr2(ptr1); // Compiler error here. EXPECT_EQ(&ptr2, ptr2.OtherEnd()->OtherEnd()); EXPECT_TRUE(ptr1.OtherEnd() == nullptr); } #endif // Tests that DoublePtr works as expected. TEST_F(HeapTest, DoublePtrTest) { DoublePtr ptr1; DoublePtr ptr2; ptr1.Connect(&ptr2); // Check that the correct copy constructor is used. DoublePtr ptr3(ptr1); EXPECT_EQ(&ptr3, ptr3.OtherEnd()->OtherEnd()); EXPECT_TRUE(ptr1.OtherEnd() == nullptr); // Check that the correct operator= is used. ptr1 = ptr3; EXPECT_EQ(&ptr1, ptr1.OtherEnd()->OtherEnd()); EXPECT_TRUE(ptr3.OtherEnd() == nullptr); } } // namespace tesseract
// (C) Copyright 2017, 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 <string> #include <utility> #include "doubleptr.h" #include "genericheap.h" #include <tesseract/genericvector.h> #include "kdpair.h" #include "include_gunit.h" namespace tesseract { int test_data[] = {8, 1, 2, -4, 7, 9, 65536, 4, 9, 0}; // The fixture for testing GenericHeap and DoublePtr. class HeapTest : public testing::Test { protected: void SetUp() { std::locale::global(std::locale("")); } public: virtual ~HeapTest(); // Pushes the test data onto both the heap and the KDVector. void PushTestData(GenericHeap<IntKDPair>* heap, KDVector* v) { for (size_t i = 0; i < ARRAYSIZE(test_data); ++i) { IntKDPair pair(test_data[i], i); heap->Push(&pair); v->push_back(pair); } } // Verifies that the data in the heap matches the vector (after sorting) by // popping everything off the heap. void VerifyHeapVectorMatch(GenericHeap<IntKDPair>* heap, KDVector* v) { EXPECT_FALSE(heap->empty()); EXPECT_EQ(heap->size(), v->size()); // Sort the vector and check that the keys come out of the heap in the same // order as v. // Also check that the indices match, except for 9, which is duplicated. v->sort(); // Check that we have increasing order. EXPECT_LT((*v)[0].key(), v->back().key()); for (int i = 0; i < v->size(); ++i) { EXPECT_EQ((*v)[i].key(), heap->PeekTop().key()); // Indices don't necessarily match for equal keys, so don't test them. if (i + 1 < v->size() && (*v)[i + 1].key() == (*v)[i].key()) { while (i + 1 < v->size() && (*v)[i + 1].key() == (*v)[i].key()) { heap->Pop(nullptr); ++i; EXPECT_FALSE(heap->empty()); EXPECT_EQ((*v)[i].key(), heap->PeekTop().key()); } } else { // The indices must also match if the key is unique. EXPECT_EQ((*v)[i].data(), heap->PeekTop().data()); } EXPECT_FALSE(heap->empty()); EXPECT_TRUE(heap->Pop(nullptr)); } EXPECT_TRUE(heap->empty()); } }; // Destructor. // It is defined here, so the compiler can create a single vtable // instead of a weak vtable (fixes compiler warning). HeapTest::~HeapTest() = default; // Tests that a sort using a GenericHeap matches the result of a sort using // a KDVector. TEST_F(HeapTest, SortTest) { GenericHeap<IntKDPair> heap; EXPECT_TRUE(heap.empty()); KDVector v; EXPECT_EQ(heap.size(), v.size()); // Push the test data onto both the heap and the KDVector. PushTestData(&heap, &v); VerifyHeapVectorMatch(&heap, &v); } // Tests that pushing some stuff, popping some stuff, and then pushing more // stuff results in output that matches the sort using a KDVector. // a KDVector. TEST_F(HeapTest, MixedTest) { GenericHeap<IntKDPair> heap; KDVector v; // Push the test data onto both the heap and the KDVector. PushTestData(&heap, &v); // Sort the vector and remove the first 5 values from both heap and v. v.sort(); for (int i = 0; i < 5; ++i) { heap.Pop(nullptr); v.remove(0); } // Push the test data onto both the heap and the KDVector. PushTestData(&heap, &v); // Heap and vector should still match! VerifyHeapVectorMatch(&heap, &v); } // Tests that PopWorst still leaves the heap in a state such that it still // matches a sorted KDVector. TEST_F(HeapTest, PopWorstTest) { GenericHeap<IntKDPair> heap; KDVector v; // Push the test data onto both the heap and the KDVector. PushTestData(&heap, &v); // Get the worst element off the heap. IntKDPair pair; heap.PopWorst(&pair); EXPECT_EQ(pair.key(), 65536); EXPECT_EQ(pair.data(), 6); // Sort and remove the worst element from the vector. v.sort(); v.truncate(v.size() - 1); // After that they should still match! VerifyHeapVectorMatch(&heap, &v); } // Tests that Reshuffle works and the heap still matches a KDVector with the // same value changed. Doubles up as a test of DoublePtr. TEST_F(HeapTest, RevalueTest) { // Here the data element of the pair is a DoublePtr, which links the entries // in the vector and heap, and we test a MAX heap. typedef KDPairDec<int, DoublePtr> PtrPair; GenericHeap<PtrPair> heap; GenericVector<PtrPair> v; // Push the test data onto both the heap and the vector. for (size_t i = 0; i < ARRAYSIZE(test_data); ++i) { PtrPair h_pair; h_pair.key() = test_data[i]; PtrPair v_pair; v_pair.key() = test_data[i]; h_pair.data().Connect(&v_pair.data()); heap.Push(&h_pair); v.push_back(v_pair); } // Test changes both ways. Index 0 is 8, so change it to -1. v[0].key() = -1; // v[0].data.OtherEnd() is a pointer to the data element in the appropriate // heap entry, wherever it may be. We can change its value via that pointer. // Without Reshuffle, that would be a terribly bad thing to do, as it violates // the heap invariant, making the heap corrupt. PtrPair* pair_ptr = reinterpret_cast<PtrPair*>(v[0].data().OtherEnd()); pair_ptr->key() = v[0].key(); heap.Reshuffle(pair_ptr); // Index 1 is 1. Change to 32767. v[1].key() = 32767; pair_ptr = reinterpret_cast<PtrPair*>(v[1].data().OtherEnd()); pair_ptr->key() = v[1].key(); heap.Reshuffle(pair_ptr); // After the changes, popping the heap should still match the sorted order // of the vector. v.sort(); EXPECT_GT(v[0].key(), v.back().key()); for (int i = 0; i < v.size(); ++i) { EXPECT_EQ(v[i].key(), heap.PeekTop().key()); EXPECT_FALSE(heap.empty()); heap.Pop(nullptr); } EXPECT_TRUE(heap.empty()); } #if 0 // Helper checks that the compiler rejects use of a copy constructor with // a const argument and the default copy constructor is properly hidden by // the non-const version. static void ConstRefTest(const DoublePtr& ptr1) { DoublePtr ptr2(ptr1); // Compiler error here. EXPECT_EQ(&ptr2, ptr2.OtherEnd()->OtherEnd()); EXPECT_TRUE(ptr1.OtherEnd() == nullptr); } #endif // Tests that DoublePtr works as expected. TEST_F(HeapTest, DoublePtrTest) { DoublePtr ptr1; DoublePtr ptr2; ptr1.Connect(&ptr2); // Check that the correct copy constructor is used. DoublePtr ptr3(ptr1); EXPECT_EQ(&ptr3, ptr3.OtherEnd()->OtherEnd()); EXPECT_TRUE(ptr1.OtherEnd() == nullptr); // Check that the correct operator= is used. ptr1 = ptr3; EXPECT_EQ(&ptr1, ptr1.OtherEnd()->OtherEnd()); EXPECT_TRUE(ptr3.OtherEnd() == nullptr); } } // namespace tesseract
Fix some compiler errors for heap_test (more remaining)
Fix some compiler errors for heap_test (more remaining) Signed-off-by: Stefan Weil <[email protected]>
C++
apache-2.0
amitdo/tesseract,UB-Mannheim/tesseract,UB-Mannheim/tesseract,stweil/tesseract,stweil/tesseract,UB-Mannheim/tesseract,amitdo/tesseract,amitdo/tesseract,tesseract-ocr/tesseract,tesseract-ocr/tesseract,tesseract-ocr/tesseract,stweil/tesseract,amitdo/tesseract,tesseract-ocr/tesseract,stweil/tesseract,amitdo/tesseract,tesseract-ocr/tesseract,UB-Mannheim/tesseract,UB-Mannheim/tesseract,stweil/tesseract
b3f36153243afca4e05acac323848003257a8788
include/mettle/suite.hpp
include/mettle/suite.hpp
#ifndef INC_METTLE_SUITE_HPP #define INC_METTLE_SUITE_HPP #include <algorithm> #include <functional> #include <memory> #include <string> #include <utility> #include <vector> namespace mettle { namespace detail { template<size_t ...> struct index_sequence {}; template<size_t N, size_t ...S> struct make_index_seq_impl : make_index_seq_impl<N-1, N-1, S...> { }; template<size_t ...S> struct make_index_seq_impl<0, S...> { typedef index_sequence<S...> type; }; template<size_t I> using make_index_sequence = typename make_index_seq_impl<I>::type; template <typename F, typename Tuple, size_t... I> auto apply_impl(F &&f, Tuple &&t, index_sequence<I...>) { return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...); } template<typename F, typename Tuple> auto apply(F &&f, Tuple &&t) { using Indices = make_index_sequence< std::tuple_size<typename std::decay<Tuple>::type>::value >; return apply_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices()); } } struct test_result { bool passed; std::string message; }; template<typename Ret, typename ...T> struct compiled_suite { struct test_info { using function_type = std::function<Ret(T&...)>; test_info(const std::string &name, const function_type &function, bool skip = false) : name(name), function(function), skip(skip) {} std::string name; function_type function; bool skip; }; using iterator = typename std::vector<test_info>::const_iterator; template<typename U, typename V, typename Func> compiled_suite(const std::string &name, const U &tests, const V &subsuites, const Func &f) : name_(name) { for(auto &test : tests) tests_.push_back(f(test)); for(auto &ss : subsuites) subsuites_.push_back(compiled_suite(ss, f)); } template<typename Ret2, typename ...T2, typename Func> compiled_suite(const compiled_suite<Ret2, T2...> &suite, const Func &f) : name_(suite.name()) { for(auto &test : suite) tests_.push_back(f(test)); for(auto &ss : suite.subsuites()) subsuites_.push_back(compiled_suite(ss, f)); } const std::string & name() const { return name_; } iterator begin() const { return tests_.begin(); } iterator end() const { return tests_.end(); } size_t size() const { return tests_.size(); } const std::vector<compiled_suite> & subsuites() const { return subsuites_; } private: std::string name_; std::vector<test_info> tests_; std::vector<compiled_suite> subsuites_; }; using runnable_suite = compiled_suite<test_result>; template<typename Parent, typename ...T> class subsuite_builder; template<typename ...T> class suite_builder_base { public: using raw_function_type = void(T&...); using function_type = std::function<raw_function_type>; using tuple_type = std::tuple<T...>; suite_builder_base(const std::string &name) : name_(name) {} suite_builder_base(const suite_builder_base &) = delete; suite_builder_base & operator =(const suite_builder_base &) = delete; void setup(const function_type &f) { setup_ = f; } void teardown(const function_type &f) { teardown_ = f; } void skip_test(const std::string &name, const function_type &f) { tests_.push_back({name, f, true}); } void test(const std::string &name, const function_type &f) { tests_.push_back({name, f, false}); } void subsuite(const compiled_suite<void, T...> &subsuite) { subsuites_.push_back(subsuite); } void subsuite(compiled_suite<void, T...> &&subsuite) { subsuites_.push_back(std::move(subsuite)); } template<typename ...U, typename F> void subsuite(const std::string &name, const F &f) { subsuite_builder<tuple_type, U...> builder(name); f(builder); subsuite(builder.finalize()); } protected: struct test_info { std::string name; function_type function; bool skip; }; std::string name_; function_type setup_, teardown_; std::vector<test_info> tests_; std::vector<compiled_suite<void, T...>> subsuites_; }; template<typename ...T, typename ...U> class subsuite_builder<std::tuple<T...>, U...> : public suite_builder_base<T..., U...> { private: using compiled_suite_type = compiled_suite<void, T...>; using base = suite_builder_base<T..., U...>; public: using base::base; compiled_suite_type finalize() const { return compiled_suite_type( base::name_, base::tests_, base::subsuites_, [this](const auto &a) { return wrap_test(a); } ); } private: template<typename V> typename compiled_suite_type::test_info wrap_test(const V &test) const { auto &f = test.function; auto &setup = base::setup_; auto &teardown = base::teardown_; typename compiled_suite_type::test_info::function_type test_function = [ f, setup, teardown ](T &...args) -> void { std::tuple<T&..., U...> fixtures(args..., U()...); if(setup) detail::apply(setup, fixtures); detail::apply(f, fixtures); if(teardown) detail::apply(teardown, fixtures); }; return { test.name, test_function, test.skip }; } }; template<typename Exception, typename ...T> class suite_builder : public suite_builder_base<T...> { private: using base = suite_builder_base<T...>; public: using exception_type = Exception; using base::base; runnable_suite finalize() const { return runnable_suite( base::name_, base::tests_, base::subsuites_, [this](const auto &a) { return wrap_test(a); } ); } private: template<typename U> runnable_suite::test_info wrap_test(const U &test) const { auto &f = test.function; auto &setup = base::setup_; auto &teardown = base::teardown_; runnable_suite::test_info::function_type test_function = [ f, setup, teardown ]() -> test_result { bool passed = false; std::string message; try { std::tuple<T...> fixtures; if(setup) detail::apply(setup, fixtures); detail::apply(f, fixtures); if(teardown) detail::apply(teardown, fixtures); passed = true; } catch(const exception_type &e) { message = e.what(); } catch(...) { message = "unknown error"; } return { passed, message }; }; return { test.name, test_function, test.skip }; } }; template<typename Exception, typename ...T, typename F> runnable_suite make_basic_suite(const std::string &name, const F &f) { suite_builder<Exception, T...> builder(name); f(builder); return builder.finalize(); } template<typename T, typename ...U, typename F> auto make_subsuite(const std::string &name, const F &f) { subsuite_builder<T, U...> builder(name); f(builder); return builder.finalize(); } template<typename ...T, typename Parent, typename F> auto make_subsuite(const Parent &, const std::string &name, const F &f) { return make_subsuite<typename Parent::tuple_type, T...>(name, f); } template<typename ...T, typename Parent, typename F> void subsuite(Parent &builder, const std::string &name, const F &f) { builder.subsuite(make_subsuite<T...>(builder, name, f)); } } // namespace mettle #endif
#ifndef INC_METTLE_SUITE_HPP #define INC_METTLE_SUITE_HPP #include <algorithm> #include <functional> #include <memory> #include <string> #include <utility> #include <vector> namespace mettle { namespace detail { template<size_t ...> struct index_sequence {}; template<size_t N, size_t ...S> struct make_index_seq_impl : make_index_seq_impl<N-1, N-1, S...> { }; template<size_t ...S> struct make_index_seq_impl<0, S...> { typedef index_sequence<S...> type; }; template<size_t I> using make_index_sequence = typename make_index_seq_impl<I>::type; template <typename F, typename Tuple, size_t... I> auto apply_impl(F &&f, Tuple &&t, index_sequence<I...>) { return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...); } template<typename F, typename Tuple> auto apply(F &&f, Tuple &&t) { using Indices = make_index_sequence< std::tuple_size<typename std::decay<Tuple>::type>::value >; return apply_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices()); } } struct test_result { bool passed; std::string message; }; template<typename Ret, typename ...T> struct compiled_suite { struct test_info { using function_type = std::function<Ret(T&...)>; test_info(const std::string &name, const function_type &function, bool skip = false) : name(name), function(function), skip(skip) {} std::string name; function_type function; bool skip; }; using iterator = typename std::vector<test_info>::const_iterator; template<typename U, typename V, typename Func> compiled_suite(const std::string &name, const U &tests, const V &subsuites, const Func &f) : name_(name) { for(auto &test : tests) tests_.push_back(f(test)); for(auto &ss : subsuites) subsuites_.push_back(compiled_suite(ss, f)); } template<typename Ret2, typename ...T2, typename Func> compiled_suite(const compiled_suite<Ret2, T2...> &suite, const Func &f) : name_(suite.name()) { for(auto &test : suite) tests_.push_back(f(test)); for(auto &ss : suite.subsuites()) subsuites_.push_back(compiled_suite(ss, f)); } const std::string & name() const { return name_; } iterator begin() const { return tests_.begin(); } iterator end() const { return tests_.end(); } size_t size() const { return tests_.size(); } const std::vector<compiled_suite> & subsuites() const { return subsuites_; } private: std::string name_; std::vector<test_info> tests_; std::vector<compiled_suite> subsuites_; }; using runnable_suite = compiled_suite<test_result>; template<typename Parent, typename ...T> class subsuite_builder; template<typename ...T> class suite_builder_base { public: using raw_function_type = void(T&...); using function_type = std::function<raw_function_type>; using tuple_type = std::tuple<T...>; suite_builder_base(const std::string &name) : name_(name) {} suite_builder_base(const suite_builder_base &) = delete; suite_builder_base & operator =(const suite_builder_base &) = delete; void setup(const function_type &f) { setup_ = f; } void teardown(const function_type &f) { teardown_ = f; } void skip_test(const std::string &name, const function_type &f) { tests_.push_back({name, f, true}); } void test(const std::string &name, const function_type &f) { tests_.push_back({name, f, false}); } void subsuite(const compiled_suite<void, T...> &subsuite) { subsuites_.push_back(subsuite); } void subsuite(compiled_suite<void, T...> &&subsuite) { subsuites_.push_back(std::move(subsuite)); } template<typename ...U, typename F> void subsuite(const std::string &name, const F &f) { subsuite_builder<tuple_type, U...> builder(name); f(builder); subsuite(builder.finalize()); } protected: struct test_info { std::string name; function_type function; bool skip; }; std::string name_; function_type setup_, teardown_; std::vector<test_info> tests_; std::vector<compiled_suite<void, T...>> subsuites_; }; template<typename ...T, typename ...U> class subsuite_builder<std::tuple<T...>, U...> : public suite_builder_base<T..., U...> { private: using compiled_suite_type = compiled_suite<void, T...>; using base = suite_builder_base<T..., U...>; public: using base::base; compiled_suite_type finalize() const { return compiled_suite_type( base::name_, base::tests_, base::subsuites_, [this](const auto &a) { return wrap_test(a); } ); } private: template<typename V> typename compiled_suite_type::test_info wrap_test(const V &test) const { auto &f = test.function; auto &setup = base::setup_; auto &teardown = base::teardown_; typename compiled_suite_type::test_info::function_type test_function = [ f, setup, teardown ](T &...args) -> void { std::tuple<T&..., U...> fixtures(args..., U()...); if(setup) detail::apply(setup, fixtures); detail::apply(f, fixtures); if(teardown) detail::apply(teardown, fixtures); }; return { test.name, test_function, test.skip }; } }; template<typename Exception, typename ...T> class suite_builder : public suite_builder_base<T...> { private: using base = suite_builder_base<T...>; public: using exception_type = Exception; using base::base; runnable_suite finalize() const { return runnable_suite( base::name_, base::tests_, base::subsuites_, [this](const auto &a) { return wrap_test(a); } ); } private: template<typename U> runnable_suite::test_info wrap_test(const U &test) const { auto &f = test.function; auto &setup = base::setup_; auto &teardown = base::teardown_; runnable_suite::test_info::function_type test_function = [ f, setup, teardown ]() -> test_result { bool passed = false; std::string message; try { std::tuple<T...> fixtures; if(setup) detail::apply(setup, fixtures); detail::apply(f, fixtures); if(teardown) detail::apply(teardown, fixtures); passed = true; } catch(const exception_type &e) { message = e.what(); } catch(const std::exception &e) { message = std::string("Uncaught exception: ") + e.what(); } catch(...) { message = "Unknown exception"; } return { passed, message }; }; return { test.name, test_function, test.skip }; } }; template<typename Exception, typename ...T, typename F> runnable_suite make_basic_suite(const std::string &name, const F &f) { suite_builder<Exception, T...> builder(name); f(builder); return builder.finalize(); } template<typename T, typename ...U, typename F> auto make_subsuite(const std::string &name, const F &f) { subsuite_builder<T, U...> builder(name); f(builder); return builder.finalize(); } template<typename ...T, typename Parent, typename F> auto make_subsuite(const Parent &, const std::string &name, const F &f) { return make_subsuite<typename Parent::tuple_type, T...>(name, f); } template<typename ...T, typename Parent, typename F> void subsuite(Parent &builder, const std::string &name, const F &f) { builder.subsuite(make_subsuite<T...>(builder, name, f)); } } // namespace mettle #endif
Print out messages from uncaught exceptions
Print out messages from uncaught exceptions
C++
bsd-3-clause
jimporter/mettle,jimporter/mettle
ea4555100a9079f1729afabdd7046d1826b052fd
jvmfwk/plugins/sunmajor/javaenvsetup/javaldx.cxx
jvmfwk/plugins/sunmajor/javaenvsetup/javaldx.cxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "sal/main.h" #include "sal/types.h" #include "osl/thread.h" #include "rtl/ustring.hxx" #include "rtl/byteseq.hxx" #include "jvmfwk/framework.h" using ::rtl::OUString; using ::rtl::OUStringToOString; using ::rtl::OString; static sal_Bool hasOption(char const * szOption, int argc, char** argv); static rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData); static bool findAndSelect(JavaInfo**); #define HELP_TEXT \ "\njavaldx is necessary to make Java work on some UNIX platforms." \ "It prints a string to std out that consists of directories which " \ "have to be included into the LD_LIBRARY_PATH variable.The setting of " \ "the variable usually occurs in a shell script that runs javaldx.\n" \ "The directories are from the chosen java installation. \n" \ "Options are: \n"\ "--help or -h\n" SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv) { if( hasOption("--help",argc, argv) || hasOption("-h", argc, argv)) { fprintf(stdout, HELP_TEXT);// default return 0; } javaFrameworkError errcode = JFW_E_NONE; sal_Bool bEnabled = sal_False; errcode = jfw_getEnabled( & bEnabled); if (errcode == JFW_E_NONE && bEnabled == sal_False) { //Do not do any preparation because that may only slow startup time. return 0; } else if (errcode != JFW_E_NONE && errcode != JFW_E_DIRECT_MODE) { fprintf(stderr,"javaldx failed! \n"); return -1; } JavaInfo * pInfo = NULL; errcode = jfw_getSelectedJRE( & pInfo); if (errcode != JFW_E_NONE && errcode != JFW_E_INVALID_SETTINGS) { fprintf(stderr,"javaldx failed! \n"); return -1; } if (pInfo == NULL) { if (false == findAndSelect(&pInfo)) return -1; } else { //check if the JRE was not uninstalled sal_Bool bExist = sal_False; errcode = jfw_existJRE(pInfo, &bExist); if (errcode == JFW_E_NONE) { if (!bExist && !findAndSelect(&pInfo)) return -1; } else { fprintf(stderr, "javaldx: Could not determine if JRE still exist\n"); return -1; } } rtl::OUString aVendor( pInfo->sVendor ); // Only do something if the sunjavaplugin created this JavaInfo if ( aVendor != "Sun Microsystems Inc." && aVendor != "Oracle Corporation" && aVendor != "IBM Corporation" && aVendor != "Blackdown Java-Linux Team" && aVendor != "Apple Inc." && aVendor != "Apple Computer, Inc." && aVendor != "BEA Systems, Inc." && aVendor != "Free Software Foundation, Inc." && aVendor != "The FreeBSD Foundation" ) return 0; rtl::OString sPaths = getLD_LIBRARY_PATH(pInfo->arVendorData); fprintf(stdout, "%s\n", sPaths.getStr()); jfw_freeJavaInfo(pInfo); return 0; } rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData) { const sal_Unicode* chars = (sal_Unicode*) vendorData.getConstArray(); sal_Int32 len = vendorData.getLength(); rtl::OUString sData(chars, len / 2); //the runtime lib is on the first line sal_Int32 index = 0; rtl::OUString aToken = sData.getToken( 1, '\n', index); rtl::OString paths = rtl::OUStringToOString(aToken, osl_getThreadTextEncoding()); return paths; } static sal_Bool hasOption(char const * szOption, int argc, char** argv) { sal_Bool retVal= sal_False; for(sal_Int16 i= 1; i < argc; i++) { if( ! strcmp(argv[i], szOption)) { retVal= sal_True; break; } } return retVal; } static bool findAndSelect(JavaInfo ** ppInfo) { javaFrameworkError errcode = jfw_findAndSelectJRE(ppInfo); if (errcode == JFW_E_NO_JAVA_FOUND) { fprintf(stderr,"javaldx: Could not find a Java Runtime Environment! \n"); return false; } else if (errcode != JFW_E_NONE && errcode != JFW_E_DIRECT_MODE) { fprintf(stderr,"javaldx failed!\n"); return false; } return true; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "sal/main.h" #include "sal/types.h" #include "osl/thread.h" #include "rtl/ustring.hxx" #include "rtl/byteseq.hxx" #include "jvmfwk/framework.h" using ::rtl::OUString; using ::rtl::OUStringToOString; using ::rtl::OString; static sal_Bool hasOption(char const * szOption, int argc, char** argv); static rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData); static bool findAndSelect(JavaInfo**); #define HELP_TEXT \ "\njavaldx is necessary to make Java work on some UNIX platforms." \ "It prints a string to std out that consists of directories which " \ "have to be included into the LD_LIBRARY_PATH variable.The setting of " \ "the variable usually occurs in a shell script that runs javaldx.\n" \ "The directories are from the chosen java installation. \n" \ "Options are: \n"\ "--help or -h\n" SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv) { if( hasOption("--help",argc, argv) || hasOption("-h", argc, argv)) { fprintf(stdout, HELP_TEXT);// default return 0; } javaFrameworkError errcode = JFW_E_NONE; sal_Bool bEnabled = sal_False; errcode = jfw_getEnabled( & bEnabled); if (errcode == JFW_E_NONE && bEnabled == sal_False) { //Do not do any preparation because that may only slow startup time. return 0; } else if (errcode != JFW_E_NONE && errcode != JFW_E_DIRECT_MODE) { fprintf(stderr,"javaldx failed! \n"); return -1; } JavaInfo * pInfo = NULL; errcode = jfw_getSelectedJRE( & pInfo); if (errcode != JFW_E_NONE && errcode != JFW_E_INVALID_SETTINGS) { fprintf(stderr,"javaldx failed! \n"); return -1; } if (pInfo == NULL) { if (false == findAndSelect(&pInfo)) return -1; } else { //check if the JRE was not uninstalled sal_Bool bExist = sal_False; errcode = jfw_existJRE(pInfo, &bExist); if (errcode == JFW_E_NONE) { if (!bExist && !findAndSelect(&pInfo)) return -1; } else { fprintf(stderr, "javaldx: Could not determine if JRE still exist\n"); return -1; } } rtl::OUString aVendor( pInfo->sVendor ); // Only do something if the sunjavaplugin created this JavaInfo if ( aVendor != "Sun Microsystems Inc." && aVendor != "Oracle Corporation" && aVendor != "IBM Corporation" && aVendor != "Blackdown Java-Linux Team" && aVendor != "Apple Inc." && aVendor != "Apple Computer, Inc." && aVendor != "BEA Systems, Inc." && aVendor != "Free Software Foundation, Inc." && aVendor != "The FreeBSD Foundation" ) { jfw_freeJavaInfo(pInfo); return 0; } rtl::OString sPaths = getLD_LIBRARY_PATH(pInfo->arVendorData); fprintf(stdout, "%s\n", sPaths.getStr()); jfw_freeJavaInfo(pInfo); return 0; } rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData) { const sal_Unicode* chars = (sal_Unicode*) vendorData.getConstArray(); sal_Int32 len = vendorData.getLength(); rtl::OUString sData(chars, len / 2); //the runtime lib is on the first line sal_Int32 index = 0; rtl::OUString aToken = sData.getToken( 1, '\n', index); rtl::OString paths = rtl::OUStringToOString(aToken, osl_getThreadTextEncoding()); return paths; } static sal_Bool hasOption(char const * szOption, int argc, char** argv) { sal_Bool retVal= sal_False; for(sal_Int16 i= 1; i < argc; i++) { if( ! strcmp(argv[i], szOption)) { retVal= sal_True; break; } } return retVal; } static bool findAndSelect(JavaInfo ** ppInfo) { javaFrameworkError errcode = jfw_findAndSelectJRE(ppInfo); if (errcode == JFW_E_NO_JAVA_FOUND) { fprintf(stderr,"javaldx: Could not find a Java Runtime Environment! \n"); return false; } else if (errcode != JFW_E_NONE && errcode != JFW_E_DIRECT_MODE) { fprintf(stderr,"javaldx failed!\n"); return false; } return true; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
fix memory leak
coverity#705669: fix memory leak Change-Id: Ib99c5e5c4a8c3c6efd0ff0665c73b241790b314b
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
c1797bb79d65af6426cacde24a02b9bdef464c2b
src/character/classes/class.cpp
src/character/classes/class.cpp
#include "character/classes/class.h" namespace d20 { bool Class::operator==(const Class &other) const { this->get_name() == other.get_name(); } float Class::bab_progression() const { throw("called bab_progression on class base!"); } std::string Class::get_name() const { throw("called get_name on class base!"); } }
#include "character/classes/class.h" namespace d20 { bool Class::operator==(const Class &other) const { return this->get_name() == other.get_name(); } float Class::bab_progression() const { throw("called bab_progression on class base!"); } std::string Class::get_name() const { throw("called get_name on class base!"); } }
Fix warning missing return statement
Fix warning missing return statement
C++
mit
fotanus/libd20,fotanus/libd20,fotanus/libd20
19186440316c692b88952fff8b4b35a50591fc07
examples/synch.cc
examples/synch.cc
#include "ten/synchronized.hh" #include <iostream> using namespace ten; class A { private: int i; int i_squared; public: A(int _i=0) { set(_i); } void set(int _i) { i = _i; i_squared = i*i; } int get_squared() { return i_squared; } }; int main() { synchronized<A> a(1); A b; synchronize(a, [&](A &a_) { a_.set(2); b = a_; }); synchronize(a, [](A &a_) { a_.set(3); std::cout << "a: " << a_.get_squared() << "\n"; }); std::cout << "b: " << b.get_squared() << "\n"; }
#include "ten/synchronized.hh" #include <iostream> using namespace ten; class A { private: int i; int i_squared; public: A(int _i=0) { set(_i); } void set(int _i) { i = _i; i_squared = i*i; } int get_squared() { return i_squared; } }; int main() { synchronized<A> a(1); A b; a([&](A &a_) { a_.set(2); b = a_; }); a([](A &a_) { a_.set(3); std::cout << "a: " << a_.get_squared() << "\n"; }); std::cout << "b: " << b.get_squared() << "\n"; }
fix sync changes
fix sync changes
C++
apache-2.0
toffaletti/libten,toffaletti/libten,toffaletti/libten,toffaletti/libten,toffaletti/libten
1651032cee143aa4741ebca17417da6c6789ab0e
src/common/integer_parent_type.cpp
src/common/integer_parent_type.cpp
//===----------------------------------------------------------------------===// // // Peloton // // numeric_value.cpp // // Identification: src/backend/common/numeric_value.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "common/integer_parent_type.h" #include <cmath> #include <iostream> #include "common/boolean_type.h" #include "common/decimal_type.h" #include "common/varlen_type.h" namespace peloton { namespace common { IntegerParentType::IntegerParentType(TypeId type) : NumericType(type) { } Value IntegerParentType::Min(const Value& left, const Value &right) const { left.CheckInteger(); left.CheckComparable(right); if (left.IsNull() || right.IsNull()) return left.OperateNull(right); Value cmp = (left.CompareGreaterThanEquals(right)); if (cmp.IsTrue()) return left.Copy(); return right.Copy(); } Value IntegerParentType::Max(const Value& left, const Value &right) const { left.CheckInteger(); left.CheckComparable(right); if (left.IsNull() || right.IsNull()) return left.OperateNull(right); Value cmp = (left.CompareGreaterThanEquals(right)); if (cmp.IsTrue()) return left.Copy(); return right.Copy(); } } // namespace common } // namespace peloton
//===----------------------------------------------------------------------===// // // Peloton // // numeric_value.cpp // // Identification: src/backend/common/numeric_value.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "common/integer_parent_type.h" #include <cmath> #include <iostream> #include "common/boolean_type.h" #include "common/decimal_type.h" #include "common/varlen_type.h" namespace peloton { namespace common { IntegerParentType::IntegerParentType(TypeId type) : NumericType(type) {} Value IntegerParentType::Min(const Value& left, const Value& right) const { left.CheckInteger(); left.CheckComparable(right); if (left.IsNull() || right.IsNull()) return left.OperateNull(right); Value cmp = (left.CompareLessThan(right)); if (cmp.IsTrue()) return left.Copy(); return right.Copy(); } Value IntegerParentType::Max(const Value& left, const Value& right) const { left.CheckInteger(); left.CheckComparable(right); if (left.IsNull() || right.IsNull()) return left.OperateNull(right); Value cmp = (left.CompareGreaterThanEquals(right)); if (cmp.IsTrue()) return left.Copy(); return right.Copy(); } } // namespace common } // namespace peloton
Fix min aggregation on integer. Will add test cases later.
[#375] Fix min aggregation on integer. Will add test cases later.
C++
apache-2.0
prashasthip/peloton,seojungmin/peloton,PauloAmora/peloton,AllisonWang/peloton,wangziqi2016/peloton,vittvolt/15721-peloton,ShuxinLin/peloton,malin1993ml/peloton,apavlo/peloton,apavlo/peloton,yingjunwu/peloton,vittvolt/peloton,wangziqi2016/peloton,phisiart/peloton-p3,malin1993ml/peloton,apavlo/peloton,seojungmin/peloton,AngLi-Leon/peloton,vittvolt/peloton,vittvolt/15721-peloton,PauloAmora/peloton,prashasthip/peloton,prashasthip/peloton,cmu-db/peloton,yingjunwu/peloton,seojungmin/peloton,ShuxinLin/peloton,seojungmin/peloton,malin1993ml/peloton,haojin2/peloton,phisiart/peloton-p3,AngLi-Leon/peloton,cmu-db/peloton,haojin2/peloton,vittvolt/15721-peloton,yingjunwu/peloton,PauloAmora/peloton,jessesleeping/iso_peloton,yingjunwu/peloton,jessesleeping/iso_peloton,prashasthip/peloton,cmu-db/peloton,ShuxinLin/peloton,AllisonWang/peloton,cmu-db/peloton,PauloAmora/peloton,vittvolt/15721-peloton,apavlo/peloton,haojin2/peloton,phisiart/peloton-p3,jessesleeping/iso_peloton,ShuxinLin/peloton,vittvolt/15721-peloton,AngLi-Leon/peloton,prashasthip/peloton,jessesleeping/iso_peloton,jessesleeping/iso_peloton,vittvolt/peloton,haojin2/peloton,ShuxinLin/peloton,phisiart/peloton-p3,AngLi-Leon/peloton,AllisonWang/peloton,seojungmin/peloton,yingjunwu/peloton,phisiart/peloton-p3,vittvolt/peloton,seojungmin/peloton,vittvolt/peloton,wangziqi2016/peloton,malin1993ml/peloton,apavlo/peloton,wangziqi2016/peloton,AngLi-Leon/peloton,vittvolt/peloton,AllisonWang/peloton,prashasthip/peloton,AllisonWang/peloton,phisiart/peloton-p3,wangziqi2016/peloton,wangziqi2016/peloton,malin1993ml/peloton,PauloAmora/peloton,cmu-db/peloton,haojin2/peloton,ShuxinLin/peloton,haojin2/peloton,yingjunwu/peloton,malin1993ml/peloton,AllisonWang/peloton,AngLi-Leon/peloton,jessesleeping/iso_peloton,vittvolt/15721-peloton,cmu-db/peloton,apavlo/peloton,PauloAmora/peloton,jessesleeping/iso_peloton
245ffbdfab7bf2ff5252a13cb6843c2f75f90cfc
tmva/src/LDA.cxx
tmva/src/LDA.cxx
// $Id$ /********************************************************************************** * Project: TMVA - a Root-integrated toolkit for multivariate data analysis * * Package: TMVA * * Class : LDA * * Web : http://tmva.sourceforge.net * * * * Description: * * Local LDA method used by MethodKNN to compute MVA value. * * This is experimental code under development. This class computes * * parameters of signal and background PDFs using Gaussian aproximation. * * * * Author: * * John Alison [email protected] - University of Pennsylvania, USA * * * * Copyright (c) 2007: * * CERN, Switzerland * * MPI-K Heidelberg, Germany * * University of Pennsylvania, USA * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted according to the terms listed in LICENSE * * (http://tmva.sourceforge.net/LICENSE) * **********************************************************************************/ // Local #include "TMVA/LDA.h" // C/C++ #include <iostream> #ifndef ROOT_TDecompSVD #include "TDecompSVD.h" #endif #ifndef ROOT_TMatrixF #include "TMatrixF.h" #endif #ifndef ROOT_TMath #include "TMath.h" #endif #ifndef ROOT_TMVA_Types #include "TMVA/Types.h" #endif #ifndef ROOT_TMVA_MsgLogger #include "TMVA/MsgLogger.h" #endif //_______________________________________________________________________ TMVA::LDA::LDA( Float_t tolerence, Bool_t debug ) : fTolerence(tolerence), fNumParams(0), fSigma(0), fSigmaInverse(0), fDebug(debug), fLogger( new MsgLogger("LDA", (debug?kINFO:kDEBUG)) ) { // constructor } //_______________________________________________________________________ TMVA::LDA::~LDA() { // destructor delete fLogger; } //_______________________________________________________________________ void TMVA::LDA::Initialize(const LDAEvents& inputSignalEvents, const LDAEvents& inputBackgroundEvents) { // Create LDA matrix using local events found by knn method Log() << kDEBUG << "There are: " << inputSignalEvents.size() << " input signal events " << Endl; Log() << kDEBUG << "There are: " << inputBackgroundEvents.size() << " input background events " << Endl; fNumParams = inputSignalEvents[0].size(); UInt_t numSignalEvents = inputSignalEvents.size(); UInt_t numBackEvents = inputBackgroundEvents.size(); UInt_t numTotalEvents = numSignalEvents + numBackEvents; fEventFraction[0] = (Float_t)numBackEvents/numTotalEvents; fEventFraction[1] = (Float_t)numSignalEvents/numTotalEvents; UInt_t K = 2; // get the mean of the signal and background for each parameter std::vector<Float_t> m_muSignal (fNumParams,0.0); std::vector<Float_t> m_muBackground (fNumParams,0.0); for (UInt_t param=0; param < fNumParams; ++param) { for (UInt_t eventNumber=0; eventNumber < numSignalEvents; ++eventNumber) m_muSignal[param] += inputSignalEvents[eventNumber][param]; for (UInt_t eventNumber=0; eventNumber < numBackEvents; ++eventNumber) m_muBackground[param] += inputBackgroundEvents[eventNumber][param]/numBackEvents; m_muSignal[param] /= numSignalEvents; m_muBackground[param] /= numBackEvents; } fMu[0] = m_muBackground; fMu[1] = m_muSignal; if (fDebug) { Log() << kDEBUG << "the signal means" << Endl; for (UInt_t param=0; param < fNumParams; ++param) Log() << kDEBUG << m_muSignal[param] << Endl; Log() << kDEBUG << "the background means" << Endl; for (UInt_t param=0; param < inputBackgroundEvents[0].size(); ++param) Log() << kDEBUG << m_muBackground[param] << Endl; } // sigma is a sum of two symmetric matrices, one for the background and one for signal // get the matricies seperately (def not be the best way to do it!) // the signal, background, and total matrix TMatrixF sigmaSignal(fNumParams, fNumParams); TMatrixF sigmaBack(fNumParams, fNumParams); if (fSigma!=0) delete fSigma; fSigma = new TMatrixF(fNumParams, fNumParams); for (UInt_t row=0; row < fNumParams; ++row) { for (UInt_t col=0; col < fNumParams; ++col) { sigmaSignal[row][col] = 0; sigmaBack[row][col] = 0; (*fSigma)[row][col] = 0; } } for (UInt_t eventNumber=0; eventNumber < numSignalEvents; ++eventNumber) { for (UInt_t row=0; row < fNumParams; ++row) { for (UInt_t col=0; col < fNumParams; ++col) { sigmaSignal[row][col] += (inputSignalEvents[eventNumber][row] - m_muSignal[row]) * (inputSignalEvents[eventNumber][col] - m_muSignal[col] ); } } } for (UInt_t eventNumber=0; eventNumber < numBackEvents; ++eventNumber) { for (UInt_t row=0; row < fNumParams; ++row) { for (UInt_t col=0; col < fNumParams; ++col) { sigmaBack[row][col] += (inputBackgroundEvents[eventNumber][row] - m_muBackground[row]) * (inputBackgroundEvents[eventNumber][col] - m_muBackground[col] ); } } } // the total matrix *fSigma = sigmaBack + sigmaSignal; *fSigma *= 1.0/(numTotalEvents - K); if (fDebug) { Log() << "after filling sigmaSignal" <<Endl; sigmaSignal.Print(); Log() << "after filling sigmaBack" <<Endl; sigmaBack.Print(); Log() << "after filling total Sigma" <<Endl; fSigma->Print(); } TDecompSVD solutionSVD = TDecompSVD( *fSigma ); TMatrixF decomposed = TMatrixF( fNumParams, fNumParams ); TMatrixF diag ( fNumParams, fNumParams ); TMatrixF uTrans( fNumParams, fNumParams ); TMatrixF vTrans( fNumParams, fNumParams ); if (solutionSVD.Decompose()) { for (UInt_t i = 0; i< fNumParams; ++i) { if (solutionSVD.GetSig()[i] > fTolerence) diag(i,i) = solutionSVD.GetSig()[i]; else diag(i,i) = fTolerence; } if (fDebug) { Log() << "the diagonal" <<Endl; diag.Print(); } decomposed = solutionSVD.GetV(); decomposed *= diag; decomposed *= solutionSVD.GetU(); if (fDebug) { Log() << "the decomposition " <<Endl; decomposed.Print(); } *fSigmaInverse = uTrans.Transpose(solutionSVD.GetU()); *fSigmaInverse /= diag; *fSigmaInverse *= vTrans.Transpose(solutionSVD.GetV()); if (fDebug) { Log() << "the SigmaInverse " <<Endl; fSigmaInverse->Print(); Log() << "the real " <<Endl; fSigma->Invert(); fSigma->Print(); Bool_t problem = false; for (UInt_t i =0; i< fNumParams; ++i) { for (UInt_t j =0; j< fNumParams; ++j) { if (TMath::Abs((Float_t)(*fSigma)(i,j) - (Float_t)(*fSigmaInverse)(i,j)) > 0.01) { Log() << "problem, i= "<< i << " j= " << j << Endl; Log() << "Sigma(i,j)= "<< (*fSigma)(i,j) << " SigmaInverse(i,j)= " << (*fSigmaInverse)(i,j) <<Endl; Log() << "The difference is : " << TMath::Abs((Float_t)(*fSigma)(i,j) - (Float_t)(*fSigmaInverse)(i,j)) <<Endl; problem = true; } } } if (problem) Log() << kWARNING << "Problem with the inversion!" << Endl; } } } //_______________________________________________________________________ Float_t TMVA::LDA::FSub(const std::vector<Float_t>& x, Int_t k) { // // Probability value using Gaussian approximation // Float_t prefactor = 1.0/(TMath::TwoPi()*TMath::Sqrt(fSigma->Determinant())); std::vector<Float_t> m_transPoseTimesSigmaInverse; for (UInt_t j=0; j < fNumParams; ++j) { Float_t m_temp = 0; for (UInt_t i=0; i < fNumParams; ++i) { m_temp += (x[i] - fMu[k][i]) * (*fSigmaInverse)(j,i); } m_transPoseTimesSigmaInverse.push_back(m_temp); } Float_t exponent = 0.0; for (UInt_t i=0; i< fNumParams; ++i) { exponent += m_transPoseTimesSigmaInverse[i]*(x[i] - fMu[k][i]); } exponent *= -0.5; return prefactor*TMath::Exp( exponent ); } //_______________________________________________________________________ Float_t TMVA::LDA::GetProb(const std::vector<Float_t>& x, Int_t k) { // // Signal probability with Gaussian approximation // Float_t m_numerator = FSub(x,k)*fEventFraction[k]; Float_t m_denominator = FSub(x,0)*fEventFraction[0]+FSub(x,1)*fEventFraction[1]; return m_numerator/m_denominator; } //_______________________________________________________________________ Float_t TMVA::LDA::GetLogLikelihood( const std::vector<Float_t>& x, Int_t k ) { // // Log likelihood function with Gaussian approximation // return TMath::Log( FSub(x,k)/FSub(x,!k) ) + TMath::Log( fEventFraction[k]/fEventFraction[!k] ); }
// $Id$ /********************************************************************************** * Project: TMVA - a Root-integrated toolkit for multivariate data analysis * * Package: TMVA * * Class : LDA * * Web : http://tmva.sourceforge.net * * * * Description: * * Local LDA method used by MethodKNN to compute MVA value. * * This is experimental code under development. This class computes * * parameters of signal and background PDFs using Gaussian aproximation. * * * * Author: * * John Alison [email protected] - University of Pennsylvania, USA * * * * Copyright (c) 2007: * * CERN, Switzerland * * MPI-K Heidelberg, Germany * * University of Pennsylvania, USA * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted according to the terms listed in LICENSE * * (http://tmva.sourceforge.net/LICENSE) * **********************************************************************************/ // Local #include "TMVA/LDA.h" // C/C++ #include <iostream> #ifndef ROOT_TDecompSVD #include "TDecompSVD.h" #endif #ifndef ROOT_TMatrixF #include "TMatrixF.h" #endif #ifndef ROOT_TMath #include "TMath.h" #endif #ifndef ROOT_TMVA_Types #include "TMVA/Types.h" #endif #ifndef ROOT_TMVA_MsgLogger #include "TMVA/MsgLogger.h" #endif //_______________________________________________________________________ TMVA::LDA::LDA( Float_t tolerence, Bool_t debug ) : fTolerence(tolerence), fNumParams(0), fSigma(0), fSigmaInverse(0), fDebug(debug), fLogger( new MsgLogger("LDA", (debug?kINFO:kDEBUG)) ) { // constructor } //_______________________________________________________________________ TMVA::LDA::~LDA() { // destructor delete fLogger; } //_______________________________________________________________________ void TMVA::LDA::Initialize(const LDAEvents& inputSignalEvents, const LDAEvents& inputBackgroundEvents) { // Create LDA matrix using local events found by knn method Log() << kDEBUG << "There are: " << inputSignalEvents.size() << " input signal events " << Endl; Log() << kDEBUG << "There are: " << inputBackgroundEvents.size() << " input background events " << Endl; fNumParams = inputSignalEvents[0].size(); UInt_t numSignalEvents = inputSignalEvents.size(); UInt_t numBackEvents = inputBackgroundEvents.size(); UInt_t numTotalEvents = numSignalEvents + numBackEvents; fEventFraction[0] = (Float_t)numBackEvents/numTotalEvents; fEventFraction[1] = (Float_t)numSignalEvents/numTotalEvents; UInt_t K = 2; // get the mean of the signal and background for each parameter std::vector<Float_t> m_muSignal (fNumParams,0.0); std::vector<Float_t> m_muBackground (fNumParams,0.0); for (UInt_t param=0; param < fNumParams; ++param) { for (UInt_t eventNumber=0; eventNumber < numSignalEvents; ++eventNumber) m_muSignal[param] += inputSignalEvents[eventNumber][param]; for (UInt_t eventNumber=0; eventNumber < numBackEvents; ++eventNumber) m_muBackground[param] += inputBackgroundEvents[eventNumber][param]/numBackEvents; if (numSignalEvents > 0) m_muSignal[param] /= numSignalEvents; if (numBackEvents > 0 ) m_muBackground[param] /= numBackEvents; } fMu[0] = m_muBackground; fMu[1] = m_muSignal; if (fDebug) { Log() << kDEBUG << "the signal means" << Endl; for (UInt_t param=0; param < fNumParams; ++param) Log() << kDEBUG << m_muSignal[param] << Endl; Log() << kDEBUG << "the background means" << Endl; for (UInt_t param=0; param < inputBackgroundEvents[0].size(); ++param) Log() << kDEBUG << m_muBackground[param] << Endl; } // sigma is a sum of two symmetric matrices, one for the background and one for signal // get the matricies seperately (def not be the best way to do it!) // the signal, background, and total matrix TMatrixF sigmaSignal(fNumParams, fNumParams); TMatrixF sigmaBack(fNumParams, fNumParams); if (fSigma!=0) delete fSigma; fSigma = new TMatrixF(fNumParams, fNumParams); for (UInt_t row=0; row < fNumParams; ++row) { for (UInt_t col=0; col < fNumParams; ++col) { sigmaSignal[row][col] = 0; sigmaBack[row][col] = 0; (*fSigma)[row][col] = 0; } } for (UInt_t eventNumber=0; eventNumber < numSignalEvents; ++eventNumber) { for (UInt_t row=0; row < fNumParams; ++row) { for (UInt_t col=0; col < fNumParams; ++col) { sigmaSignal[row][col] += (inputSignalEvents[eventNumber][row] - m_muSignal[row]) * (inputSignalEvents[eventNumber][col] - m_muSignal[col] ); } } } for (UInt_t eventNumber=0; eventNumber < numBackEvents; ++eventNumber) { for (UInt_t row=0; row < fNumParams; ++row) { for (UInt_t col=0; col < fNumParams; ++col) { sigmaBack[row][col] += (inputBackgroundEvents[eventNumber][row] - m_muBackground[row]) * (inputBackgroundEvents[eventNumber][col] - m_muBackground[col] ); } } } // the total matrix *fSigma = sigmaBack + sigmaSignal; *fSigma *= 1.0/(numTotalEvents - K); if (fDebug) { Log() << "after filling sigmaSignal" <<Endl; sigmaSignal.Print(); Log() << "after filling sigmaBack" <<Endl; sigmaBack.Print(); Log() << "after filling total Sigma" <<Endl; fSigma->Print(); } TDecompSVD solutionSVD = TDecompSVD( *fSigma ); TMatrixF decomposed = TMatrixF( fNumParams, fNumParams ); TMatrixF diag ( fNumParams, fNumParams ); TMatrixF uTrans( fNumParams, fNumParams ); TMatrixF vTrans( fNumParams, fNumParams ); if (solutionSVD.Decompose()) { for (UInt_t i = 0; i< fNumParams; ++i) { if (solutionSVD.GetSig()[i] > fTolerence) diag(i,i) = solutionSVD.GetSig()[i]; else diag(i,i) = fTolerence; } if (fDebug) { Log() << "the diagonal" <<Endl; diag.Print(); } decomposed = solutionSVD.GetV(); decomposed *= diag; decomposed *= solutionSVD.GetU(); if (fDebug) { Log() << "the decomposition " <<Endl; decomposed.Print(); } *fSigmaInverse = uTrans.Transpose(solutionSVD.GetU()); *fSigmaInverse /= diag; *fSigmaInverse *= vTrans.Transpose(solutionSVD.GetV()); if (fDebug) { Log() << "the SigmaInverse " <<Endl; fSigmaInverse->Print(); Log() << "the real " <<Endl; fSigma->Invert(); fSigma->Print(); Bool_t problem = false; for (UInt_t i =0; i< fNumParams; ++i) { for (UInt_t j =0; j< fNumParams; ++j) { if (TMath::Abs((Float_t)(*fSigma)(i,j) - (Float_t)(*fSigmaInverse)(i,j)) > 0.01) { Log() << "problem, i= "<< i << " j= " << j << Endl; Log() << "Sigma(i,j)= "<< (*fSigma)(i,j) << " SigmaInverse(i,j)= " << (*fSigmaInverse)(i,j) <<Endl; Log() << "The difference is : " << TMath::Abs((Float_t)(*fSigma)(i,j) - (Float_t)(*fSigmaInverse)(i,j)) <<Endl; problem = true; } } } if (problem) Log() << kWARNING << "Problem with the inversion!" << Endl; } } } //_______________________________________________________________________ Float_t TMVA::LDA::FSub(const std::vector<Float_t>& x, Int_t k) { // // Probability value using Gaussian approximation // Float_t prefactor = 1.0/(TMath::TwoPi()*TMath::Sqrt(fSigma->Determinant())); std::vector<Float_t> m_transPoseTimesSigmaInverse; for (UInt_t j=0; j < fNumParams; ++j) { Float_t m_temp = 0; for (UInt_t i=0; i < fNumParams; ++i) { m_temp += (x[i] - fMu[k][i]) * (*fSigmaInverse)(j,i); } m_transPoseTimesSigmaInverse.push_back(m_temp); } Float_t exponent = 0.0; for (UInt_t i=0; i< fNumParams; ++i) { exponent += m_transPoseTimesSigmaInverse[i]*(x[i] - fMu[k][i]); } exponent *= -0.5; return prefactor*TMath::Exp( exponent ); } //_______________________________________________________________________ Float_t TMVA::LDA::GetProb(const std::vector<Float_t>& x, Int_t k) { // // Signal probability with Gaussian approximation // Float_t m_numerator = FSub(x,k)*fEventFraction[k]; Float_t m_denominator = FSub(x,0)*fEventFraction[0]+FSub(x,1)*fEventFraction[1]; return m_numerator/m_denominator; } //_______________________________________________________________________ Float_t TMVA::LDA::GetLogLikelihood( const std::vector<Float_t>& x, Int_t k ) { // // Log likelihood function with Gaussian approximation // return TMath::Log( FSub(x,k)/FSub(x,!k) ) + TMath::Log( fEventFraction[k]/fEventFraction[!k] ); }
fix coverity issue 35429 and 35430
fix coverity issue 35429 and 35430
C++
lgpl-2.1
nilqed/root,buuck/root,mhuwiler/rootauto,Y--/root,simonpf/root,evgeny-boger/root,sbinet/cxx-root,nilqed/root,arch1tect0r/root,perovic/root,omazapa/root-old,arch1tect0r/root,smarinac/root,omazapa/root-old,beniz/root,krafczyk/root,agarciamontoro/root,dfunke/root,dfunke/root,veprbl/root,abhinavmoudgil95/root,bbockelm/root,mkret2/root,sirinath/root,0x0all/ROOT,jrtomps/root,BerserkerTroll/root,arch1tect0r/root,thomaskeck/root,satyarth934/root,zzxuanyuan/root-compressor-dummy,root-mirror/root,esakellari/my_root_for_test,georgtroska/root,zzxuanyuan/root,veprbl/root,krafczyk/root,sbinet/cxx-root,evgeny-boger/root,Duraznos/root,esakellari/root,sirinath/root,georgtroska/root,abhinavmoudgil95/root,bbockelm/root,arch1tect0r/root,omazapa/root-old,karies/root,simonpf/root,jrtomps/root,jrtomps/root,satyarth934/root,CristinaCristescu/root,CristinaCristescu/root,karies/root,simonpf/root,smarinac/root,perovic/root,zzxuanyuan/root-compressor-dummy,vukasinmilosevic/root,buuck/root,thomaskeck/root,BerserkerTroll/root,beniz/root,jrtomps/root,0x0all/ROOT,Duraznos/root,gbitzes/root,esakellari/root,veprbl/root,dfunke/root,zzxuanyuan/root,georgtroska/root,gganis/root,mkret2/root,abhinavmoudgil95/root,pspe/root,veprbl/root,omazapa/root,dfunke/root,simonpf/root,olifre/root,mhuwiler/rootauto,pspe/root,omazapa/root,gganis/root,bbockelm/root,sawenzel/root,pspe/root,gganis/root,mattkretz/root,CristinaCristescu/root,lgiommi/root,sirinath/root,vukasinmilosevic/root,georgtroska/root,CristinaCristescu/root,smarinac/root,lgiommi/root,perovic/root,mkret2/root,veprbl/root,simonpf/root,dfunke/root,pspe/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,olifre/root,gbitzes/root,beniz/root,sbinet/cxx-root,sirinath/root,lgiommi/root,sirinath/root,beniz/root,mattkretz/root,evgeny-boger/root,esakellari/root,omazapa/root-old,evgeny-boger/root,Y--/root,smarinac/root,mhuwiler/rootauto,abhinavmoudgil95/root,satyarth934/root,0x0all/ROOT,vukasinmilosevic/root,mhuwiler/rootauto,perovic/root,gganis/root,CristinaCristescu/root,dfunke/root,dfunke/root,buuck/root,Y--/root,simonpf/root,root-mirror/root,sawenzel/root,nilqed/root,zzxuanyuan/root-compressor-dummy,georgtroska/root,Duraznos/root,sawenzel/root,mkret2/root,perovic/root,0x0all/ROOT,olifre/root,georgtroska/root,perovic/root,georgtroska/root,pspe/root,CristinaCristescu/root,root-mirror/root,gbitzes/root,krafczyk/root,omazapa/root-old,nilqed/root,omazapa/root,davidlt/root,esakellari/my_root_for_test,davidlt/root,satyarth934/root,thomaskeck/root,BerserkerTroll/root,vukasinmilosevic/root,esakellari/root,BerserkerTroll/root,esakellari/my_root_for_test,lgiommi/root,omazapa/root,vukasinmilosevic/root,BerserkerTroll/root,Y--/root,gbitzes/root,pspe/root,sbinet/cxx-root,jrtomps/root,karies/root,sbinet/cxx-root,sawenzel/root,agarciamontoro/root,root-mirror/root,root-mirror/root,smarinac/root,abhinavmoudgil95/root,thomaskeck/root,olifre/root,davidlt/root,0x0all/ROOT,gganis/root,vukasinmilosevic/root,karies/root,buuck/root,georgtroska/root,zzxuanyuan/root,root-mirror/root,sirinath/root,CristinaCristescu/root,olifre/root,Y--/root,sawenzel/root,zzxuanyuan/root-compressor-dummy,thomaskeck/root,Duraznos/root,krafczyk/root,lgiommi/root,zzxuanyuan/root,perovic/root,gganis/root,gbitzes/root,abhinavmoudgil95/root,olifre/root,karies/root,sbinet/cxx-root,esakellari/root,abhinavmoudgil95/root,buuck/root,mhuwiler/rootauto,mhuwiler/rootauto,davidlt/root,Y--/root,esakellari/my_root_for_test,sirinath/root,evgeny-boger/root,bbockelm/root,georgtroska/root,sirinath/root,beniz/root,buuck/root,arch1tect0r/root,BerserkerTroll/root,simonpf/root,Duraznos/root,agarciamontoro/root,zzxuanyuan/root-compressor-dummy,krafczyk/root,arch1tect0r/root,evgeny-boger/root,mattkretz/root,thomaskeck/root,sawenzel/root,beniz/root,gbitzes/root,dfunke/root,krafczyk/root,Duraznos/root,nilqed/root,mhuwiler/rootauto,esakellari/my_root_for_test,gbitzes/root,agarciamontoro/root,veprbl/root,sirinath/root,agarciamontoro/root,krafczyk/root,zzxuanyuan/root-compressor-dummy,sbinet/cxx-root,agarciamontoro/root,mattkretz/root,CristinaCristescu/root,Duraznos/root,mattkretz/root,omazapa/root-old,Y--/root,sbinet/cxx-root,veprbl/root,gbitzes/root,esakellari/my_root_for_test,simonpf/root,jrtomps/root,beniz/root,mhuwiler/rootauto,zzxuanyuan/root,arch1tect0r/root,gbitzes/root,root-mirror/root,vukasinmilosevic/root,lgiommi/root,nilqed/root,0x0all/ROOT,esakellari/my_root_for_test,abhinavmoudgil95/root,Y--/root,omazapa/root,nilqed/root,Duraznos/root,bbockelm/root,sbinet/cxx-root,beniz/root,esakellari/root,krafczyk/root,pspe/root,sawenzel/root,evgeny-boger/root,buuck/root,Duraznos/root,zzxuanyuan/root,smarinac/root,abhinavmoudgil95/root,perovic/root,jrtomps/root,olifre/root,BerserkerTroll/root,omazapa/root,zzxuanyuan/root,thomaskeck/root,vukasinmilosevic/root,lgiommi/root,satyarth934/root,thomaskeck/root,gganis/root,bbockelm/root,mattkretz/root,vukasinmilosevic/root,georgtroska/root,simonpf/root,CristinaCristescu/root,smarinac/root,lgiommi/root,gbitzes/root,zzxuanyuan/root-compressor-dummy,davidlt/root,zzxuanyuan/root,esakellari/root,arch1tect0r/root,mkret2/root,mattkretz/root,bbockelm/root,arch1tect0r/root,mkret2/root,mkret2/root,gganis/root,georgtroska/root,mkret2/root,sbinet/cxx-root,perovic/root,davidlt/root,omazapa/root,vukasinmilosevic/root,agarciamontoro/root,evgeny-boger/root,satyarth934/root,satyarth934/root,gganis/root,jrtomps/root,Duraznos/root,veprbl/root,buuck/root,sirinath/root,smarinac/root,mkret2/root,karies/root,satyarth934/root,beniz/root,olifre/root,smarinac/root,BerserkerTroll/root,mattkretz/root,gganis/root,arch1tect0r/root,lgiommi/root,karies/root,mattkretz/root,zzxuanyuan/root,sawenzel/root,thomaskeck/root,krafczyk/root,esakellari/root,olifre/root,esakellari/root,satyarth934/root,0x0all/ROOT,agarciamontoro/root,Y--/root,sawenzel/root,omazapa/root,krafczyk/root,satyarth934/root,davidlt/root,agarciamontoro/root,thomaskeck/root,abhinavmoudgil95/root,zzxuanyuan/root,pspe/root,CristinaCristescu/root,pspe/root,karies/root,gbitzes/root,esakellari/my_root_for_test,sawenzel/root,BerserkerTroll/root,0x0all/ROOT,bbockelm/root,veprbl/root,sawenzel/root,buuck/root,olifre/root,Y--/root,davidlt/root,nilqed/root,mattkretz/root,root-mirror/root,root-mirror/root,pspe/root,agarciamontoro/root,agarciamontoro/root,zzxuanyuan/root,veprbl/root,Duraznos/root,root-mirror/root,zzxuanyuan/root-compressor-dummy,satyarth934/root,dfunke/root,buuck/root,evgeny-boger/root,jrtomps/root,olifre/root,krafczyk/root,dfunke/root,bbockelm/root,karies/root,vukasinmilosevic/root,nilqed/root,simonpf/root,perovic/root,lgiommi/root,omazapa/root,BerserkerTroll/root,omazapa/root-old,mkret2/root,buuck/root,esakellari/my_root_for_test,zzxuanyuan/root,sbinet/cxx-root,pspe/root,bbockelm/root,davidlt/root,karies/root,omazapa/root-old,dfunke/root,omazapa/root-old,mkret2/root,karies/root,mhuwiler/rootauto,bbockelm/root,jrtomps/root,beniz/root,esakellari/my_root_for_test,omazapa/root,jrtomps/root,omazapa/root-old,arch1tect0r/root,smarinac/root,mattkretz/root,root-mirror/root,sirinath/root,nilqed/root,beniz/root,CristinaCristescu/root,lgiommi/root,esakellari/root,gganis/root,veprbl/root,zzxuanyuan/root-compressor-dummy,Y--/root,mhuwiler/rootauto,nilqed/root,simonpf/root,BerserkerTroll/root,omazapa/root-old,esakellari/root,davidlt/root,evgeny-boger/root,omazapa/root,0x0all/ROOT,perovic/root,mhuwiler/rootauto,evgeny-boger/root,davidlt/root,abhinavmoudgil95/root
c15cb15c4c799e2c370978e479b9ec8f6df8af47
toml/to_toml.hpp
toml/to_toml.hpp
#ifndef TOML11_TO_TOML #define TOML11_TO_TOML #include "value.hpp" namespace toml { template<typename T, typename std::enable_if< detail::is_exact_toml_type<T>::value, std::nullptr_t>::type = nullptr> inline value to_toml(const T& x) { return value(x); } template<typename T, typename std::enable_if<detail::conjunction< detail::negation<detail::is_exact_toml_type<T>>, std::is_integral<T> >::value, std::nullptr_t>::type = nullptr> inline value to_toml(const T& x) { return value(::toml::Integer(x)); } template<typename T, typename std::enable_if<detail::conjunction< detail::negation<detail::is_exact_toml_type<T>>, std::is_floating_point<T> >::value, std::nullptr_t>::type = nullptr> inline value to_toml(const T& x) { return value(::toml::Float(x)); } inline value to_toml(const char* str) { return value(::toml::String(str)); } template<typename T, typename std::enable_if<detail::conjunction< detail::negation<detail::is_exact_toml_type<T>>, detail::is_container<T> >::value, std::nullptr_t>::type = nullptr> value to_toml(const T& x) { Array tmp; tmp.reserve(std::distance(std::begin(x), std::end(x))); for(auto iter = std::begin(x); iter != std::end(x); ++iter) { tmp.emplace_back(*iter); } return value(std::move(tmp)); } template<typename T, typename std::enable_if<detail::conjunction< detail::negation<detail::is_exact_toml_type<T>>, detail::is_map<T> >::value, std::nullptr_t>::type = nullptr> value to_toml(const T& x) { Table tmp; for(auto iter = std::begin(x); iter != std::end(x); ++iter) { tmp.emplace(iter->first, to_toml(iter->second)); } return value(std::move(tmp)); } template<typename T> inline value to_toml(std::initializer_list<T> init) { return value(std::move(init)); } inline value to_toml(std::initializer_list<std::pair<std::string, value>> init) { return value(std::move(init)); } template<typename T> inline value to_toml(const value& x) { return x; } } // toml #endif // TOML11_TO_TOML
#ifndef TOML11_TO_TOML #define TOML11_TO_TOML #include "value.hpp" namespace toml { template<typename T> inline value to_toml(T&& x) { return value(std::forward<T>(x)); } template<typename T> inline value to_toml(T&& x, string_t kind) { return value(std::forward<T>(x), kind); } inline value to_toml(local_date d, local_time t) { return value(local_datetime(d, t)); } inline value to_toml(local_date d, local_time t, time_offset ofs) { return value(offset_datetime(d, t, ofs)); } template<typename ... Ts> inline value to_toml(Ts&& ... xs) { return value(toml::array{toml::value(std::forward<Ts>(xs)) ... }); } inline value to_toml(std::initializer_list<std::pair<std::string, toml::value>> xs) { return value(toml::table(xs.begin(), xs.end())); } } // toml #endif // TOML11_TO_TOML
simplify to_toml implementation
simplify to_toml implementation
C++
mit
ToruNiina/toml11
4e055c0858ff64ef3e203d292bcdafcb282084ce
src/codegen/llvm/llvm_common.cc
src/codegen/llvm/llvm_common.cc
/*! * Copyright (c) 2017 by Contributors * \file llvm_common.cc */ #ifdef TVM_LLVM_VERSION #include <tvm/base.h> #include <mutex> #include "llvm_common.h" namespace tvm { namespace codegen { struct LLVMEnv { std::mutex mu; volatile bool all_initialized{false}; static LLVMEnv* Global() { static LLVMEnv inst; return &inst; } }; void InitializeLLVM() { LLVMEnv* e = LLVMEnv::Global(); if (!e->all_initialized) { std::lock_guard<std::mutex> lock(e->mu); if (!e->all_initialized) { llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmParsers(); llvm::InitializeAllAsmPrinters(); e->all_initialized = true; } } } void ParseLLVMTargetOptions(const std::string& target_str, std::string* triple, std::string* mcpu, std::string* mattr, llvm::TargetOptions* options) { // setup target triple size_t start = 0; if (target_str.length() >= 4 && target_str.substr(0, 4) == "llvm") { start = 4; } // simple parser triple->resize(0); mcpu->resize(0); mattr->resize(0); bool soft_float_abi = false; std::string key, value; std::istringstream is(target_str.substr(start, target_str.length() - start)); while (is >> key) { if (key == "--system-lib" || key == "-system-lib") { continue; } size_t pos = key.find('='); if (pos != std::string::npos) { CHECK_GE(key.length(), pos + 1) << "inavlid argument " << key; value = key.substr(pos + 1, key.length() - 1); key = key.substr(0, pos); } else { CHECK(is >> value) << "Unspecified value for option " << key; } if (key == "-target" || key == "-mtriple") { *triple = value; } else if (key == "-mcpu") { *mcpu = value; } else if (key == "-mattr") { *mattr = value; } else if (key == "-mfloat-abi") { if (value == "hard") { soft_float_abi = false; } else if (value == "soft") { soft_float_abi = true; } else { LOG(FATAL) << "invalid -mfloat-abi option " << value; } } else if (key == "-device" || key == "-libs" || key == "-model") { // pass } else { LOG(FATAL) << "unknown option " << key; } } if (triple->length() == 0 || *triple == "default") { *triple = llvm::sys::getDefaultTargetTriple(); } // set target option llvm::TargetOptions& opt = *options; opt = llvm::TargetOptions(); #if TVM_LLVM_VERSION < 50 opt.LessPreciseFPMADOption = true; #endif opt.AllowFPOpFusion = llvm::FPOpFusion::Fast; opt.UnsafeFPMath = true; opt.NoInfsFPMath = true; opt.NoNaNsFPMath = true; if (soft_float_abi) { opt.FloatABIType = llvm::FloatABI::Soft; } else { opt.FloatABIType = llvm::FloatABI::Hard; } } std::unique_ptr<llvm::TargetMachine> GetLLVMTargetMachine(const std::string& target_str, bool allow_null) { std::string target_triple, mcpu, mattr; llvm::TargetOptions opt; ParseLLVMTargetOptions(target_str, &target_triple, &mcpu, &mattr, &opt); if (target_triple.length() == 0 || target_triple == "default") { target_triple = llvm::sys::getDefaultTargetTriple(); } if (mcpu.length() == 0) { mcpu = "generic"; } std::string err; const llvm::Target* target = llvm::TargetRegistry::lookupTarget(target_triple, err); if (target == nullptr) { CHECK(allow_null) << err << " target_triple=" << target_triple; return nullptr; } llvm::TargetMachine* tm = target->createTargetMachine( target_triple, mcpu, mattr, opt, llvm::Reloc::PIC_); return std::unique_ptr<llvm::TargetMachine>(tm); } } // namespace codegen } // namespace tvm #endif // TVM_LLVM_VERSION
/*! * Copyright (c) 2017 by Contributors * \file llvm_common.cc */ #ifdef TVM_LLVM_VERSION #include <tvm/base.h> #include <atomic> #include <mutex> #include "llvm_common.h" namespace tvm { namespace codegen { struct LLVMEnv { std::mutex mu; std::atomic<bool> all_initialized{false}; static LLVMEnv* Global() { static LLVMEnv inst; return &inst; } }; void InitializeLLVM() { LLVMEnv* e = LLVMEnv::Global(); if (!e->all_initialized.load(std::memory_order::memory_order_acquire)) { std::lock_guard<std::mutex> lock(e->mu); if (!e->all_initialized.load(std::memory_order::memory_order_acquire)) { llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmParsers(); llvm::InitializeAllAsmPrinters(); e->all_initialized.store(true, std::memory_order::memory_order_release); } } } void ParseLLVMTargetOptions(const std::string& target_str, std::string* triple, std::string* mcpu, std::string* mattr, llvm::TargetOptions* options) { // setup target triple size_t start = 0; if (target_str.length() >= 4 && target_str.substr(0, 4) == "llvm") { start = 4; } // simple parser triple->resize(0); mcpu->resize(0); mattr->resize(0); bool soft_float_abi = false; std::string key, value; std::istringstream is(target_str.substr(start, target_str.length() - start)); while (is >> key) { if (key == "--system-lib" || key == "-system-lib") { continue; } size_t pos = key.find('='); if (pos != std::string::npos) { CHECK_GE(key.length(), pos + 1) << "inavlid argument " << key; value = key.substr(pos + 1, key.length() - 1); key = key.substr(0, pos); } else { CHECK(is >> value) << "Unspecified value for option " << key; } if (key == "-target" || key == "-mtriple") { *triple = value; } else if (key == "-mcpu") { *mcpu = value; } else if (key == "-mattr") { *mattr = value; } else if (key == "-mfloat-abi") { if (value == "hard") { soft_float_abi = false; } else if (value == "soft") { soft_float_abi = true; } else { LOG(FATAL) << "invalid -mfloat-abi option " << value; } } else if (key == "-device" || key == "-libs" || key == "-model") { // pass } else { LOG(FATAL) << "unknown option " << key; } } if (triple->length() == 0 || *triple == "default") { *triple = llvm::sys::getDefaultTargetTriple(); } // set target option llvm::TargetOptions& opt = *options; opt = llvm::TargetOptions(); #if TVM_LLVM_VERSION < 50 opt.LessPreciseFPMADOption = true; #endif opt.AllowFPOpFusion = llvm::FPOpFusion::Fast; opt.UnsafeFPMath = true; opt.NoInfsFPMath = true; opt.NoNaNsFPMath = true; if (soft_float_abi) { opt.FloatABIType = llvm::FloatABI::Soft; } else { opt.FloatABIType = llvm::FloatABI::Hard; } } std::unique_ptr<llvm::TargetMachine> GetLLVMTargetMachine(const std::string& target_str, bool allow_null) { std::string target_triple, mcpu, mattr; llvm::TargetOptions opt; ParseLLVMTargetOptions(target_str, &target_triple, &mcpu, &mattr, &opt); if (target_triple.length() == 0 || target_triple == "default") { target_triple = llvm::sys::getDefaultTargetTriple(); } if (mcpu.length() == 0) { mcpu = "generic"; } std::string err; const llvm::Target* target = llvm::TargetRegistry::lookupTarget(target_triple, err); if (target == nullptr) { CHECK(allow_null) << err << " target_triple=" << target_triple; return nullptr; } llvm::TargetMachine* tm = target->createTargetMachine( target_triple, mcpu, mattr, opt, llvm::Reloc::PIC_); return std::unique_ptr<llvm::TargetMachine>(tm); } } // namespace codegen } // namespace tvm #endif // TVM_LLVM_VERSION
Fix LLVM initialization again (#2399)
Fix LLVM initialization again (#2399)
C++
apache-2.0
tqchen/tvm,tqchen/tvm,sxjscience/tvm,Huyuwei/tvm,Huyuwei/tvm,dmlc/tvm,Laurawly/tvm-1,Laurawly/tvm-1,dmlc/tvm,dmlc/tvm,sxjscience/tvm,Huyuwei/tvm,Laurawly/tvm-1,tqchen/tvm,dmlc/tvm,dmlc/tvm,Laurawly/tvm-1,Laurawly/tvm-1,Huyuwei/tvm,tqchen/tvm,Laurawly/tvm-1,sxjscience/tvm,sxjscience/tvm,tqchen/tvm,Huyuwei/tvm,Laurawly/tvm-1,tqchen/tvm,Huyuwei/tvm,sxjscience/tvm,tqchen/tvm,Huyuwei/tvm,sxjscience/tvm,sxjscience/tvm,dmlc/tvm,Huyuwei/tvm,dmlc/tvm,Laurawly/tvm-1,tqchen/tvm,sxjscience/tvm,dmlc/tvm,Huyuwei/tvm,Laurawly/tvm-1,tqchen/tvm,sxjscience/tvm,tqchen/tvm,Laurawly/tvm-1,dmlc/tvm
ea0f0fe0af4fd60eebde5e61b038a99daa70a3f9
src/eventql/server/sql/scheduler.cc
src/eventql/server/sql/scheduler.cc
/** * Copyright (c) 2016 zScale Technology GmbH <[email protected]> * Authors: * - Paul Asmuth <[email protected]> * - Laura Schlimmer <[email protected]> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * 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 license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include <eventql/server/sql/scheduler.h> #include <eventql/server/sql/table_provider.h> #include <eventql/server/sql/pipelined_expression.h> #include <eventql/sql/qtree/QueryTreeUtil.h> #include <eventql/db/metadata_client.h> #include "eventql/eventql.h" namespace eventql { Scheduler::Scheduler( PartitionMap* pmap, ConfigDirectory* cdir, InternalAuth* auth, ReplicationScheme* repl_scheme) : pmap_(pmap), cdir_(cdir), auth_(auth), repl_scheme_(repl_scheme), running_cnt_(0) {} ScopedPtr<csql::TableExpression> Scheduler::buildTableExpression( csql::Transaction* txn, csql::ExecutionContext* execution_context, RefPtr<csql::TableExpressionNode> node) { rewriteTableTimeSuffix(node.get()); return DefaultScheduler::buildTableExpression( txn, execution_context, node.asInstanceOf<csql::TableExpressionNode>()); } ScopedPtr<csql::TableExpression> Scheduler::buildGroupByExpression( csql::Transaction* txn, csql::ExecutionContext* execution_context, RefPtr<csql::GroupByNode> node) { if (node->isPartialAggregation()) { return buildPartialGroupByExpression( txn, execution_context, node); } if (isPipelineable(*node->inputTable())) { return buildPipelineGroupByExpression( txn, execution_context, node); } else { return csql::DefaultScheduler::buildGroupByExpression( txn, execution_context, node); } } ScopedPtr<csql::TableExpression> Scheduler::buildPartialGroupByExpression( csql::Transaction* txn, csql::ExecutionContext* execution_context, RefPtr<csql::GroupByNode> node) { Vector<csql::ValueExpression> select_expressions; Vector<csql::ValueExpression> group_expressions; for (const auto& slnode : node->selectList()) { select_expressions.emplace_back( txn->getCompiler()->buildValueExpression( txn, slnode->expression())); } for (const auto& e : node->groupExpressions()) { group_expressions.emplace_back( txn->getCompiler()->buildValueExpression(txn, e)); } return mkScoped( new csql::PartialGroupByExpression( txn, std::move(select_expressions), std::move(group_expressions), buildTableExpression( txn, execution_context, node->inputTable().asInstanceOf<csql::TableExpressionNode>()))); } ScopedPtr<csql::TableExpression> Scheduler::buildPipelineGroupByExpression( csql::Transaction* txn, csql::ExecutionContext* execution_context, RefPtr<csql::GroupByNode> node) { auto remote_aggregate = mkScoped( new PipelinedExpression( txn, execution_context, static_cast<Session*>(txn->getUserData())->getEffectiveNamespace(), auth_, kMaxConcurrency)); auto shards = pipelineExpression(txn, node.get()); for (size_t i = 0; i < shards.size(); ++i) { auto group_by_copy = mkRef( new csql::GroupByNode( node->selectList(), node->groupExpressions(), shards[i].qtree)); group_by_copy->setIsPartialAggreagtion(true); if (shards[i].is_local) { auto partial = buildPartialGroupByExpression(txn, execution_context, group_by_copy); remote_aggregate->addLocalQuery(std::move(partial)); } else { remote_aggregate->addRemoteQuery(group_by_copy.get(), shards[i].hosts); } } Vector<csql::ValueExpression> select_expressions; for (const auto& slnode : node->selectList()) { select_expressions.emplace_back( txn->getCompiler()->buildValueExpression( txn, slnode->expression())); } return mkScoped( new csql::GroupByMergeExpression( txn, execution_context, std::move(select_expressions), std::move(remote_aggregate))); } Vector<Scheduler::PipelinedQueryTree> Scheduler::pipelineExpression( csql::Transaction* txn, RefPtr<csql::QueryTreeNode> qtree) { auto seqscan = csql::QueryTreeUtil::findNode<csql::SequentialScanNode>( qtree.get()); if (!seqscan) { RAISE(kIllegalStateError, "can't pipeline query tree"); } auto table_ref = TSDBTableRef::parse(seqscan->tableName()); if (!table_ref.partition_key.isEmpty()) { RAISE(kIllegalStateError, "can't pipeline query tree"); } auto user_data = txn->getUserData(); if (user_data == nullptr) { RAISE(kRuntimeError, "no user data"); } auto table = pmap_->findTable( static_cast<Session*>(txn->getUserData())->getEffectiveNamespace(), table_ref.table_key); if (table.isEmpty()) { RAISE(kIllegalStateError, "can't pipeline query tree"); } auto db_namespace = static_cast<Session*>(txn->getUserData())->getEffectiveNamespace(); Set<SHA1Hash> partitions; if (table.get()->partitionerType() == TBL_PARTITION_TIMEWINDOW) { auto keyrange = TSDBTableProvider::findKeyRange( table.get()->config().config().partition_key(), seqscan->constraints()); MetadataClient metadata_client(cdir_); PartitionListResponse partition_list; auto rc = metadata_client.listPartitions( db_namespace, table_ref.table_key, keyrange, &partition_list); if (!rc.isSuccess()) { RAISEF(kRuntimeError, "metadata lookup failure: $0", rc.message()); } for (const auto& p : partition_list.partitions()) { partitions.emplace( SHA1Hash(p.partition_id().data(), p.partition_id().size())); } } else { auto partitioner = table.get()->partitioner(); for (const auto& p : partitioner->listPartitions(seqscan->constraints())) { partitions.emplace(p); } } Vector<PipelinedQueryTree> shards; for (const auto& partition : partitions) { auto table_name = StringUtil::format( "tsdb://localhost/$0/$1", URI::urlEncode(table_ref.table_key), partition.toString()); auto qtree_copy = qtree->deepCopy(); auto shard = csql::QueryTreeUtil::findNode<csql::SequentialScanNode>( qtree_copy.get()); shard->setTableName(table_name); auto shard_hosts = repl_scheme_->replicasFor(partition); shards.emplace_back(PipelinedQueryTree { .is_local = repl_scheme_->hasLocalReplica(partition), .qtree = shard, .hosts = shard_hosts }); } return shards; } bool Scheduler::isPipelineable(const csql::QueryTreeNode& qtree) { if (dynamic_cast<const csql::SequentialScanNode*>(&qtree)) { return true; } if (dynamic_cast<const csql::SelectExpressionNode*>(&qtree)) { return true; } if (dynamic_cast<const csql::SubqueryNode*>(&qtree)) { return isPipelineable( *dynamic_cast<const csql::SubqueryNode&>(qtree).subquery()); } return false; } void Scheduler::rewriteTableTimeSuffix(RefPtr<csql::QueryTreeNode> node) { auto seqscan = dynamic_cast<csql::SequentialScanNode*>(node.get()); if (seqscan) { auto table_ref = TSDBTableRef::parse(seqscan->tableName()); if (!table_ref.timerange_begin.isEmpty() && !table_ref.timerange_limit.isEmpty()) { seqscan->setTableName(table_ref.table_key); auto pred = mkRef( new csql::CallExpressionNode( "logical_and", Vector<RefPtr<csql::ValueExpressionNode>>{ new csql::CallExpressionNode( "gte", Vector<RefPtr<csql::ValueExpressionNode>>{ new csql::ColumnReferenceNode("time"), new csql::LiteralExpressionNode( csql::SValue(csql::SValue::IntegerType( table_ref.timerange_begin.get().unixMicros()))) }), new csql::CallExpressionNode( "lte", Vector<RefPtr<csql::ValueExpressionNode>>{ new csql::ColumnReferenceNode("time"), new csql::LiteralExpressionNode( csql::SValue(csql::SValue::IntegerType( table_ref.timerange_limit.get().unixMicros()))) }) })); auto where_expr = seqscan->whereExpression(); if (!where_expr.isEmpty()) { pred = mkRef( new csql::CallExpressionNode( "logical_and", Vector<RefPtr<csql::ValueExpressionNode>>{ where_expr.get(), pred.asInstanceOf<csql::ValueExpressionNode>() })); } seqscan->setWhereExpression( pred.asInstanceOf<csql::ValueExpressionNode>()); } } auto ntables = node->numChildren(); for (int i = 0; i < ntables; ++i) { rewriteTableTimeSuffix(node->child(i)); } } } // namespace eventql
/** * Copyright (c) 2016 zScale Technology GmbH <[email protected]> * Authors: * - Paul Asmuth <[email protected]> * - Laura Schlimmer <[email protected]> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * 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 license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include <eventql/server/sql/scheduler.h> #include <eventql/server/sql/table_provider.h> #include <eventql/server/sql/pipelined_expression.h> #include <eventql/sql/qtree/QueryTreeUtil.h> #include <eventql/db/metadata_client.h> #include "eventql/eventql.h" namespace eventql { Scheduler::Scheduler( PartitionMap* pmap, ConfigDirectory* cdir, InternalAuth* auth, ReplicationScheme* repl_scheme) : pmap_(pmap), cdir_(cdir), auth_(auth), repl_scheme_(repl_scheme), running_cnt_(0) {} ScopedPtr<csql::TableExpression> Scheduler::buildTableExpression( csql::Transaction* txn, csql::ExecutionContext* execution_context, RefPtr<csql::TableExpressionNode> node) { rewriteTableTimeSuffix(node.get()); return DefaultScheduler::buildTableExpression( txn, execution_context, node.asInstanceOf<csql::TableExpressionNode>()); } ScopedPtr<csql::TableExpression> Scheduler::buildGroupByExpression( csql::Transaction* txn, csql::ExecutionContext* execution_context, RefPtr<csql::GroupByNode> node) { if (node->isPartialAggregation()) { return buildPartialGroupByExpression( txn, execution_context, node); } if (isPipelineable(*node->inputTable())) { return buildPipelineGroupByExpression( txn, execution_context, node); } else { return csql::DefaultScheduler::buildGroupByExpression( txn, execution_context, node); } } ScopedPtr<csql::TableExpression> Scheduler::buildPartialGroupByExpression( csql::Transaction* txn, csql::ExecutionContext* execution_context, RefPtr<csql::GroupByNode> node) { Vector<csql::ValueExpression> select_expressions; Vector<csql::ValueExpression> group_expressions; for (const auto& slnode : node->selectList()) { select_expressions.emplace_back( txn->getCompiler()->buildValueExpression( txn, slnode->expression())); } for (const auto& e : node->groupExpressions()) { group_expressions.emplace_back( txn->getCompiler()->buildValueExpression(txn, e)); } return mkScoped( new csql::PartialGroupByExpression( txn, std::move(select_expressions), std::move(group_expressions), buildTableExpression( txn, execution_context, node->inputTable().asInstanceOf<csql::TableExpressionNode>()))); } ScopedPtr<csql::TableExpression> Scheduler::buildPipelineGroupByExpression( csql::Transaction* txn, csql::ExecutionContext* execution_context, RefPtr<csql::GroupByNode> node) { auto remote_aggregate = mkScoped( new PipelinedExpression( txn, execution_context, static_cast<Session*>(txn->getUserData())->getEffectiveNamespace(), auth_, kMaxConcurrency)); auto shards = pipelineExpression(txn, node.get()); for (size_t i = 0; i < shards.size(); ++i) { auto group_by_copy = mkRef( new csql::GroupByNode( node->selectList(), node->groupExpressions(), shards[i].qtree)); group_by_copy->setIsPartialAggreagtion(true); if (shards[i].is_local) { auto partial = buildPartialGroupByExpression(txn, execution_context, group_by_copy); remote_aggregate->addLocalQuery(std::move(partial)); } else { remote_aggregate->addRemoteQuery(group_by_copy.get(), shards[i].hosts); } } Vector<csql::ValueExpression> select_expressions; for (const auto& slnode : node->selectList()) { select_expressions.emplace_back( txn->getCompiler()->buildValueExpression( txn, slnode->expression())); } return mkScoped( new csql::GroupByMergeExpression( txn, execution_context, std::move(select_expressions), std::move(remote_aggregate))); } Vector<Scheduler::PipelinedQueryTree> Scheduler::pipelineExpression( csql::Transaction* txn, RefPtr<csql::QueryTreeNode> qtree) { auto seqscan = csql::QueryTreeUtil::findNode<csql::SequentialScanNode>( qtree.get()); if (!seqscan) { RAISE(kIllegalStateError, "can't pipeline query tree"); } auto table_ref = TSDBTableRef::parse(seqscan->tableName()); if (!table_ref.partition_key.isEmpty()) { RAISE(kIllegalStateError, "can't pipeline query tree"); } auto user_data = txn->getUserData(); if (user_data == nullptr) { RAISE(kRuntimeError, "no user data"); } auto table = pmap_->findTable( static_cast<Session*>(txn->getUserData())->getEffectiveNamespace(), table_ref.table_key); if (table.isEmpty()) { RAISE(kIllegalStateError, "can't pipeline query tree"); } auto db_namespace = static_cast<Session*>(txn->getUserData())->getEffectiveNamespace(); auto local_server_id = cdir_->getServerID(); HashMap<SHA1Hash, Vector<ReplicaRef>> partitions; Set<SHA1Hash> local_partitions; if (table.get()->partitionerType() == TBL_PARTITION_TIMEWINDOW) { auto keyrange = TSDBTableProvider::findKeyRange( table.get()->config().config().partition_key(), seqscan->constraints()); MetadataClient metadata_client(cdir_); PartitionListResponse partition_list; auto rc = metadata_client.listPartitions( db_namespace, table_ref.table_key, keyrange, &partition_list); if (!rc.isSuccess()) { RAISEF(kRuntimeError, "metadata lookup failure: $0", rc.message()); } for (const auto& p : partition_list.partitions()) { Vector<ReplicaRef> replicas; SHA1Hash pid(p.partition_id().data(), p.partition_id().size()); for (const auto& s : p.servers()) { if (s == local_server_id) { local_partitions.emplace(pid); } auto server_cfg = cdir_->getServerConfig(s); if (server_cfg.server_status() != SERVER_UP) { continue; } ReplicaRef rref(SHA1::compute(s), server_cfg.server_addr()); rref.name = s; replicas.emplace_back(rref); } partitions.emplace(pid, replicas); } } else { auto partitioner = table.get()->partitioner(); for (const auto& p : partitioner->listPartitions(seqscan->constraints())) { auto replicas = repl_scheme_->replicasFor(p); if (repl_scheme_->hasLocalReplica(p)) { local_partitions.emplace(p); } partitions.emplace(p, Vector<ReplicaRef>(replicas.begin(), replicas.end())); } } Vector<PipelinedQueryTree> shards; for (const auto& p : partitions) { auto table_name = StringUtil::format( "tsdb://localhost/$0/$1", URI::urlEncode(table_ref.table_key), p.first.toString()); auto qtree_copy = qtree->deepCopy(); auto shard = csql::QueryTreeUtil::findNode<csql::SequentialScanNode>( qtree_copy.get()); shard->setTableName(table_name); PipelinedQueryTree pipelined { .is_local = local_partitions.count(p.first) > 0, .qtree = shard, .hosts = p.second }; shards.emplace_back(pipelined); } return shards; } bool Scheduler::isPipelineable(const csql::QueryTreeNode& qtree) { if (dynamic_cast<const csql::SequentialScanNode*>(&qtree)) { return true; } if (dynamic_cast<const csql::SelectExpressionNode*>(&qtree)) { return true; } if (dynamic_cast<const csql::SubqueryNode*>(&qtree)) { return isPipelineable( *dynamic_cast<const csql::SubqueryNode&>(qtree).subquery()); } return false; } void Scheduler::rewriteTableTimeSuffix(RefPtr<csql::QueryTreeNode> node) { auto seqscan = dynamic_cast<csql::SequentialScanNode*>(node.get()); if (seqscan) { auto table_ref = TSDBTableRef::parse(seqscan->tableName()); if (!table_ref.timerange_begin.isEmpty() && !table_ref.timerange_limit.isEmpty()) { seqscan->setTableName(table_ref.table_key); auto pred = mkRef( new csql::CallExpressionNode( "logical_and", Vector<RefPtr<csql::ValueExpressionNode>>{ new csql::CallExpressionNode( "gte", Vector<RefPtr<csql::ValueExpressionNode>>{ new csql::ColumnReferenceNode("time"), new csql::LiteralExpressionNode( csql::SValue(csql::SValue::IntegerType( table_ref.timerange_begin.get().unixMicros()))) }), new csql::CallExpressionNode( "lte", Vector<RefPtr<csql::ValueExpressionNode>>{ new csql::ColumnReferenceNode("time"), new csql::LiteralExpressionNode( csql::SValue(csql::SValue::IntegerType( table_ref.timerange_limit.get().unixMicros()))) }) })); auto where_expr = seqscan->whereExpression(); if (!where_expr.isEmpty()) { pred = mkRef( new csql::CallExpressionNode( "logical_and", Vector<RefPtr<csql::ValueExpressionNode>>{ where_expr.get(), pred.asInstanceOf<csql::ValueExpressionNode>() })); } seqscan->setWhereExpression( pred.asInstanceOf<csql::ValueExpressionNode>()); } } auto ntables = node->numChildren(); for (int i = 0; i < ntables; ++i) { rewriteTableTimeSuffix(node->child(i)); } } } // namespace eventql
use servers from partition map in pipelined aggregate
use servers from partition map in pipelined aggregate
C++
agpl-3.0
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
6c3f6353a4f18d78210c85463898433fc5fc9ab6
src/filebrowser/progress-dialog.cpp
src/filebrowser/progress-dialog.cpp
#include <QLabel> #include <QVBoxLayout> #include <QHBoxLayout> #include <QProgressBar> #include <QPushButton> #include <QDesktopServices> #include <QDebug> #include "utils/utils.h" #include "progress-dialog.h" FileBrowserProgressDialog::FileBrowserProgressDialog(FileNetworkTask *task, QWidget *parent) : QProgressDialog(parent), task_(task->sharedFromThis()) { setWindowModality(Qt::WindowModal); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setWindowIcon(QIcon(":/images/seafile.png")); QVBoxLayout *layout_ = new QVBoxLayout; progress_bar_ = new QProgressBar; description_label_ = new QLabel; layout_->addWidget(description_label_); layout_->addWidget(progress_bar_); QHBoxLayout *hlayout_ = new QHBoxLayout; more_details_label_ = new QLabel; more_details_label_->setText("Pending"); QPushButton *cancel_button_ = new QPushButton(tr("Cancel")); QWidget *spacer = new QWidget; spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); hlayout_->addWidget(more_details_label_); hlayout_->addWidget(spacer); hlayout_->addWidget(cancel_button_); hlayout_->setContentsMargins(-1, 0, -1, 6); layout_->setContentsMargins(-1, 0, -1, 6); layout_->addLayout(hlayout_); setLayout(layout_); setLabel(description_label_); setBar(progress_bar_); setCancelButton(cancel_button_); initTaskInfo(); } FileBrowserProgressDialog::~FileBrowserProgressDialog() { } void FileBrowserProgressDialog::initTaskInfo() { QString title, label; if (task_->type() == FileNetworkTask::Upload) { title = tr("Upload"); label = tr("Uploading %1"); } else { title = tr("Download"); label = tr("Downloading %1"); } setWindowTitle(title); setLabelText(label.arg(task_->fileName())); more_details_label_->setText(""); setMaximum(0); setValue(0); connect(task_.data(), SIGNAL(progressUpdate(qint64, qint64)), this, SLOT(onProgressUpdate(qint64, qint64))); connect(task_.data(), SIGNAL(finished(bool)), this, SLOT(onTaskFinished(bool))); connect(this, SIGNAL(canceled()), task_.data(), SLOT(cancel())); show(); } void FileBrowserProgressDialog::onProgressUpdate(qint64 processed_bytes, qint64 total_bytes) { // if the value is less than the maxmium, this dialog will close itself // add this guard for safety if (processed_bytes >= total_bytes) total_bytes = processed_bytes + 1; if (maximum() != total_bytes) setMaximum(total_bytes); setValue(processed_bytes); more_details_label_->setText(tr("%1 of %2") .arg(::readableFileSizeV2(processed_bytes)) .arg(::readableFileSizeV2(total_bytes))); } void FileBrowserProgressDialog::onTaskFinished(bool success) { if (success) { // printf ("progress dialog: task success\n"); accept(); } else { // printf ("progress dialog: task failed\n"); reject(); } } void FileBrowserProgressDialog::cancel() { task_->cancel(); reject(); }
#include <QLabel> #include <QVBoxLayout> #include <QHBoxLayout> #include <QProgressBar> #include <QPushButton> #include <QDesktopServices> #include <QDebug> #include <climits> #include "utils/utils.h" #include "progress-dialog.h" FileBrowserProgressDialog::FileBrowserProgressDialog(FileNetworkTask *task, QWidget *parent) : QProgressDialog(parent), task_(task->sharedFromThis()) { setWindowModality(Qt::WindowModal); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setWindowIcon(QIcon(":/images/seafile.png")); QVBoxLayout *layout_ = new QVBoxLayout; progress_bar_ = new QProgressBar; description_label_ = new QLabel; layout_->addWidget(description_label_); layout_->addWidget(progress_bar_); QHBoxLayout *hlayout_ = new QHBoxLayout; more_details_label_ = new QLabel; more_details_label_->setText("Pending"); QPushButton *cancel_button_ = new QPushButton(tr("Cancel")); QWidget *spacer = new QWidget; spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); hlayout_->addWidget(more_details_label_); hlayout_->addWidget(spacer); hlayout_->addWidget(cancel_button_); hlayout_->setContentsMargins(-1, 0, -1, 6); layout_->setContentsMargins(-1, 0, -1, 6); layout_->addLayout(hlayout_); setLayout(layout_); setLabel(description_label_); setBar(progress_bar_); setCancelButton(cancel_button_); initTaskInfo(); } FileBrowserProgressDialog::~FileBrowserProgressDialog() { } void FileBrowserProgressDialog::initTaskInfo() { QString title, label; if (task_->type() == FileNetworkTask::Upload) { title = tr("Upload"); label = tr("Uploading %1"); } else { title = tr("Download"); label = tr("Downloading %1"); } setWindowTitle(title); setLabelText(label.arg(task_->fileName())); more_details_label_->setText(""); setMaximum(0); setValue(0); connect(task_.data(), SIGNAL(progressUpdate(qint64, qint64)), this, SLOT(onProgressUpdate(qint64, qint64))); connect(task_.data(), SIGNAL(finished(bool)), this, SLOT(onTaskFinished(bool))); connect(this, SIGNAL(canceled()), task_.data(), SLOT(cancel())); show(); } void FileBrowserProgressDialog::onProgressUpdate(qint64 processed_bytes, qint64 total_bytes) { // if the value is less than the maxmium, this dialog will close itself // add this guard for safety if (processed_bytes >= total_bytes) total_bytes = processed_bytes + 1; if (total_bytes > INT_MAX) { if (maximum() != INT_MAX) setMaximum(INT_MAX); // Avoid overflow double progress = double(processed_bytes) * INT_MAX / total_bytes; setValue((int)progress); } else { if (maximum() != total_bytes) setMaximum(total_bytes); setValue(processed_bytes); } more_details_label_->setText(tr("%1 of %2") .arg(::readableFileSizeV2(processed_bytes)) .arg(::readableFileSizeV2(total_bytes))); } void FileBrowserProgressDialog::onTaskFinished(bool success) { if (success) { // printf ("progress dialog: task success\n"); accept(); } else { // printf ("progress dialog: task failed\n"); reject(); } } void FileBrowserProgressDialog::cancel() { task_->cancel(); reject(); }
Fix integer conversion overflow in `FileBrowserProgressDialog::onProgressUpdate` (#898)
Fix integer conversion overflow in `FileBrowserProgressDialog::onProgressUpdate` (#898)
C++
apache-2.0
haiwen/seafile-client,haiwen/seafile-client,haiwen/seafile-client,haiwen/seafile-client
b65fd5b24d4dc4f14884c2e4e3f10894e333006d
src/condor_c++_util/iso_dates.C
src/condor_c++_util/iso_dates.C
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "iso_dates.h" static bool get_next_bit(const char **current, int count, char *workspace); /*********************************************************************** * * Function: time_to_iso8601 * Purpose: This converts a "struct tm" into a string containing a * representation of the date that conforms to the ISO8601 * standard. * Returns: A string allcoated with malloc. You'll need to free() it * when you're done with it. * Note: We expect a normal struct tm: the year you give is 1900 * less than the actual year, months are 0-11, etc. * ***********************************************************************/ char *time_to_iso8601( const struct tm &time, ISO8601Format format, ISO8601Type type, bool is_utc) { char buffer[128]; char *iso_representation; char *utc_note; int year, month, day; int hour, minute, second; if (type != ISO8601_TimeOnly) { year = 1900 + time.tm_year; // struct tm has year-1900 if (year < 0) year = 0; else if (year > 9999) year = 9999; month = time.tm_mon + 1; // struct tm has 0-11 if (month < 1) month = 1; else if (month > 12) month = 12; day = time.tm_mday; if (day < 1) day = 1; else if (day > 31) day = 31; } if (type != ISO8601_DateOnly) { hour = time.tm_hour; if (hour < 0) hour = 0; else if (hour > 24) hour = 24; // yes, I really mean 24 minute = time.tm_min; if (minute < 0) minute = 0; else if (minute > 60) minute = 60; // yes, I really mean 60 second = time.tm_sec; if (second < 0) second = 0; else if (second > 60) second = 60; // yes, I really mean 60 if (is_utc) utc_note = "Z"; else utc_note = ""; } if (type == ISO8601_DateOnly) { if (format == ISO8601_BasicFormat) { sprintf(buffer, "%04d%02d%02d", year, month, day); } else { sprintf(buffer, "%04d-%02d-%02d", year, month, day); } } else if (type == ISO8601_TimeOnly) { if (format == ISO8601_BasicFormat) { sprintf(buffer, "T%02d%02d%02d%s", hour, minute, second, utc_note); } else { sprintf(buffer, "T%02d:%02d:%02d%s", hour, minute, second, utc_note); } } else { if (format == ISO8601_BasicFormat) { sprintf(buffer, "%04d%02d%02dT%02d%02d%02d%s", year, month, day, hour, minute, second, utc_note); } else { sprintf(buffer, "%04d-%02d-%02dT%02d:%02d:%02d%s", year, month, day, hour, minute, second, utc_note); } } iso_representation = strdup(buffer); return iso_representation; } /*********************************************************************** * * Function: iso8601_to_time * Purpose: This converts a date/time in ISO 8601 format to a "struct * tm". Note that the string may contain a date, a time, * or a date and time. Only the appropriate fields will be * filled in the structure. The wday and yday fields are never * filled in. Any fields that can't be filled in are set to * -1. Also note that we maintain the goofiness of the * "struct tm": the year 2001 is represented as 101, January * is month 0, etc. * ***********************************************************************/ void iso8601_to_time( const char *iso_time, struct tm *time, bool *is_utc) { bool begins_with_time; // Preset to -1, to indicate nothing was parsed. if (time != NULL) { time->tm_year = -1; time->tm_wday = -1; time->tm_yday = -1; time->tm_mon = -1; time->tm_mday = -1; time->tm_hour = -1; time->tm_min = -1; time->tm_sec = -1; } // Only do something if we got valid parameters if (iso_time != NULL && time != NULL) { if (iso_time[0] == 'T' || iso_time[2] == ':') begins_with_time = true; else begins_with_time = false; const char *current; char workspace[6]; current = iso_time; /* ----- Parse the date ----- */ if (!begins_with_time) { if (get_next_bit(&current, 4, workspace)) { time->tm_year = atoi(workspace); time->tm_year -= 1900; } if (get_next_bit(&current, 2, workspace)) { time->tm_mon = atoi(workspace); time->tm_mon -= 1; } if (get_next_bit(&current, 2, workspace)) { time->tm_mday = atoi(workspace); } } /* ----- Parse the time ----- */ if (get_next_bit(&current, 2, workspace)) { time->tm_hour = atoi(workspace); } if (get_next_bit(&current, 2, workspace)) { time->tm_min = atoi(workspace); } if (get_next_bit(&current, 2, workspace)) { time->tm_sec = atoi(workspace); } if (is_utc != NULL) { if (toupper(*current) == 'Z') { *is_utc = true; } else { *is_utc = false; } } } return; } /*********************************************************************** * * Function: get_next_bit * Purpose: This fills in the workspacce with the next "count" characters * from current, and updates current to point just past the * characters is got. * If there aren't enough characters in current to copy, we don't * copy them. We only return true if exactly "count" characters * were copied. * We skip delimiters that may exist in an ISO8601 string. We * are somewhat leninent: for example, you could have a string * like 2001T-T03-03, and it would grab out the correct digits. * This could be good or bad. On the other hand, you couldn't * have 2001*03*03 and have it work. * ***********************************************************************/ static bool get_next_bit( const char **current, int count, char *workspace) { int i; const char *p; bool got_characters; p = *current; // Skip delimiters while (*p == ':' || *p == '-' || *p == 'T') { p++; } // Copy the requested number of characters into the workspace, // assuming that we actually have them. i = 0; while (i < count && *p != 0) { workspace[i++] = *p; p++; } // Null terminate the workspace, to make a valid string. workspace[i] = 0; *current = p; if (i == count) got_characters = true; else got_characters = false; return got_characters; }
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "iso_dates.h" static bool get_next_bit(const char **current, int count, char *workspace); /*********************************************************************** * * Function: time_to_iso8601 * Purpose: This converts a "struct tm" into a string containing a * representation of the date that conforms to the ISO8601 * standard. * Returns: A string allcoated with malloc. You'll need to free() it * when you're done with it. * Note: We expect a normal struct tm: the year you give is 1900 * less than the actual year, months are 0-11, etc. * ***********************************************************************/ char *time_to_iso8601( const struct tm &time, ISO8601Format format, ISO8601Type type, bool is_utc) { char buffer[128]; char *iso_representation; char *utc_note; int year, month, day; int hour, minute, second; if (type != ISO8601_TimeOnly) { year = 1900 + time.tm_year; // struct tm has year-1900 if (year < 0) year = 0; else if (year > 9999) year = 9999; month = time.tm_mon + 1; // struct tm has 0-11 if (month < 1) month = 1; else if (month > 12) month = 12; day = time.tm_mday; if (day < 1) day = 1; else if (day > 31) day = 31; } if (type != ISO8601_DateOnly) { hour = time.tm_hour; if (hour < 0) hour = 0; else if (hour > 24) hour = 24; // yes, I really mean 24 minute = time.tm_min; if (minute < 0) minute = 0; else if (minute > 60) minute = 60; // yes, I really mean 60 second = time.tm_sec; if (second < 0) second = 0; else if (second > 60) second = 60; // yes, I really mean 60 if (is_utc) utc_note = "Z"; else utc_note = ""; } if (type == ISO8601_DateOnly) { if (format == ISO8601_BasicFormat) { sprintf(buffer, "%04d%02d%02d", year, month, day); } else { sprintf(buffer, "%04d-%02d-%02d", year, month, day); } } else if (type == ISO8601_TimeOnly) { if (format == ISO8601_BasicFormat) { sprintf(buffer, "T%02d%02d%02d%s", hour, minute, second, utc_note); } else { sprintf(buffer, "T%02d:%02d:%02d%s", hour, minute, second, utc_note); } } else { if (format == ISO8601_BasicFormat) { sprintf(buffer, "%04d%02d%02dT%02d%02d%02d%s", year, month, day, hour, minute, second, utc_note); } else { sprintf(buffer, "%04d-%02d-%02dT%02d:%02d:%02d%s", year, month, day, hour, minute, second, utc_note); } } iso_representation = strdup(buffer); return iso_representation; } /*********************************************************************** * * Function: iso8601_to_time * Purpose: This converts a date/time in ISO 8601 format to a "struct * tm". Note that the string may contain a date, a time, * or a date and time. Only the appropriate fields will be * filled in the structure. The wday and yday fields are never * filled in. Any fields that can't be filled in are set to * -1. Also note that we maintain the goofiness of the * "struct tm": the year 2001 is represented as 101, January * is month 0, etc. * ***********************************************************************/ void iso8601_to_time( const char *iso_time, struct tm *time, bool *is_utc) { bool begins_with_time; // Preset to -1, to indicate nothing was parsed. if (time != NULL) { time->tm_year = -1; time->tm_wday = -1; time->tm_yday = -1; time->tm_mon = -1; time->tm_mday = -1; time->tm_hour = -1; time->tm_min = -1; time->tm_sec = -1; time->tm_isdst = -1; } // Only do something if we got valid parameters if (iso_time != NULL && time != NULL) { if (iso_time[0] == 'T' || iso_time[2] == ':') begins_with_time = true; else begins_with_time = false; const char *current; char workspace[6]; current = iso_time; /* ----- Parse the date ----- */ if (!begins_with_time) { if (get_next_bit(&current, 4, workspace)) { time->tm_year = atoi(workspace); time->tm_year -= 1900; } if (get_next_bit(&current, 2, workspace)) { time->tm_mon = atoi(workspace); time->tm_mon -= 1; } if (get_next_bit(&current, 2, workspace)) { time->tm_mday = atoi(workspace); } } /* ----- Parse the time ----- */ if (get_next_bit(&current, 2, workspace)) { time->tm_hour = atoi(workspace); } if (get_next_bit(&current, 2, workspace)) { time->tm_min = atoi(workspace); } if (get_next_bit(&current, 2, workspace)) { time->tm_sec = atoi(workspace); } if (is_utc != NULL) { if (toupper(*current) == 'Z') { *is_utc = true; } else { *is_utc = false; } } } return; } /*********************************************************************** * * Function: get_next_bit * Purpose: This fills in the workspacce with the next "count" characters * from current, and updates current to point just past the * characters is got. * If there aren't enough characters in current to copy, we don't * copy them. We only return true if exactly "count" characters * were copied. * We skip delimiters that may exist in an ISO8601 string. We * are somewhat leninent: for example, you could have a string * like 2001T-T03-03, and it would grab out the correct digits. * This could be good or bad. On the other hand, you couldn't * have 2001*03*03 and have it work. * ***********************************************************************/ static bool get_next_bit( const char **current, int count, char *workspace) { int i; const char *p; bool got_characters; p = *current; // Skip delimiters while (*p == ':' || *p == '-' || *p == 'T') { p++; } // Copy the requested number of characters into the workspace, // assuming that we actually have them. i = 0; while (i < count && *p != 0) { workspace[i++] = *p; p++; } // Null terminate the workspace, to make a valid string. workspace[i] = 0; *current = p; if (i == count) got_characters = true; else got_characters = false; return got_characters; }
Initialize time->tm_isdst to indicate we don't know if DST is in effect.
Initialize time->tm_isdst to indicate we don't know if DST is in effect.
C++
apache-2.0
zhangzhehust/htcondor,djw8605/htcondor,zhangzhehust/htcondor,clalancette/condor-dcloud,djw8605/htcondor,djw8605/htcondor,djw8605/condor,mambelli/osg-bosco-marco,htcondor/htcondor,mambelli/osg-bosco-marco,zhangzhehust/htcondor,zhangzhehust/htcondor,djw8605/condor,clalancette/condor-dcloud,htcondor/htcondor,bbockelm/condor-network-accounting,neurodebian/htcondor,mambelli/osg-bosco-marco,mambelli/osg-bosco-marco,clalancette/condor-dcloud,djw8605/htcondor,neurodebian/htcondor,djw8605/condor,zhangzhehust/htcondor,neurodebian/htcondor,htcondor/htcondor,neurodebian/htcondor,clalancette/condor-dcloud,neurodebian/htcondor,htcondor/htcondor,neurodebian/htcondor,djw8605/htcondor,zhangzhehust/htcondor,djw8605/condor,clalancette/condor-dcloud,htcondor/htcondor,djw8605/condor,neurodebian/htcondor,bbockelm/condor-network-accounting,mambelli/osg-bosco-marco,djw8605/htcondor,neurodebian/htcondor,djw8605/htcondor,bbockelm/condor-network-accounting,bbockelm/condor-network-accounting,mambelli/osg-bosco-marco,bbockelm/condor-network-accounting,djw8605/condor,bbockelm/condor-network-accounting,htcondor/htcondor,bbockelm/condor-network-accounting,zhangzhehust/htcondor,mambelli/osg-bosco-marco,mambelli/osg-bosco-marco,djw8605/condor,djw8605/htcondor,neurodebian/htcondor,bbockelm/condor-network-accounting,htcondor/htcondor,clalancette/condor-dcloud,zhangzhehust/htcondor,zhangzhehust/htcondor,djw8605/condor,djw8605/htcondor,htcondor/htcondor,clalancette/condor-dcloud
cbce775a0cacc68e7b5b665bcd778dc604145755
cores/cosa/Cosa/Event.hh
cores/cosa/Cosa/Event.hh
/** * @file Cosa/Event.hh * @version 1.0 * * @section License * Copyright (C) 2012-2015, Mikael Patel * * 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. * * This file is part of the Arduino Che Cosa project. */ #ifndef COSA_EVENT_HH #define COSA_EVENT_HH #include "Cosa/Types.h" #include "Cosa/Queue.hh" #ifndef COSA_EVENT_QUEUE_MAX #if defined(BOARD_ATTINY) #define COSA_EVENT_QUEUE_MAX 8 #else #define COSA_EVENT_QUEUE_MAX 16 #endif #endif /** * Event data structure with type, source and value. */ class Event { public: /** * Size of event queue. Adjust depending on application. Must be * Power(2). */ static const uint8_t QUEUE_MAX = COSA_EVENT_QUEUE_MAX; /** * Event types are added here. Typical mapping from interrupts to * events. Note that the event is not a global numbering * scheme. Instead depends on the receiving/sending party, the * protocol. */ enum { NULL_TYPE = 0, FALLING_TYPE, // Digital Pins RISING_TYPE, CHANGE_TYPE, SAMPLE_REQUEST_TYPE, // Analog Pins SAMPLE_COMPLETED_TYPE, WATCHDOG_TYPE, // Watchdog and timers TIMEOUT_TYPE, BEGIN_TYPE, // Finite State Machines END_TYPE, RUN_TYPE, // Thread CONNECT_TYPE, // Device drivers and protocol stacks DISCONNECT_TYPE, RECEIVE_REQUEST_TYPE, RECEIVE_COMPLETED_TYPE, SEND_REQUEST_TYPE, SEND_COMPLETED_TYPE, OPEN_TYPE, // Device drivers and storage CLOSE_TYPE, READ_REQUEST_TYPE, READ_COMPLETED_TYPE, WRITE_REQUEST_TYPE, WRITE_COMPLETED_TYPE, COMMAND_REQUEST_TYPE, COMMAND_COMPLETED_TYPE, SERVICE_REQUEST_TYPE, // Servers SERVICE_RESPONSE_TYPE, USER_TYPE = 64, // User defined events/messages, 64-254 ERROR_TYPE = 255 // Error event } __attribute__((packed)); /** * Event handler root class. */ class Handler { public: /** * @override Event::Handler * Default null event handler. Should be redefined by sub-classes. * Called by Event::dispatch(). * @param[in] type the event type. * @param[in] value the event value. */ virtual void on_event(uint8_t type, uint16_t value) { UNUSED(type); UNUSED(value); } }; public: /** * Construct event with given type, target and value. * @param[in] type event identity (default NULL_TYPE(0)). * @param[in] target event receiver (default null(0)). * @param[in] value event value (default zero(0)). */ Event(int8_t type = NULL_TYPE, Handler* target = NULL, uint16_t value = 0) : m_type(type), m_target(target), m_value(value) {} /** * Return event type. * @return type. */ uint8_t get_type() const { return (m_type); } /** * Return event target. * @return pointer. */ Handler* get_target() const { return (m_target); } /** * Return event value. * @return value. */ uint16_t get_value() const { return (m_value); } /** * Return event environment pointer. * @return pointer. */ void* get_env() const { return ((void*) m_value); } /** * Dispatch event handler for target object. */ void dispatch() __attribute__((always_inline)) { if (m_target != NULL) m_target->on_event(m_type, m_value); } /** * Push an event with given type, source and value into the event queue. * Return true(1) if successful otherwise false(0). * @param[in] type event identity. * @param[in] target event target. * @param[in] value event value. * @return bool. */ static bool push(uint8_t type, Handler* target, uint16_t value = 0) __attribute__((always_inline)) { Event event(type, target, value); return (queue.enqueue(&event)); } /** * Push an event with given type, source and value into the event queue. * Return true(1) if successful otherwise false(0). * @param[in] type event identity. * @param[in] target event target. * @param[in] env event environment pointer. * @return bool. */ static bool push(uint8_t type, Handler* target, void* env) __attribute__((always_inline)) { return (push(type, target, (uint16_t) env)); } /** * Event queue of size QUEUE_MAX. */ static Queue<Event, QUEUE_MAX> queue; /** * Service events and wait at most given number of milliseconds. The * value zero(0) indicates that call should block until an event. * @param[in] ms maximum wait time (Default blocking). * @return true(1) if an event was dispatched otherwise false(0). */ static bool service(uint32_t ms = 0L); private: uint8_t m_type; //!< Event type. Handler* m_target; //!< Event target object (receiver). uint16_t m_value; //!< Event parameter and/or value. }; #endif
/** * @file Cosa/Event.hh * @version 1.0 * * @section License * Copyright (C) 2012-2015, Mikael Patel * * 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. * * This file is part of the Arduino Che Cosa project. */ #ifndef COSA_EVENT_HH #define COSA_EVENT_HH #include "Cosa/Types.h" #include "Cosa/Queue.hh" // Default event queue size #ifndef COSA_EVENT_QUEUE_MAX # if defined(BOARD_ATTINY) # define COSA_EVENT_QUEUE_MAX 8 # else # define COSA_EVENT_QUEUE_MAX 16 # endif #endif /** * Event data structure with type, source and value. */ class Event { public: /** * Size of event queue. Adjust depending on application. Must be * Power(2). Class Queue will statically check this. */ static const uint8_t QUEUE_MAX = COSA_EVENT_QUEUE_MAX; /** * Event types are added here. Typical mapping from interrupts to * events. Note that the event is not a global numbering * scheme. Instead depends on the receiving/sending party, the * protocol. */ enum { NULL_TYPE = 0, FALLING_TYPE, // Digital Pins RISING_TYPE, CHANGE_TYPE, SAMPLE_REQUEST_TYPE, // Analog Pins SAMPLE_COMPLETED_TYPE, WATCHDOG_TYPE, // Watchdog and timers TIMEOUT_TYPE, BEGIN_TYPE, // Finite State Machines END_TYPE, RUN_TYPE, // Thread CONNECT_TYPE, // Device drivers and protocol stacks DISCONNECT_TYPE, RECEIVE_REQUEST_TYPE, RECEIVE_COMPLETED_TYPE, SEND_REQUEST_TYPE, SEND_COMPLETED_TYPE, OPEN_TYPE, // Device drivers and storage CLOSE_TYPE, READ_REQUEST_TYPE, READ_COMPLETED_TYPE, WRITE_REQUEST_TYPE, WRITE_COMPLETED_TYPE, COMMAND_REQUEST_TYPE, COMMAND_COMPLETED_TYPE, SERVICE_REQUEST_TYPE, // Servers SERVICE_RESPONSE_TYPE, USER_TYPE = 64, // User defined events/messages, 64-254 ERROR_TYPE = 255 // Error event } __attribute__((packed)); /** * Event handler root class. */ class Handler { public: /** * @override Event::Handler * Default null event handler. Should be redefined by sub-classes. * Called by Event::dispatch(). * @param[in] type the event type. * @param[in] value the event value. */ virtual void on_event(uint8_t type, uint16_t value) { UNUSED(type); UNUSED(value); } }; public: /** * Construct event with given type, target and value. * @param[in] type event identity (default NULL_TYPE(0)). * @param[in] target event receiver (default null(0)). * @param[in] value event value (default zero(0)). */ Event(int8_t type = NULL_TYPE, Handler* target = NULL, uint16_t value = 0) : m_type(type), m_target(target), m_value(value) {} /** * Return event type. * @return type. */ uint8_t get_type() const { return (m_type); } /** * Return event target. * @return pointer. */ Handler* get_target() const { return (m_target); } /** * Return event value. * @return value. */ uint16_t get_value() const { return (m_value); } /** * Return event environment pointer. * @return pointer. */ void* get_env() const { return ((void*) m_value); } /** * Dispatch event handler for target object. */ void dispatch() __attribute__((always_inline)) { if (m_target != NULL) m_target->on_event(m_type, m_value); } /** * Push an event with given type, source and value into the event queue. * Return true(1) if successful otherwise false(0). * @param[in] type event identity. * @param[in] target event target. * @param[in] value event value. * @return bool. */ static bool push(uint8_t type, Handler* target, uint16_t value = 0) __attribute__((always_inline)) { Event event(type, target, value); return (queue.enqueue(&event)); } /** * Push an event with given type, source and value into the event queue. * Return true(1) if successful otherwise false(0). * @param[in] type event identity. * @param[in] target event target. * @param[in] env event environment pointer. * @return bool. */ static bool push(uint8_t type, Handler* target, void* env) __attribute__((always_inline)) { return (push(type, target, (uint16_t) env)); } /** * Event queue of size QUEUE_MAX. */ static Queue<Event, QUEUE_MAX> queue; /** * Service events and wait at most given number of milliseconds. The * value zero(0) indicates that call should block until an event. * @param[in] ms maximum wait time (Default blocking). * @return true(1) if an event was dispatched otherwise false(0). */ static bool service(uint32_t ms = 0L); private: uint8_t m_type; //!< Event type. Handler* m_target; //!< Event target object (receiver). uint16_t m_value; //!< Event parameter and/or value. }; #endif
Add Event queue size to configuration.
Add Event queue size to configuration.
C++
lgpl-2.1
jeditekunum/Cosa,jeditekunum/Cosa,rrobinet/Cosa,jeditekunum/Cosa,mikaelpatel/Cosa,dansut/Cosa,rrobinet/Cosa,dansut/Cosa,dansut/Cosa,rrobinet/Cosa,mikaelpatel/Cosa,rrobinet/Cosa,dansut/Cosa,mikaelpatel/Cosa,jeditekunum/Cosa,mikaelpatel/Cosa
4f6c3166b8a59810ed4aa12d6ccc80e86ddfbc9a
TRD/AliTRDpidESD.cxx
TRD/AliTRDpidESD.cxx
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //----------------------------------------------------------------- // Implementation of the TRD PID class // Assigns the electron and pion liklihoods for each ESD track. // The AliTRDprobdist class is instantiated here. // The function MakePID(AliESD *event) calculates the probability // of having dedx and the probability of having timbin at a given // momentum (mom) and particle type k (0 for e) and (2 for pi) // from the precalculated timbin distributions. // Prashant Shukla <[email protected]> //----------------------------------------------------------------- #include "AliTRDpidESD.h" #include "AliESD.h" #include "AliESDtrack.h" #include "AliTRDprobdist.h" ClassImp(AliTRDpidESD) //_________________________________________________________________________ AliTRDpidESD::AliTRDpidESD(Double_t *param) { // // The main constructor // fMIP=param[0]; // MIP signal fRes=param[1]; // relative resolution fRange=param[2]; // PID "range" (in sigmas) } Double_t AliTRDpidESD::Bethe(Double_t bg) { // // Parametrization of the Bethe-Bloch-curve // The parametrization is the same as for the TPC and is taken from Lehrhaus. // // This parameters have been adjusted to averaged values from GEANT const Double_t kP1 = 7.17960e-02; const Double_t kP2 = 8.54196; const Double_t kP3 = 1.38065e-06; const Double_t kP4 = 5.30972; const Double_t kP5 = 2.83798; // This parameters have been adjusted to Xe-data found in: // Allison & Cobb, Ann. Rev. Nucl. Sci. (1980), 30, 253 //const Double_t kP1 = 0.76176E-1; //const Double_t kP2 = 10.632; //const Double_t kP3 = 3.17983E-6; //const Double_t kP4 = 1.8631; //const Double_t kP5 = 1.9479; // Lower cutoff of the Bethe-Bloch-curve to limit step sizes const Double_t kBgMin = 0.8; const Double_t kBBMax = 6.83298; //const Double_t kBgMin = 0.6; //const Double_t kBBMax = 17.2809; //const Double_t kBgMin = 0.4; //const Double_t kBBMax = 82.0; if (bg > kBgMin) { Double_t yy = bg / TMath::Sqrt(1. + bg*bg); Double_t aa = TMath::Power(yy,kP4); Double_t bb = TMath::Power((1./bg),kP5); bb = TMath::Log(kP3 + bb); return ((kP2 - aa - bb)*kP1 / aa); } else { return kBBMax; } } //_________________________________________________________________________ Int_t AliTRDpidESD::MakePID(AliESD *event) { // // This function calculates the "detector response" PID probabilities // // The class AliTRDprobdist contains precalculated prob dis. AliTRDprobdist *pd = new AliTRDprobdist(); // Double_t ebin[200], ppi[200], pel[200]; // pd->GetData(2,ebin,ppi,pel); // for(Int_t ie=0; ie<10; ie++) // printf(" %f %f %f \n", ebin[ie], ppi[ie], pel[ie]); Int_t ntrk=event->GetNumberOfTracks(); for (Int_t i=0; i<ntrk; i++) { AliESDtrack *t=event->GetTrack(i); if ((t->GetStatus()&AliESDtrack::kTRDin)==0) if ((t->GetStatus()&AliESDtrack::kTRDout)==0) if ((t->GetStatus()&AliESDtrack::kTRDrefit)==0) continue; if(t->GetTRDsignal()==0) continue; // Int_t ns=AliESDtrack::kSPECIES; Int_t ns=AliPID::kSPECIES; Double_t p[10]; Double_t mom=t->GetP(); for (Int_t j=0; j<ns; j++) { p[j]=1.; for (Int_t ilayer=0; ilayer <6; ilayer++) { Double_t dedx=t->GetTRDsignals(ilayer); Int_t timbin=t->GetTRDTimBin(ilayer); if (j==0 || j==2){ p[j]*= pd->GetProbability(j,mom,dedx); p[j]*= pd->GetProbabilityT(j,mom,timbin); p[j]*= 100; } } // loop over layers } //loop over particle species // printf(" %f %d %f %f %f \n", mom, timbin, p[0], p[1], p[2]); if(p[0]) p[0]= p[0]/(p[0]+p[2]); if(p[2]) p[2]= 1.-p[0]; t->SetTRDpid(p); } //loop over track delete pd; return 0; } /* //_________________________________________________________________________ MakePID(AliESD *event) { // // This function calculates the "detector response" PID probabilities // Int_t ntrk=event->GetNumberOfTracks(); for (Int_t i=0; i<ntrk; i++) { AliESDtrack *t=event->GetTrack(i); if ((t->GetStatus()&AliESDtrack::kTRDin)==0) if ((t->GetStatus()&AliESDtrack::kTRDout)==0) if ((t->GetStatus()&AliESDtrack::kTRDrefit)==0) continue; // Int_t ns=AliESDtrack::kSPECIES; Int_t ns=AliPID::kSPECIES; Double_t p[10]; for (Int_t j=0; j<ns; j++) { Double_t mass=AliPID::ParticleMass(j); Double_t mass=masses[j]; Double_t mom=t->GetP(); Double_t dedx=t->GetTRDsignal()/fMIP; Double_t bethe= AliTRDpidESD::Bethe(mom/mass); Double_t sigma=fRes*bethe; if (TMath::Abs(dedx-bethe) > fRange*sigma) { p[j]=TMath::Exp(-0.5*fRange*fRange)/sigma; continue; } p[j]=TMath::Exp(-0.5*(dedx-bethe)*(dedx-bethe)/(sigma*sigma))/sigma; } t->SetTRDpid(p); // if(i==50) printf("%f %f %f \n", p[0], p[1], p[2]); } return 0; } */
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //----------------------------------------------------------------- // Implementation of the TRD PID class // Assigns the electron and pion liklihoods for each ESD track. // The AliTRDprobdist class is instantiated here. // The function MakePID(AliESD *event) calculates the probability // of having dedx and the probability of having timbin at a given // momentum (mom) and particle type k (0 for e) and (2 for pi) // from the precalculated timbin distributions. // Prashant Shukla <[email protected]> //----------------------------------------------------------------- #include "AliTRDpidESD.h" #include "AliESD.h" #include "AliESDtrack.h" #include "AliTRDprobdist.h" ClassImp(AliTRDpidESD) //_________________________________________________________________________ AliTRDpidESD::AliTRDpidESD(Double_t *param) { // // The main constructor // fMIP=param[0]; // MIP signal fRes=param[1]; // relative resolution fRange=param[2]; // PID "range" (in sigmas) } Double_t AliTRDpidESD::Bethe(Double_t bg) { // // Parametrization of the Bethe-Bloch-curve // The parametrization is the same as for the TPC and is taken from Lehrhaus. // // This parameters have been adjusted to averaged values from GEANT const Double_t kP1 = 7.17960e-02; const Double_t kP2 = 8.54196; const Double_t kP3 = 1.38065e-06; const Double_t kP4 = 5.30972; const Double_t kP5 = 2.83798; // This parameters have been adjusted to Xe-data found in: // Allison & Cobb, Ann. Rev. Nucl. Sci. (1980), 30, 253 //const Double_t kP1 = 0.76176E-1; //const Double_t kP2 = 10.632; //const Double_t kP3 = 3.17983E-6; //const Double_t kP4 = 1.8631; //const Double_t kP5 = 1.9479; // Lower cutoff of the Bethe-Bloch-curve to limit step sizes const Double_t kBgMin = 0.8; const Double_t kBBMax = 6.83298; //const Double_t kBgMin = 0.6; //const Double_t kBBMax = 17.2809; //const Double_t kBgMin = 0.4; //const Double_t kBBMax = 82.0; if (bg > kBgMin) { Double_t yy = bg / TMath::Sqrt(1. + bg*bg); Double_t aa = TMath::Power(yy,kP4); Double_t bb = TMath::Power((1./bg),kP5); bb = TMath::Log(kP3 + bb); return ((kP2 - aa - bb)*kP1 / aa); } else { return kBBMax; } } //_________________________________________________________________________ Int_t AliTRDpidESD::MakePID(AliESD *event) { // // This function calculates the "detector response" PID probabilities // // The class AliTRDprobdist contains precalculated prob dis. AliTRDprobdist *pd = new AliTRDprobdist(); // Double_t ebin[200], ppi[200], pel[200]; // pd->GetData(2,ebin,ppi,pel); // for(Int_t ie=0; ie<10; ie++) // printf(" %f %f %f \n", ebin[ie], ppi[ie], pel[ie]); Int_t ntrk=event->GetNumberOfTracks(); for (Int_t i=0; i<ntrk; i++) { AliESDtrack *t=event->GetTrack(i); if ((t->GetStatus()&AliESDtrack::kTRDin)==0) if ((t->GetStatus()&AliESDtrack::kTRDout)==0) if ((t->GetStatus()&AliESDtrack::kTRDrefit)==0) continue; if(t->GetTRDsignal()==0) continue; // Int_t ns=AliESDtrack::kSPECIES; Int_t ns=AliPID::kSPECIES; Double_t p[10]; Double_t mom=t->GetP(); for (Int_t j=0; j<ns; j++) { p[j]=1.; for (Int_t ilayer=0; ilayer <6; ilayer++) { Double_t dedx=t->GetTRDsignals(ilayer); Int_t timbin=t->GetTRDTimBin(ilayer); if (j==0 || j==2){ p[j]*= pd->GetProbability(j,mom,dedx); p[j]*= pd->GetProbabilityT(j,mom,timbin); p[j]*= 100; } } // loop over layers } //loop over particle species // printf(" %f %d %f %f %f \n", mom, timbin, p[0], p[1], p[2]); if(p[0]) p[0]= p[0]/(p[0]+p[2]); if(p[2]) p[2]= 1.-p[0]; if(p[0]==0&p[2]==0){ p[0]=1.; p[2]=1.; } t->SetTRDpid(p); } //loop over track delete pd; return 0; } /* //_________________________________________________________________________ MakePID(AliESD *event) { // // This function calculates the "detector response" PID probabilities // Int_t ntrk=event->GetNumberOfTracks(); for (Int_t i=0; i<ntrk; i++) { AliESDtrack *t=event->GetTrack(i); if ((t->GetStatus()&AliESDtrack::kTRDin)==0) if ((t->GetStatus()&AliESDtrack::kTRDout)==0) if ((t->GetStatus()&AliESDtrack::kTRDrefit)==0) continue; // Int_t ns=AliESDtrack::kSPECIES; Int_t ns=AliPID::kSPECIES; Double_t p[10]; for (Int_t j=0; j<ns; j++) { Double_t mass=AliPID::ParticleMass(j); Double_t mass=masses[j]; Double_t mom=t->GetP(); Double_t dedx=t->GetTRDsignal()/fMIP; Double_t bethe= AliTRDpidESD::Bethe(mom/mass); Double_t sigma=fRes*bethe; if (TMath::Abs(dedx-bethe) > fRange*sigma) { p[j]=TMath::Exp(-0.5*fRange*fRange)/sigma; continue; } p[j]=TMath::Exp(-0.5*(dedx-bethe)*(dedx-bethe)/(sigma*sigma))/sigma; } t->SetTRDpid(p); // if(i==50) printf("%f %f %f \n", p[0], p[1], p[2]); } return 0; } */
Set Probabilities to zero if there is no signal in any plane
Set Probabilities to zero if there is no signal in any plane
C++
bsd-3-clause
shahor02/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,alisw/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,shahor02/AliRoot,coppedis/AliRoot,miranov25/AliRoot,alisw/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,shahor02/AliRoot,alisw/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,ALICEHLT/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,sebaleh/AliRoot
b4264b12a51ecea93517a84f94c15f8e97b2f50f
examples/script/customclass/bytearrayclass.cpp
examples/script/customclass/bytearrayclass.cpp
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://www.qtsoftware.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtScript/QScriptClassPropertyIterator> #include <QtScript/QScriptEngine> #include "bytearrayclass.h" #include "bytearrayprototype.h" #include <stdlib.h> Q_DECLARE_METATYPE(QByteArray*) Q_DECLARE_METATYPE(ByteArrayClass*) class ByteArrayClassPropertyIterator : public QScriptClassPropertyIterator { public: ByteArrayClassPropertyIterator(const QScriptValue &object); ~ByteArrayClassPropertyIterator(); bool hasNext() const; void next(); bool hasPrevious() const; void previous(); void toFront(); void toBack(); QScriptString name() const; uint id() const; private: int m_index; int m_last; }; static qint32 toArrayIndex(const QString &str) { QByteArray bytes = str.toUtf8(); char *eptr; quint32 pos = strtoul(bytes.constData(), &eptr, 10); if ((eptr == bytes.constData() + bytes.size()) && (QByteArray::number(pos) == bytes)) { return pos; } return -1; } //! [0] ByteArrayClass::ByteArrayClass(QScriptEngine *engine) : QObject(engine), QScriptClass(engine) { qScriptRegisterMetaType<QByteArray>(engine, toScriptValue, fromScriptValue); length = engine->toStringHandle(QLatin1String("length")); proto = engine->newQObject(new ByteArrayPrototype(this), QScriptEngine::QtOwnership, QScriptEngine::SkipMethodsInEnumeration | QScriptEngine::ExcludeSuperClassMethods | QScriptEngine::ExcludeSuperClassProperties); QScriptValue global = engine->globalObject(); proto.setPrototype(global.property("Object").property("prototype")); ctor = engine->newFunction(construct, proto); ctor.setData(qScriptValueFromValue(engine, this)); } //! [0] ByteArrayClass::~ByteArrayClass() { } //! [3] QScriptClass::QueryFlags ByteArrayClass::queryProperty(const QScriptValue &object, const QScriptString &name, QueryFlags flags, uint *id) { QByteArray *ba = qscriptvalue_cast<QByteArray*>(object.data()); if (!ba) return 0; if (name == length) { return flags; } else { qint32 pos = toArrayIndex(name); if (pos == -1) return 0; *id = pos; if ((flags & HandlesReadAccess) && (pos >= ba->size())) flags &= ~HandlesReadAccess; return flags; } } //! [3] //! [4] QScriptValue ByteArrayClass::property(const QScriptValue &object, const QScriptString &name, uint id) { QByteArray *ba = qscriptvalue_cast<QByteArray*>(object.data()); if (!ba) return QScriptValue(); if (name == length) { return ba->length(); } else { qint32 pos = id; if ((pos < 0) || (pos >= ba->size())) return QScriptValue(); return uint(ba->at(pos)) & 255; } return QScriptValue(); } //! [4] //! [5] void ByteArrayClass::setProperty(QScriptValue &object, const QScriptString &name, uint id, const QScriptValue &value) { QByteArray *ba = qscriptvalue_cast<QByteArray*>(object.data()); if (!ba) return; if (name == length) { ba->resize(value.toInt32()); } else { qint32 pos = id; if (pos < 0) return; if (ba->size() <= pos) ba->resize(pos + 1); (*ba)[pos] = char(value.toInt32()); } } //! [5] //! [6] QScriptValue::PropertyFlags ByteArrayClass::propertyFlags( const QScriptValue &/*object*/, const QScriptString &name, uint /*id*/) { if (name == length) { return QScriptValue::Undeletable | QScriptValue::SkipInEnumeration; } return QScriptValue::Undeletable; } //! [6] //! [7] QScriptClassPropertyIterator *ByteArrayClass::newIterator(const QScriptValue &object) { return new ByteArrayClassPropertyIterator(object); } //! [7] QString ByteArrayClass::name() const { return QLatin1String("ByteArray"); } QScriptValue ByteArrayClass::prototype() const { return proto; } QScriptValue ByteArrayClass::constructor() { return ctor; } QScriptValue ByteArrayClass::newInstance(int size) { return newInstance(QByteArray(size, /*ch=*/0)); } //! [1] QScriptValue ByteArrayClass::newInstance(const QByteArray &ba) { QScriptValue data = engine()->newVariant(qVariantFromValue(ba)); return engine()->newObject(this, data); } //! [1] //! [2] QScriptValue ByteArrayClass::construct(QScriptContext *ctx, QScriptEngine *) { ByteArrayClass *cls = qscriptvalue_cast<ByteArrayClass*>(ctx->callee().data()); if (!cls) return QScriptValue(); QScriptValue arg = ctx->argument(0); if (arg.instanceOf(ctx->callee())) return cls->newInstance(qscriptvalue_cast<QByteArray>(arg)); int size = arg.toInt32(); return cls->newInstance(size); } //! [2] QScriptValue ByteArrayClass::toScriptValue(QScriptEngine *eng, const QByteArray &ba) { QScriptValue ctor = eng->globalObject().property("ByteArray"); ByteArrayClass *cls = qscriptvalue_cast<ByteArrayClass*>(ctor.data()); if (!cls) return eng->newVariant(qVariantFromValue(ba)); return cls->newInstance(ba); } void ByteArrayClass::fromScriptValue(const QScriptValue &obj, QByteArray &ba) { ba = qvariant_cast<QByteArray>(obj.data().toVariant()); } ByteArrayClassPropertyIterator::ByteArrayClassPropertyIterator(const QScriptValue &object) : QScriptClassPropertyIterator(object) { toFront(); } ByteArrayClassPropertyIterator::~ByteArrayClassPropertyIterator() { } //! [8] bool ByteArrayClassPropertyIterator::hasNext() const { QByteArray *ba = qscriptvalue_cast<QByteArray*>(object().data()); return m_index < ba->size(); } void ByteArrayClassPropertyIterator::next() { m_last = m_index; ++m_index; } bool ByteArrayClassPropertyIterator::hasPrevious() const { return (m_index > 0); } void ByteArrayClassPropertyIterator::previous() { --m_index; m_last = m_index; } void ByteArrayClassPropertyIterator::toFront() { m_index = 0; m_last = -1; } void ByteArrayClassPropertyIterator::toBack() { QByteArray *ba = qscriptvalue_cast<QByteArray*>(object().data()); m_index = ba->size(); m_last = -1; } QScriptString ByteArrayClassPropertyIterator::name() const { return QScriptString(); } uint ByteArrayClassPropertyIterator::id() const { return m_last; } //! [8]
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://www.qtsoftware.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtScript/QScriptClassPropertyIterator> #include <QtScript/QScriptEngine> #include "bytearrayclass.h" #include "bytearrayprototype.h" #include <stdlib.h> Q_DECLARE_METATYPE(QByteArray*) Q_DECLARE_METATYPE(ByteArrayClass*) class ByteArrayClassPropertyIterator : public QScriptClassPropertyIterator { public: ByteArrayClassPropertyIterator(const QScriptValue &object); ~ByteArrayClassPropertyIterator(); bool hasNext() const; void next(); bool hasPrevious() const; void previous(); void toFront(); void toBack(); QScriptString name() const; uint id() const; private: int m_index; int m_last; }; static qint32 toArrayIndex(const QString &str) { QByteArray bytes = str.toUtf8(); char *eptr; quint32 pos = strtoul(bytes.constData(), &eptr, 10); if ((eptr == bytes.constData() + bytes.size()) && (QByteArray::number(pos) == bytes)) { return pos; } return -1; } //! [0] ByteArrayClass::ByteArrayClass(QScriptEngine *engine) : QObject(engine), QScriptClass(engine) { qScriptRegisterMetaType<QByteArray>(engine, toScriptValue, fromScriptValue); length = engine->toStringHandle(QLatin1String("length")); proto = engine->newQObject(new ByteArrayPrototype(this), QScriptEngine::QtOwnership, QScriptEngine::SkipMethodsInEnumeration | QScriptEngine::ExcludeSuperClassMethods | QScriptEngine::ExcludeSuperClassProperties); QScriptValue global = engine->globalObject(); proto.setPrototype(global.property("Object").property("prototype")); ctor = engine->newFunction(construct, proto); ctor.setData(qScriptValueFromValue(engine, this)); } //! [0] ByteArrayClass::~ByteArrayClass() { } //! [3] QScriptClass::QueryFlags ByteArrayClass::queryProperty(const QScriptValue &object, const QScriptString &name, QueryFlags flags, uint *id) { QByteArray *ba = qscriptvalue_cast<QByteArray*>(object.data()); if (!ba) return 0; if (name == length) { return flags; } else { qint32 pos = toArrayIndex(name); if (pos == -1) return 0; *id = pos; if ((flags & HandlesReadAccess) && (pos >= ba->size())) flags &= ~HandlesReadAccess; return flags; } } //! [3] //! [4] QScriptValue ByteArrayClass::property(const QScriptValue &object, const QScriptString &name, uint id) { QByteArray *ba = qscriptvalue_cast<QByteArray*>(object.data()); if (!ba) return QScriptValue(); if (name == length) { return ba->length(); } else { qint32 pos = id; if ((pos < 0) || (pos >= ba->size())) return QScriptValue(); return uint(ba->at(pos)) & 255; } return QScriptValue(); } //! [4] //! [5] void ByteArrayClass::setProperty(QScriptValue &object, const QScriptString &name, uint id, const QScriptValue &value) { QByteArray *ba = qscriptvalue_cast<QByteArray*>(object.data()); if (!ba) return; if (name == length) { ba->resize(value.toInt32()); } else { qint32 pos = id; if (pos < 0) return; if (ba->size() <= pos) ba->resize(pos + 1); (*ba)[pos] = char(value.toInt32()); } } //! [5] //! [6] QScriptValue::PropertyFlags ByteArrayClass::propertyFlags( const QScriptValue &/*object*/, const QScriptString &name, uint /*id*/) { if (name == length) { return QScriptValue::Undeletable | QScriptValue::SkipInEnumeration; } return QScriptValue::Undeletable; } //! [6] //! [7] QScriptClassPropertyIterator *ByteArrayClass::newIterator(const QScriptValue &object) { return new ByteArrayClassPropertyIterator(object); } //! [7] QString ByteArrayClass::name() const { return QLatin1String("ByteArray"); } QScriptValue ByteArrayClass::prototype() const { return proto; } QScriptValue ByteArrayClass::constructor() { return ctor; } QScriptValue ByteArrayClass::newInstance(int size) { return newInstance(QByteArray(size, /*ch=*/0)); } //! [1] QScriptValue ByteArrayClass::newInstance(const QByteArray &ba) { QScriptValue data = engine()->newVariant(qVariantFromValue(ba)); return engine()->newObject(this, data); } //! [1] //! [2] QScriptValue ByteArrayClass::construct(QScriptContext *ctx, QScriptEngine *) { ByteArrayClass *cls = qscriptvalue_cast<ByteArrayClass*>(ctx->callee().data()); if (!cls) return QScriptValue(); QScriptValue arg = ctx->argument(0); if (arg.instanceOf(ctx->callee())) return cls->newInstance(qscriptvalue_cast<QByteArray>(arg)); int size = arg.toInt32(); return cls->newInstance(size); } //! [2] QScriptValue ByteArrayClass::toScriptValue(QScriptEngine *eng, const QByteArray &ba) { QScriptValue ctor = eng->globalObject().property("ByteArray"); ByteArrayClass *cls = qscriptvalue_cast<ByteArrayClass*>(ctor.data()); if (!cls) return eng->newVariant(qVariantFromValue(ba)); return cls->newInstance(ba); } void ByteArrayClass::fromScriptValue(const QScriptValue &obj, QByteArray &ba) { ba = qvariant_cast<QByteArray>(obj.data().toVariant()); } ByteArrayClassPropertyIterator::ByteArrayClassPropertyIterator(const QScriptValue &object) : QScriptClassPropertyIterator(object) { toFront(); } ByteArrayClassPropertyIterator::~ByteArrayClassPropertyIterator() { } //! [8] bool ByteArrayClassPropertyIterator::hasNext() const { QByteArray *ba = qscriptvalue_cast<QByteArray*>(object().data()); return m_index < ba->size(); } void ByteArrayClassPropertyIterator::next() { m_last = m_index; ++m_index; } bool ByteArrayClassPropertyIterator::hasPrevious() const { return (m_index > 0); } void ByteArrayClassPropertyIterator::previous() { --m_index; m_last = m_index; } void ByteArrayClassPropertyIterator::toFront() { m_index = 0; m_last = -1; } void ByteArrayClassPropertyIterator::toBack() { QByteArray *ba = qscriptvalue_cast<QByteArray*>(object().data()); m_index = ba->size(); m_last = -1; } QScriptString ByteArrayClassPropertyIterator::name() const { return object().engine()->toStringHandle(QString::number(m_last)); } uint ByteArrayClassPropertyIterator::id() const { return m_last; } //! [8]
implement name() function of custom property iterator
implement name() function of custom property iterator
C++
lgpl-2.1
pruiz/wkhtmltopdf-qt,radekp/qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,radekp/qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,radekp/qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,radekp/qt,radekp/qt,igor-sfdc/qt-wk,radekp/qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,radekp/qt,radekp/qt,radekp/qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,radekp/qt,pruiz/wkhtmltopdf-qt
3f008453ea8d9d19444813aae348c0a722e14c9f
tinfra/win32/w32_subprocess.cpp
tinfra/win32/w32_subprocess.cpp
#include "tinfra/subprocess.h" #include "tinfra/io/stream.h" #include "tinfra/fmt.h" #include "tinfra/win32.h" #include "tinfra/holder.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> namespace tinfra { template<> void holder<HANDLE>::release() { if( value_ != 0 ) { ::CloseHandle(value_); value_ = 0; } } namespace win32 { using tinfra::io::stream; using tinfra::io::io_exception; using tinfra::io::open_native; static HANDLE open_null_for_subprocess(std::ios::openmode mode) { stream* stream = tinfra::io::open_file("NUL", mode); HANDLE result = reinterpret_cast<HANDLE>(stream->native()); stream->release(); delete stream; SetHandleInformation(result, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); return result; } // // pipe support for win32 // struct win32_subprocess: public subprocess { stream* stdin_; stream* stdout_; stream* stderr_; HANDLE process_handle; int exit_code; win32_subprocess() : exit_code(-1) { } ~win32_subprocess() { delete stdin_; delete stdout_; if( stdout_ != stderr_ ) delete stderr_; get_exit_code(); if( !::CloseHandle(process_handle) ) { // TODO: silent win32 error } } virtual void wait() { if( WaitForSingleObject(process_handle, INFINITE) != WAIT_OBJECT_0 ) { throw_system_error("WaitForSingleObject on subprocess failed"); } } virtual int get_exit_code() { if( process_handle != NULL ) { DWORD dwExitCode; if( !::GetExitCodeProcess(process_handle,&dwExitCode) ) { throw_system_error("GetExitCodeProcess failed"); } if( dwExitCode == STILL_ACTIVE ) return -1; exit_code = dwExitCode; } return exit_code; } virtual void terminate() { // unfortunately there is no way to grcefully kill // win32 process kill(); } virtual void kill() { if( !::TerminateProcess(process_handle, 10) ) { throw_system_error("TerminateProcess failed"); } } virtual stream* get_stdin() { return stdin_; } virtual stream* get_stdout() { return stdout_; } virtual stream* get_stderr() { return stderr_; } virtual intptr_t get_native_handle() { return reinterpret_cast<intptr_t>(process_handle); } void start(std::vector<std::string> const& args) { std::ostringstream cmd; for(std::vector<std::string>::const_iterator i = args.begin(); i != args.end(); ++i ) { if( i != args.begin() ) cmd << " "; if( i->find_first_of(" \t") ) cmd << "\"" << *i << "\""; else cmd << *i; } start(cmd.str().c_str()); } void start(const char* command) { HANDLE out_here(0); // writing HERE -> child HANDLE out_remote(0); // reading CHILD <- here HANDLE in_here(0); // reading HERE <- child HANDLE in_remote(0); // writing CHILD -> here HANDLE err_here(0); // reading HERE <- child (diagnostic) HANDLE err_remote(0); // writing CHILD -> here (diagnostic) const bool fread = (stdout_mode == REDIRECT); const bool fwrite = (stdin_mode == REDIRECT); const bool ferr = (stderr_mode == REDIRECT && !redirect_stderr); stdin_ = stderr_ = stdout_ = 0; { SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; if( fwrite ) { if ( CreatePipe(&out_remote, &out_here, &saAttr, 0) == 0 ) { throw_system_error("CreatePipe failed"); } SetHandleInformation(out_remote, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); SetHandleInformation(out_here, HANDLE_FLAG_INHERIT, 0); } if( fread ) { if ( CreatePipe(&in_here, &in_remote, &saAttr, 0) == 0 ) { throw_system_error("CreatePipe failed"); } SetHandleInformation(in_remote, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); SetHandleInformation(in_here, HANDLE_FLAG_INHERIT, 0); } if( ferr ) { if ( CreatePipe(&err_here, & err_remote, &saAttr, 0) == 0 ) { throw_system_error("CreatePipe failed"); } SetHandleInformation(err_remote, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); SetHandleInformation(err_here, HANDLE_FLAG_INHERIT, 0); } } { /* spawn process */ STARTUPINFO si; PROCESS_INFORMATION processi; DWORD creationFlags = 0; memset(&processi,0,sizeof(processi)); memset(&si,0,sizeof(si)); si.cb = sizeof(si); /* GetStartupInfo(&si);*/ if( fwrite ) { stdin_ = open_native(reinterpret_cast<intptr_t>((HANDLE)out_here)); out_here = 0; si.hStdInput = out_remote; } else if( stdin_mode == NONE) { si.hStdInput = out_remote = open_null_for_subprocess(std::ios::in); } else { si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); } if( fread ) { stdout_ = open_native(reinterpret_cast<intptr_t>((HANDLE)in_here)); in_here = 0; si.hStdOutput = in_remote; } else if( stdout_mode == NONE) { si.hStdOutput = in_remote = open_null_for_subprocess(std::ios::out); } else { si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); } if( redirect_stderr && fread ) { stderr_ = stdout_; si.hStdError = in_remote; } else if( ferr ) { stderr_ = open_native(reinterpret_cast<intptr_t>((HANDLE)err_here)); err_here = 0; si.hStdError = err_remote; } else if( stderr_mode == NONE ) { si.hStdError = err_remote = open_null_for_subprocess(std::ios::out); } else{ stderr_ = NULL; si.hStdError = GetStdHandle(STD_ERROR_HANDLE); } si.dwFlags |= STARTF_USESTDHANDLES; creationFlags |= DETACHED_PROCESS; si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; if( CreateProcess( NULL, (char*)command, NULL, NULL, TRUE, creationFlags, NULL, NULL, &si, &processi) == 0 ) { throw_system_error("CreateProcess failed"); } process_handle = processi.hProcess; if( in_remote ) ::CloseHandle(in_remote); if( out_remote ) ::CloseHandle(out_remote); if( err_remote ) ::CloseHandle(err_remote); } } }; } // end namespace win32 // // tinfra global stub for win32 // subprocess* create_subprocess() { return new win32::win32_subprocess(); } } // end namespace tinfra::win32
#include "tinfra/subprocess.h" #include "tinfra/io/stream.h" #include "tinfra/fmt.h" #include "tinfra/win32.h" #include "tinfra/holder.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> namespace tinfra { template<> void holder<HANDLE>::release() { if( value_ != 0 ) { ::CloseHandle(value_); value_ = 0; } } namespace win32 { using tinfra::io::stream; using tinfra::io::io_exception; using tinfra::io::open_native; static HANDLE open_null_for_subprocess(std::ios::openmode mode) { stream* stream = tinfra::io::open_file("NUL", mode); HANDLE result = reinterpret_cast<HANDLE>(stream->native()); stream->release(); delete stream; SetHandleInformation(result, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); return result; } // // pipe support for win32 // struct win32_subprocess: public subprocess { stream* stdin_; stream* stdout_; stream* stderr_; HANDLE process_handle; int exit_code; win32_subprocess() : process_handle(0), exit_code(-1) { } ~win32_subprocess() { delete stdin_; delete stdout_; if( stdout_ != stderr_ ) delete stderr_; get_exit_code(); if( !::CloseHandle(process_handle) ) { // TODO: silent win32 error } } virtual void wait() { if( WaitForSingleObject(process_handle, INFINITE) != WAIT_OBJECT_0 ) { throw_system_error("WaitForSingleObject on subprocess failed"); } } virtual int get_exit_code() { if( process_handle != NULL ) { DWORD dwExitCode; if( !::GetExitCodeProcess(process_handle,&dwExitCode) ) { throw_system_error("GetExitCodeProcess failed"); } if( dwExitCode == STILL_ACTIVE ) return -1; exit_code = dwExitCode; } return exit_code; } virtual void terminate() { // unfortunately there is no way to grcefully kill // win32 process kill(); } virtual void kill() { if( !::TerminateProcess(process_handle, 10) ) { throw_system_error("TerminateProcess failed"); } } virtual stream* get_stdin() { return stdin_; } virtual stream* get_stdout() { return stdout_; } virtual stream* get_stderr() { return stderr_; } virtual intptr_t get_native_handle() { return reinterpret_cast<intptr_t>(process_handle); } void start(std::vector<std::string> const& args) { std::ostringstream cmd; for(std::vector<std::string>::const_iterator i = args.begin(); i != args.end(); ++i ) { if( i != args.begin() ) cmd << " "; if( i->find_first_of(" \t") ) cmd << "\"" << *i << "\""; else cmd << *i; } start(cmd.str().c_str()); } void start(const char* command) { HANDLE out_here(0); // writing HERE -> child HANDLE out_remote(0); // reading CHILD <- here HANDLE in_here(0); // reading HERE <- child HANDLE in_remote(0); // writing CHILD -> here HANDLE err_here(0); // reading HERE <- child (diagnostic) HANDLE err_remote(0); // writing CHILD -> here (diagnostic) const bool fread = (stdout_mode == REDIRECT); const bool fwrite = (stdin_mode == REDIRECT); const bool ferr = (stderr_mode == REDIRECT && !redirect_stderr); stdin_ = stderr_ = stdout_ = 0; { SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; if( fwrite ) { if ( CreatePipe(&out_remote, &out_here, &saAttr, 0) == 0 ) { throw_system_error("CreatePipe failed"); } SetHandleInformation(out_remote, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); SetHandleInformation(out_here, HANDLE_FLAG_INHERIT, 0); } if( fread ) { if ( CreatePipe(&in_here, &in_remote, &saAttr, 0) == 0 ) { throw_system_error("CreatePipe failed"); } SetHandleInformation(in_remote, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); SetHandleInformation(in_here, HANDLE_FLAG_INHERIT, 0); } if( ferr ) { if ( CreatePipe(&err_here, & err_remote, &saAttr, 0) == 0 ) { throw_system_error("CreatePipe failed"); } SetHandleInformation(err_remote, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); SetHandleInformation(err_here, HANDLE_FLAG_INHERIT, 0); } } { /* spawn process */ STARTUPINFO si; PROCESS_INFORMATION processi; DWORD creationFlags = 0; memset(&processi,0,sizeof(processi)); memset(&si,0,sizeof(si)); si.cb = sizeof(si); /* GetStartupInfo(&si);*/ if( fwrite ) { stdin_ = open_native(reinterpret_cast<intptr_t>((HANDLE)out_here)); out_here = 0; si.hStdInput = out_remote; } else if( stdin_mode == NONE) { si.hStdInput = out_remote = open_null_for_subprocess(std::ios::in); } else { si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); } if( fread ) { stdout_ = open_native(reinterpret_cast<intptr_t>((HANDLE)in_here)); in_here = 0; si.hStdOutput = in_remote; } else if( stdout_mode == NONE) { si.hStdOutput = in_remote = open_null_for_subprocess(std::ios::out); } else { si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); } if( redirect_stderr && fread ) { stderr_ = stdout_; si.hStdError = in_remote; } else if( ferr ) { stderr_ = open_native(reinterpret_cast<intptr_t>((HANDLE)err_here)); err_here = 0; si.hStdError = err_remote; } else if( stderr_mode == NONE ) { si.hStdError = err_remote = open_null_for_subprocess(std::ios::out); } else{ stderr_ = NULL; si.hStdError = GetStdHandle(STD_ERROR_HANDLE); } si.dwFlags |= STARTF_USESTDHANDLES; creationFlags |= DETACHED_PROCESS; si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; if( CreateProcess( NULL, (char*)command, NULL, NULL, TRUE, creationFlags, NULL, NULL, &si, &processi) == 0 ) { throw_system_error("CreateProcess failed"); } process_handle = processi.hProcess; if( in_remote ) ::CloseHandle(in_remote); if( out_remote ) ::CloseHandle(out_remote); if( err_remote ) ::CloseHandle(err_remote); } } }; } // end namespace win32 // // tinfra global stub for win32 // subprocess* create_subprocess() { return new win32::win32_subprocess(); } } // end namespace tinfra::win32
fix fatal error (crash when CreateProcess fails): initialize process_handle member
fix fatal error (crash when CreateProcess fails): initialize process_handle member
C++
bsd-2-clause
zbigg/tinfra,zbigg/tinfra,zbigg/tinfra
33911acbbc48133d56a1367b2fe99a370f55b01d
examples/main.cpp
examples/main.cpp
#include <iostream> #include "Utils/utils.h" #include "numgrind.h" #include "Solvers/GradientDescentSolver.h" #include "Solvers/SGDSolver.h" #include "Solvers/SGDWithMomentumSolver.h" #include "Solvers/checkgradient.h" #include "DeepGrind/ActivationFunctions.h" #include "mnist.h" void mnistTest01() { const std::string fnameMNISTDir = "/home/daiver/coding/data/mnist/"; const std::string fnameImagesTrain = fnameMNISTDir + "train-images-idx3-ubyte"; const std::string fnameLabelsTrain = fnameMNISTDir + "train-labels-idx1-ubyte"; const std::string fnameImagesTest = fnameMNISTDir + "t10k-images-idx3-ubyte"; const std::string fnameLabelsTest = fnameMNISTDir + "t10k-labels-idx1-ubyte"; const Eigen::MatrixXf trainData = mnist::readMNISTImages(fnameImagesTrain) / 255.0; const Eigen::VectorXi trainLabelsPure = mnist::readMNISTLabels(fnameLabelsTrain); const Eigen::MatrixXf testData = mnist::readMNISTImages(fnameImagesTest) / 255.0; const Eigen::VectorXi testLabelsPure = mnist::readMNISTLabels(fnameLabelsTest); Eigen::MatrixXf trainLabels = NumGrind::Utils::labelsToMatrix(trainLabelsPure, 10); std::default_random_engine generator; generator.seed(42); using namespace NumGrind::SymbolicGraph; NumGrind::GraphManager gm; auto X = gm.constant(trainData); auto y = gm.constant(trainLabels); auto W1 = gm.variable(NumGrind::Utils::gaussf(trainData.cols(), 500, 0.0, 0.02, generator)); auto b1 = gm.variable(NumGrind::Utils::gaussf(1, 500, 0.0, 0.02, generator)); auto W2 = gm.variable(NumGrind::Utils::gaussf(500, 10, 0.0, 0.01, generator)); auto b2 = gm.variable(NumGrind::Utils::gaussf(1, 10, 0.0f, 0.01f, generator)); auto f1 = apply<NumGrind::DeepGrind::relu, NumGrind::DeepGrind::reluDer>(matmult(X, W1) + b1); auto f2 = apply<NumGrind::DeepGrind::sigmoid, NumGrind::DeepGrind::sigmoidDer>(matmult(f1, W2) + b2); auto output = f2; const int batchSize = 32; auto err = sumOfSquares(output - y); auto vars = gm.initializeVariables(); NumGrind::Solvers::SolverSettings settings; settings.nMaxIterations = 20; settings.verbose = false; float bestAcc = 0.0; X.setValue(trainData.block(0, 0, batchSize, 28 * 28)); y.setValue(trainLabels.block(0, 0, batchSize, 10)); NumGrind::Solvers::gradientDescent(settings, 0.0003, gm.funcFromNode(&err), gm.gradFromNode(&err), vars); settings.nMaxIterations = 1; // NumGrind::Solvers::SGDSolver solver(settings, 0.002, vars); NumGrind::Solvers::SGDWithMomentumSolver solver(settings, 0.0025, 0.9, vars); Eigen::MatrixXf trainDataSamples(trainData.rows(), trainData.cols()); Eigen::MatrixXf trainLabelsSamples(trainData.rows(), trainLabels.cols()); std::vector<int> shuffledIndices = NumGrind::Utils::range(0, trainData.rows()); // for(int iterInd = 0; iterInd < 10001; ++iterInd){ for (int epochInd = 0; epochInd < 10000; ++epochInd) { std::shuffle(shuffledIndices.begin(), shuffledIndices.end(), generator); NumGrind::Utils::sampleRowsByIndices(shuffledIndices, trainData, trainDataSamples); NumGrind::Utils::sampleRowsByIndices(shuffledIndices, trainLabels, trainLabelsSamples); solver.setStep(0.003/(0.05*epochInd + 1));//step decay solver.setMomentumCoeff(0.9/(0.05*epochInd + 1)); for (int iterInd = 0; iterInd < trainData.rows() / batchSize + 1; ++iterInd) { // NumGrind::Utils::rowDataTargetRandomSampling<float, float>(trainData, trainLabels, generator, trainDataSamples, trainLabelsSamples); // X.setValue(trainDataSamples); // y.setValue(trainLabelsSamples); X.setValue(trainDataSamples.block((iterInd * batchSize) % (trainData.rows() - batchSize), 0, batchSize, 28 * 28)); y.setValue(trainLabelsSamples.block((iterInd * batchSize) % (trainData.rows() - batchSize), 0, batchSize, 10)); solver.makeStep(gm.funcFromNode(&err), gm.gradFromNode(&err)); if (iterInd % 10 == 0) std::cout << "Epoch: " << epochInd << " iter: " << iterInd << " err " << err.node()->value() << std::endl; if (iterInd % 100 == 0) { X.setValue(testData); output.node()->forwardPass(solver.vars()); auto res = f2.value(); const auto colwiseMax = NumGrind::Utils::argmaxRowwise(res); int nErr = 0; for (int j = 0; j < colwiseMax.rows(); ++j) { if (colwiseMax[j] != testLabelsPure[j]) nErr += 1; } const float fErr = (float) nErr / testLabelsPure.rows(); const float acc = (1.0 - fErr) * 100; if (acc > bestAcc) bestAcc = acc; std::cout << std::endl << "Test error " << fErr << ", " << "acc " << (1.0 - fErr) * 100 << "%, " << "n errors " << (float) nErr << ", " << "best " << bestAcc << "% " << std::endl << std::endl; } } } } int main() { mnistTest01(); return 0; }
#include <iostream> #include "Utils/utils.h" #include "numgrind.h" #include "Solvers/GradientDescentSolver.h" #include "Solvers/SGDSolver.h" #include "Solvers/SGDWithMomentumSolver.h" #include "Solvers/checkgradient.h" #include "DeepGrind/ActivationFunctions.h" #include "mnist.h" void mnistTest01() { const std::string fnameMNISTDir = "/home/daiver/coding/data/mnist/"; const std::string fnameImagesTrain = fnameMNISTDir + "train-images-idx3-ubyte"; const std::string fnameLabelsTrain = fnameMNISTDir + "train-labels-idx1-ubyte"; const std::string fnameImagesTest = fnameMNISTDir + "t10k-images-idx3-ubyte"; const std::string fnameLabelsTest = fnameMNISTDir + "t10k-labels-idx1-ubyte"; const Eigen::MatrixXf trainData = mnist::readMNISTImages(fnameImagesTrain) / 255.0; const Eigen::VectorXi trainLabelsPure = mnist::readMNISTLabels(fnameLabelsTrain); const Eigen::MatrixXf testData = mnist::readMNISTImages(fnameImagesTest) / 255.0; const Eigen::VectorXi testLabelsPure = mnist::readMNISTLabels(fnameLabelsTest); Eigen::MatrixXf trainLabels = NumGrind::Utils::labelsToMatrix(trainLabelsPure, 10); std::default_random_engine generator; generator.seed(42); using namespace NumGrind::SymbolicGraph; NumGrind::GraphManager gm; auto X = gm.constant(trainData); auto y = gm.constant(trainLabels); auto W1 = gm.variable(NumGrind::Utils::gaussf(trainData.cols(), 500, 0.0, 0.02, generator)); auto b1 = gm.variable(NumGrind::Utils::gaussf(1, 500, 0.0, 0.02, generator)); auto W2 = gm.variable(NumGrind::Utils::gaussf(500, 10, 0.0, 0.01, generator)); auto b2 = gm.variable(NumGrind::Utils::gaussf(1, 10, 0.0f, 0.01f, generator)); auto f1 = apply<NumGrind::DeepGrind::relu, NumGrind::DeepGrind::reluDer>(matmult(X, W1) + b1); auto f2 = apply<NumGrind::DeepGrind::sigmoid, NumGrind::DeepGrind::sigmoidDer>(matmult(f1, W2) + b2); auto output = f2; const int batchSize = 50; auto err = sumOfSquares(output - y); auto vars = gm.initializeVariables(); NumGrind::Solvers::SolverSettings settings; settings.nMaxIterations = 20; settings.verbose = false; float bestAcc = 0.0; X.setValue(trainData.block(0, 0, batchSize, trainData.cols())); y.setValue(trainLabels.block(0, 0, batchSize, trainLabels.cols())); NumGrind::Solvers::gradientDescent(settings, 0.0003, gm.funcFromNode(&err), gm.gradFromNode(&err), vars); settings.nMaxIterations = 1; // NumGrind::Solvers::SGDSolver solver(settings, 0.002, vars); NumGrind::Solvers::SGDWithMomentumSolver solver(settings, 0.0025, 0.9, vars); Eigen::MatrixXf trainDataSamples(trainData.rows(), trainData.cols()); Eigen::MatrixXf trainLabelsSamples(trainData.rows(), trainLabels.cols()); std::vector<int> shuffledIndices = NumGrind::Utils::range(0, trainData.rows()); for (int epochInd = 0; epochInd < 10000; ++epochInd) { std::shuffle(shuffledIndices.begin(), shuffledIndices.end(), generator); NumGrind::Utils::sampleRowsByIndices(shuffledIndices, trainData, trainDataSamples); NumGrind::Utils::sampleRowsByIndices(shuffledIndices, trainLabels, trainLabelsSamples); // solver.setStep(0.003/(0.05*epochInd + 1));//step decay // solver.setMomentumCoeff(0.9/(0.05*epochInd + 1)); for (int iterInd = 0; iterInd < trainData.rows() / batchSize + 1; ++iterInd) { X.setValue(trainDataSamples.block((iterInd * batchSize) % (trainData.rows() - batchSize), 0, batchSize, trainDataSamples.cols())); y.setValue(trainLabelsSamples.block((iterInd * batchSize) % (trainData.rows() - batchSize), 0, batchSize, trainLabelsSamples.cols())); solver.makeStep(gm.funcFromNode(&err), gm.gradFromNode(&err)); if (iterInd % 10 == 0) std::cout << "Epoch: " << epochInd << " iter: " << iterInd << " err " << err.node()->value() << std::endl; if (iterInd % 100 == 0) { X.setValue(testData); output.node()->forwardPass(solver.vars()); auto res = f2.value(); const auto colwiseMax = NumGrind::Utils::argmaxRowwise(res); int nErr = 0; for (int j = 0; j < colwiseMax.rows(); ++j) { if (colwiseMax[j] != testLabelsPure[j]) nErr += 1; } const float fErr = (float) nErr / testLabelsPure.rows(); const float acc = (1.0 - fErr) * 100; if (acc > bestAcc) bestAcc = acc; std::cout << std::endl << "Test error " << fErr << ", " << "acc " << (1.0 - fErr) * 100 << "%, " << "n errors " << (float) nErr << ", " << "best " << bestAcc << "% " << std::endl << std::endl; } } } } int main() { mnistTest01(); return 0; }
disable weight decay
disable weight decay
C++
mit
Daiver/NumGrind
f0972a626b715b57092415f03f13e80d4286c65f
jni/src/future_jni.cpp
jni/src/future_jni.cpp
/* ** ** Author(s): ** - Pierre ROULLON <[email protected]> ** ** Copyright (C) 2012, 2013 Aldebaran Robotics */ #include <qitype/anyvalue.hpp> #include <jnitools.hpp> #include <futurehandler.hpp> #include <future_jni.hpp> #include <callbridge.hpp> qiLogCategory("qimessaging.java"); void java_future_callback(const qi::Future<qi::AnyReference>& future) { JNIEnv *env = 0; jclass cls = 0; // Attach JNIEnv to current thread to avoid segfault in jni functions. (eventloop dependent) if (JVM()->AttachCurrentThread((envPtr) &env, (void *) 0) != JNI_OK || env == 0) { qiLogError() << "Cannot attach callback thread to Java VM"; throw std::runtime_error("Cannot attach callback thread to Java VM"); } // Get Java information related to Java callback qi::CallbackInfo* info = qi::FutureHandler::methodInfo(future); if ((cls = env->FindClass(info->className.c_str())) == 0) { qiLogError() << "Cannot find com.aldebaran.qimessaging.Callback implementation"; throw new std::runtime_error("Cannot find com.aldebaran.qimessaging.Callback interface"); } if (future.hasError()) // Call onFailure qi::FutureHandler::onFailure(env, cls, info); if (!future.hasError() && future.isFinished()) // Call onSuccess qi::FutureHandler::onSuccess(env, cls, info); if (future.isFinished()) // Call onCompleted qi::FutureHandler::onComplete(env, cls, info); // Only called once, so remove and delete info qi::FutureHandler::removeCallbackInfo(future); env->DeleteLocalRef(cls); } jboolean Java_com_aldebaran_qimessaging_Future_qiFutureCallCancel(JNIEnv *env, jobject obj, jlong pFuture, jboolean mayInterup) { qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); if (fut->isCancelable() == false) return false; fut->cancel(); return true; } jobject Java_com_aldebaran_qimessaging_Future_qiFutureCallGet(JNIEnv *env, jobject obj, jlong pFuture) { qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); try { // UGLY WORKAROUND // jobject typeinterface has deep-value meaning on the pointed _jobject // but jobject as a C++ type is just _jobject* // so workaround by allocating, and performin only a shallow delete qi::AnyReference arRes = fut->value(); std::pair<qi::AnyReference, bool> converted = arRes.convert(qi::typeOf<jobject>()); jobject result = * (jobject*)converted.first.rawValue(); delete (jobject*)converted.first.rawValue(); return result; } catch (std::runtime_error &e) { throwJavaError(env, e.what()); return 0; } } jobject Java_com_aldebaran_qimessaging_Future_qiFutureCallGetWithTimeout(JNIEnv *env, jobject obj, jlong pFuture, jint timeout) { qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); qi::FutureState status = fut->wait(timeout); switch(status) { case qi::FutureState_FinishedWithValue: return Java_com_aldebaran_qimessaging_Future_qiFutureCallGetWithTimeout(env, obj, pFuture, 0); case qi::FutureState_Running: return 0; default: throwJavaError(env, fut->error().c_str()); } return 0; } jboolean Java_com_aldebaran_qimessaging_Future_qiFutureCallIsCancelled(JNIEnv *env, jobject obj, jlong pFuture) { qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); return fut->isCanceled(); } jboolean Java_com_aldebaran_qimessaging_Future_qiFutureCallIsDone(JNIEnv *env, jobject obj, jlong pFuture) { qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); return fut->isFinished(); } jboolean Java_com_aldebaran_qimessaging_Future_qiFutureCallConnect(JNIEnv *env, jobject obj, jlong pFuture, jobject callback, jstring jclassName, jobjectArray args) { qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); std::string className = qi::jni::toString(jclassName); qi::CallbackInfo* info = 0; // Attach JNIEnv to current thread to avoid segfault in jni functions. (eventloop dependent) if (JVM()->AttachCurrentThread((envPtr) &env, (void *) 0) != JNI_OK || env == 0) { qiLogError() << "Cannot attach callback thread to Java VM"; throwJavaError(env, "Cannot attach callback thread to Java VM"); return false; } info = new qi::CallbackInfo(callback, args, className); qi::FutureHandler::addCallbackInfo(fut, info); fut->connect(boost::bind(&java_future_callback, _1)); return true; } void Java_com_aldebaran_qimessaging_Future_qiFutureCallWaitWithTimeout(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(obj), jlong pFuture, jint timeout) { qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); if (timeout) fut->wait(timeout); else fut->wait(); }
/* ** ** Author(s): ** - Pierre ROULLON <[email protected]> ** ** Copyright (C) 2012, 2013 Aldebaran Robotics */ #include <qitype/anyvalue.hpp> #include <jnitools.hpp> #include <futurehandler.hpp> #include <future_jni.hpp> #include <callbridge.hpp> qiLogCategory("qimessaging.java"); void java_future_callback(const qi::Future<qi::AnyReference>& future) { JNIEnv *env = 0; jclass cls = 0; // Attach JNIEnv to current thread to avoid segfault in jni functions. (eventloop dependent) if (JVM()->AttachCurrentThread((envPtr) &env, (void *) 0) != JNI_OK || env == 0) { qiLogError() << "Cannot attach callback thread to Java VM"; throw std::runtime_error("Cannot attach callback thread to Java VM"); } // Get Java information related to Java callback qi::CallbackInfo* info = qi::FutureHandler::methodInfo(future); if ((cls = env->FindClass(info->className.c_str())) == 0) { qiLogError() << "Cannot find com.aldebaran.qimessaging.Callback implementation"; throw new std::runtime_error("Cannot find com.aldebaran.qimessaging.Callback interface"); } if (future.hasError()) // Call onFailure qi::FutureHandler::onFailure(env, cls, info); if (!future.hasError() && future.isFinished()) // Call onSuccess qi::FutureHandler::onSuccess(env, cls, info); if (future.isFinished()) // Call onCompleted qi::FutureHandler::onComplete(env, cls, info); // Only called once, so remove and delete info qi::FutureHandler::removeCallbackInfo(future); env->DeleteLocalRef(cls); } jboolean Java_com_aldebaran_qimessaging_Future_qiFutureCallCancel(JNIEnv *env, jobject obj, jlong pFuture, jboolean mayInterup) { qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); if (fut->isCancelable() == false) return false; fut->cancel(); return true; } jobject Java_com_aldebaran_qimessaging_Future_qiFutureCallGet(JNIEnv *env, jobject obj, jlong pFuture) { qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); try { // UGLY WORKAROUND // jobject typeinterface has deep-value meaning on the pointed _jobject // but jobject as a C++ type is just _jobject* // so workaround by allocating, and performin only a shallow delete qi::AnyReference arRes = fut->value(); std::pair<qi::AnyReference, bool> converted = arRes.convert(qi::typeOf<jobject>()); jobject result = * (jobject*)converted.first.rawValue(); delete (jobject*)converted.first.rawValue(); return result; } catch (std::runtime_error &e) { throwJavaError(env, e.what()); return 0; } } jobject Java_com_aldebaran_qimessaging_Future_qiFutureCallGetWithTimeout(JNIEnv *env, jobject obj, jlong pFuture, jint timeout) { qiLogVerbose() << "Future wait " << timeout; qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); qi::FutureState status = fut->wait(timeout); qiLogVerbose() << "Waited, got " << status; switch(status) { case qi::FutureState_FinishedWithValue: return Java_com_aldebaran_qimessaging_Future_qiFutureCallGet(env, obj, pFuture); case qi::FutureState_Running: return 0; default: throwJavaError(env, fut->error().c_str()); } return 0; } jboolean Java_com_aldebaran_qimessaging_Future_qiFutureCallIsCancelled(JNIEnv *env, jobject obj, jlong pFuture) { qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); return fut->isCanceled(); } jboolean Java_com_aldebaran_qimessaging_Future_qiFutureCallIsDone(JNIEnv *env, jobject obj, jlong pFuture) { qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); return fut->isFinished(); } jboolean Java_com_aldebaran_qimessaging_Future_qiFutureCallConnect(JNIEnv *env, jobject obj, jlong pFuture, jobject callback, jstring jclassName, jobjectArray args) { qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); std::string className = qi::jni::toString(jclassName); qi::CallbackInfo* info = 0; // Attach JNIEnv to current thread to avoid segfault in jni functions. (eventloop dependent) if (JVM()->AttachCurrentThread((envPtr) &env, (void *) 0) != JNI_OK || env == 0) { qiLogError() << "Cannot attach callback thread to Java VM"; throwJavaError(env, "Cannot attach callback thread to Java VM"); return false; } info = new qi::CallbackInfo(callback, args, className); qi::FutureHandler::addCallbackInfo(fut, info); fut->connect(boost::bind(&java_future_callback, _1)); return true; } void Java_com_aldebaran_qimessaging_Future_qiFutureCallWaitWithTimeout(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(obj), jlong pFuture, jint timeout) { qi::Future<qi::AnyReference>* fut = reinterpret_cast<qi::Future<qi::AnyReference>*>(pFuture); if (timeout) fut->wait(timeout); else fut->wait(); }
Fix infinite recursion bug.
Future: Fix infinite recursion bug. Change-Id: I8a5f37e3d767382b23dabe1b8da97ce956c51361 Reviewed-on: http://gerrit.aldebaran.lan/32494 Reviewed-by: mnottale <[email protected]> Tested-by: mnottale <[email protected]>
C++
bsd-3-clause
aldebaran/libqi-java,aldebaran/libqi-java,aldebaran/libqi-java
181b5f17eac06a9629cc0a741d2708b23daaf290
src/grovecircularled/grovecircularled.cxx
src/grovecircularled/grovecircularled.cxx
/* * Author: Jun Kato and Yevgeniy Kiveisha <[email protected]> * Contributions: Jon Trulson <[email protected]> * Copyright (c) 2015 Intel Corporation. * * This module is based on the my9221 driver * * 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 <iostream> #include <string> #include <stdexcept> #include <unistd.h> #include <stdlib.h> #include "grovecircularled.h" using namespace upm; GroveCircularLED::GroveCircularLED (uint8_t di, uint8_t dcki) : m_clkPinCtx(dcki), m_dataPinCtx(di) { mraa::Result error = mraa::SUCCESS; m_clkPinCtx.useMmap(true); m_dataPinCtx.useMmap(true); // set direction (out) error = m_clkPinCtx.dir(mraa::DIR_OUT); if (error != mraa::SUCCESS) { printError(error); } } mraa::Result GroveCircularLED::setSpinner (uint8_t position) { if (position < 0 || position >= 24) { return mraa::ERROR_INVALID_PARAMETER; } for(uint8_t block_idx = 0; block_idx < 24; block_idx++) { if (block_idx % 12 == 0) { send16bitBlock (CMDMODE); } uint32_t state = (block_idx == position) ? BIT_HIGH : BIT_LOW; send16bitBlock (state); } return lockData (); } mraa::Result GroveCircularLED::setLevel (uint8_t level, bool direction) { if (level < 0 || level > 24) { return mraa::ERROR_INVALID_PARAMETER; } if (direction) { for(uint8_t block_idx = 24; block_idx > 0; block_idx--) { if (block_idx % 12 == 0) { send16bitBlock (CMDMODE); } uint32_t state = (block_idx <= level) ? BIT_HIGH : BIT_LOW; send16bitBlock (state); } } else { for(uint8_t block_idx = 0; block_idx < 24; block_idx++) { if (block_idx % 12 == 0) { send16bitBlock (CMDMODE); } uint32_t state = (block_idx <= level - 1) ? BIT_HIGH : BIT_LOW; send16bitBlock (state); } } return lockData (); } mraa::Result GroveCircularLED::setStatus (bool status[24]) { for(uint8_t block_idx = 0; block_idx < 24; block_idx++) { if (block_idx % 12 == 0) { send16bitBlock (CMDMODE); } send16bitBlock (status[block_idx] ? BIT_HIGH : BIT_LOW); } return lockData (); } mraa::Result GroveCircularLED::lockData () { mraa::Result error = mraa::SUCCESS; error = m_dataPinCtx.write (LOW); usleep(10); for(int idx = 0; idx < 4; idx++) { error = m_dataPinCtx.write(HIGH); error = m_dataPinCtx.write(LOW); } return error; } mraa::Result GroveCircularLED::send16bitBlock (short data) { mraa::Result error = mraa::SUCCESS; for (uint8_t bit_idx = 0; bit_idx < MAX_BIT_PER_BLOCK; bit_idx++) { uint32_t state = (data & 0x8000) ? HIGH : LOW; error = m_dataPinCtx.write (state); state = m_clkPinCtx.read (); if (state) { state = LOW; } else { state = HIGH; } error = m_clkPinCtx.write (state); data <<= 1; } return error; }
/* * Author: Jun Kato and Yevgeniy Kiveisha <[email protected]> * Contributions: Jon Trulson <[email protected]> * Copyright (c) 2015 Intel Corporation. * * This module is based on the my9221 driver * * 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 <iostream> #include <string> #include <stdexcept> #include <unistd.h> #include <stdlib.h> #include "grovecircularled.h" using namespace upm; GroveCircularLED::GroveCircularLED (uint8_t di, uint8_t dcki) : m_clkPinCtx(dcki), m_dataPinCtx(di) { mraa::Result error = mraa::SUCCESS; // set direction (out) error = m_dataPinCtx.dir(mraa::DIR_OUT); if (error != mraa::SUCCESS) { printError(error); } error = m_clkPinCtx.dir(mraa::DIR_OUT); if (error != mraa::SUCCESS) { printError(error); } m_clkPinCtx.useMmap(true); m_dataPinCtx.useMmap(true); } mraa::Result GroveCircularLED::setSpinner (uint8_t position) { if (position < 0 || position >= 24) { return mraa::ERROR_INVALID_PARAMETER; } for(uint8_t block_idx = 0; block_idx < 24; block_idx++) { if (block_idx % 12 == 0) { send16bitBlock (CMDMODE); } uint32_t state = (block_idx == position) ? BIT_HIGH : BIT_LOW; send16bitBlock (state); } return lockData (); } mraa::Result GroveCircularLED::setLevel (uint8_t level, bool direction) { if (level < 0 || level > 24) { return mraa::ERROR_INVALID_PARAMETER; } if (direction) { for(uint8_t block_idx = 24; block_idx > 0; block_idx--) { if (block_idx % 12 == 0) { send16bitBlock (CMDMODE); } uint32_t state = (block_idx <= level) ? BIT_HIGH : BIT_LOW; send16bitBlock (state); } } else { for(uint8_t block_idx = 0; block_idx < 24; block_idx++) { if (block_idx % 12 == 0) { send16bitBlock (CMDMODE); } uint32_t state = (block_idx <= level - 1) ? BIT_HIGH : BIT_LOW; send16bitBlock (state); } } return lockData (); } mraa::Result GroveCircularLED::setStatus (bool status[24]) { for(uint8_t block_idx = 0; block_idx < 24; block_idx++) { if (block_idx % 12 == 0) { send16bitBlock (CMDMODE); } send16bitBlock (status[block_idx] ? BIT_HIGH : BIT_LOW); } return lockData (); } mraa::Result GroveCircularLED::lockData () { mraa::Result error = mraa::SUCCESS; error = m_dataPinCtx.write (LOW); usleep(10); for(int idx = 0; idx < 4; idx++) { error = m_dataPinCtx.write(HIGH); error = m_dataPinCtx.write(LOW); } return error; } mraa::Result GroveCircularLED::send16bitBlock (short data) { mraa::Result error = mraa::SUCCESS; for (uint8_t bit_idx = 0; bit_idx < MAX_BIT_PER_BLOCK; bit_idx++) { uint32_t state = (data & 0x8000) ? HIGH : LOW; error = m_dataPinCtx.write (state); state = m_clkPinCtx.read (); if (state) { state = LOW; } else { state = HIGH; } error = m_clkPinCtx.write (state); data <<= 1; } return error; }
fix up a missing mraa::DATA_OUT and formatting
grovecircularled: fix up a missing mraa::DATA_OUT and formatting Signed-off-by: Mihai Tudor Panu <[email protected]>
C++
mit
Jon-ICS/upm,kissbac/upm,nitirohilla/upm,nitirohilla/upm,arfoll/upm,pylbert/upm,afmckinney/upm,Jon-ICS/upm,skiselev/upm,skiselev/upm,pylbert/upm,intel-iot-devkit/upm,arfoll/upm,arfoll/upm,andreivasiliu2211/upm,srware/upm,MakerCollider/upm,whbruce/upm,g-vidal/upm,skiselev/upm,stefan-andritoiu/upm,stefan-andritoiu/upm,srware/upm,pylbert/upm,intel-iot-devkit/upm,Propanu/upm,kissbac/upm,sasmita/upm,spitfire88/upm,srware/upm,g-vidal/upm,stefan-andritoiu/upm,pylbert/upm,g-vidal/upm,pylbert/upm,andreivasiliu2211/upm,spitfire88/upm,g-vidal/upm,Propanu/upm,Propanu/upm,sasmita/upm,Propanu/upm,ShawnHymel/upm,Propanu/upm,whbruce/upm,sasmita/upm,spitfire88/upm,nitirohilla/upm,intel-iot-devkit/upm,Jon-ICS/upm,ShawnHymel/upm,malikabhi05/upm,spitfire88/upm,intel-iot-devkit/upm,malikabhi05/upm,sasmita/upm,jontrulson/upm,spitfire88/upm,tripzero/upm,afmckinney/upm,skiselev/upm,whbruce/upm,afmckinney/upm,jontrulson/upm,srware/upm,arfoll/upm,g-vidal/upm,stefan-andritoiu/upm,malikabhi05/upm,afmckinney/upm,stefan-andritoiu/upm,intel-iot-devkit/upm,kissbac/upm,jontrulson/upm,andreivasiliu2211/upm,MakerCollider/upm,MakerCollider/upm,afmckinney/upm,malikabhi05/upm,tripzero/upm,MakerCollider/upm,whbruce/upm,Jon-ICS/upm,arfoll/upm,nitirohilla/upm,tripzero/upm,andreivasiliu2211/upm,jontrulson/upm,malikabhi05/upm,intel-iot-devkit/upm,g-vidal/upm,andreivasiliu2211/upm,jontrulson/upm,sasmita/upm,ShawnHymel/upm,stefan-andritoiu/upm,pylbert/upm,tripzero/upm,skiselev/upm,MakerCollider/upm,ShawnHymel/upm,srware/upm,ShawnHymel/upm,skiselev/upm,kissbac/upm,tripzero/upm,Jon-ICS/upm,kissbac/upm,malikabhi05/upm,whbruce/upm,nitirohilla/upm,Propanu/upm
2135cd5c65faf47aed8735b4df36b36fbe642ebb
cpp/SmurffCpp/Utils/HDF5Group.cpp
cpp/SmurffCpp/Utils/HDF5Group.cpp
#include <iostream> #include <SmurffCpp/Utils/HDF5Group.h> #include <Utils/Error.h> #include <Utils/StringUtils.h> namespace smurff { bool HDF5Group::hasDataSet(const std::string& section, const std::string& tag) const { if (!m_group.exist(section)) return false; auto section_group = m_group.getGroup(section); return (section_group.exist(tag)); } bool HDF5Group::hasSection(const std::string& section) const { return m_group.exist(section); } h5::Group HDF5Group::addGroup(const std::string& name) { if (!m_group.exist(name)) m_group.createGroup(name); return getGroup(name); } h5::Group HDF5Group::getGroup(const std::string& name) const { return m_group.getGroup(name); } void HDF5Group::read(const std::string& section, const std::string& tag, Matrix &X) const { auto dataset = m_group.getGroup(section).getDataSet(tag); std::vector<size_t> dims = dataset.getDimensions(); X.resize(dims[0], dims[1]); dataset.read(X.data()); if (!X.IsRowMajor) { Matrix colMajor = Eigen::Map<Eigen::Matrix< typename Matrix::Scalar, Matrix::RowsAtCompileTime, Matrix::ColsAtCompileTime, Matrix::ColsAtCompileTime==1?Eigen::ColMajor:Eigen::RowMajor, Matrix::MaxRowsAtCompileTime, Matrix::MaxColsAtCompileTime>>(X.data(), dims[0], dims[1]); std::swap(colMajor, X); } } void HDF5Group::read(const std::string& section, const std::string& tag, Vector &X) const { auto dataset = m_group.getGroup(section).getDataSet(tag); std::vector<size_t> dims = dataset.getDimensions(); THROWERROR_ASSERT(dims[0] == 1); X.resize(dims[1]); dataset.read(X.data()); } void HDF5Group::read(const std::string& section, const std::string& tag, SparseMatrix &X) const { auto sparse_group = m_group.getGroup(section).getGroup(tag); std::string format; sparse_group.getAttribute("h5sparse_format").read(format); THROWERROR_ASSERT(( SparseMatrix::IsRowMajor && format == "csr") || \ (!SparseMatrix::IsRowMajor && format == "csc")); std::vector<Eigen::Index> shape(2); sparse_group.getAttribute("h5sparse_shape").read(shape); X.resize(shape.at(0), shape.at(1)); X.makeCompressed(); auto data = sparse_group.getDataSet("data"); THROWERROR_ASSERT(data.getDataType() == h5::AtomicType<SparseMatrix::value_type>()); X.resizeNonZeros(data.getElementCount()); data.read(X.valuePtr()); auto indptr = sparse_group.getDataSet("indptr"); THROWERROR_ASSERT(indptr.getDataType() == h5::AtomicType<SparseMatrix::Index>()); indptr.read(X.outerIndexPtr()); auto indices = sparse_group.getDataSet("indices"); THROWERROR_ASSERT(indices.getDataType() == h5::AtomicType<SparseMatrix::Index>()); indices.read(X.innerIndexPtr()); } void HDF5Group::read(const std::string& section, const std::string& tag, DenseTensor &) const { THROWERROR_NOTIMPL(); } void HDF5Group::read(const std::string& section, const std::string& tag, SparseTensor &) const { THROWERROR_NOTIMPL(); } void HDF5Group::write(const std::string& section, const std::string& tag, const Vector &V) { write(section, tag, Matrix(V)); } void HDF5Group::write(const std::string& section, const std::string& tag, const Matrix &M) { if (!m_group.exist(section)) m_group.createGroup(section); h5::Group group = m_group.getGroup(section); h5::DataSet dataset = group.createDataSet<Matrix::Scalar>(tag, h5::DataSpace({static_cast<size_t>(M.rows()), static_cast<size_t>(M.cols())})); Eigen::Ref< const Eigen::Matrix< Matrix::Scalar, Matrix::RowsAtCompileTime, Matrix::ColsAtCompileTime, Matrix::ColsAtCompileTime==1?Eigen::ColMajor:Eigen::RowMajor, Matrix::MaxRowsAtCompileTime, Matrix::MaxColsAtCompileTime>, 0, Eigen::InnerStride<1>> row_major(M); dataset.write(row_major.data()); } void HDF5Group::write(const std::string& section, const std::string& tag, const SparseMatrix &X) { if (!m_group.exist(section)) m_group.createGroup(section); h5::Group sparse_group = m_group.getGroup(section).createGroup(tag); sparse_group.createAttribute<std::string>("h5sparse_format", (SparseMatrix::IsRowMajor ? "csr" : "csc")); std::vector<Eigen::Index> shape{X.rows(), X.cols()}; sparse_group.createAttribute<Eigen::Index>("h5sparse_shape", h5::DataSpace::From(shape)).write(shape); auto data = sparse_group.createDataSet<SparseMatrix::value_type>("data", h5::DataSpace(X.nonZeros())); data.write(X.valuePtr()); auto indptr = sparse_group.createDataSet<SparseMatrix::Index>("indptr", h5::DataSpace(X.outerSize() + 1)); indptr.write(X.outerIndexPtr()); auto indices = sparse_group.createDataSet<SparseMatrix::Index>("indices", h5::DataSpace(X.nonZeros())); indices.write(X.innerIndexPtr()); } void HDF5Group::write(const std::string& section, const std::string& tag, const DenseTensor &X) { THROWERROR_NOTIMPL(); } void HDF5Group::write(const std::string& section, const std::string& tag, const SparseTensor &X) { THROWERROR_NOTIMPL(); } } // end namespace smurff
#include <iostream> #include <SmurffCpp/Utils/HDF5Group.h> #include <Utils/Error.h> #include <Utils/StringUtils.h> namespace smurff { bool HDF5Group::hasDataSet(const std::string& section, const std::string& tag) const { if (!m_group.exist(section)) return false; auto section_group = m_group.getGroup(section); return (section_group.exist(tag)); } bool HDF5Group::hasSection(const std::string& section) const { return m_group.exist(section); } h5::Group HDF5Group::addGroup(const std::string& name) { if (!m_group.exist(name)) m_group.createGroup(name); return getGroup(name); } h5::Group HDF5Group::getGroup(const std::string& name) const { return m_group.getGroup(name); } void HDF5Group::read(const std::string& section, const std::string& tag, Matrix &X) const { auto dataset = m_group.getGroup(section).getDataSet(tag); std::vector<size_t> dims = dataset.getDimensions(); X.resize(dims[0], dims[1]); dataset.read(X.data()); if (!X.IsRowMajor) { Matrix colMajor = Eigen::Map<Eigen::Matrix< typename Matrix::Scalar, Matrix::RowsAtCompileTime, Matrix::ColsAtCompileTime, Matrix::ColsAtCompileTime==1?Eigen::ColMajor:Eigen::RowMajor, Matrix::MaxRowsAtCompileTime, Matrix::MaxColsAtCompileTime>>(X.data(), dims[0], dims[1]); std::swap(colMajor, X); } } void HDF5Group::read(const std::string& section, const std::string& tag, Vector &X) const { auto dataset = m_group.getGroup(section).getDataSet(tag); std::vector<size_t> dims = dataset.getDimensions(); THROWERROR_ASSERT(dims[0] == 1); X.resize(dims[1]); dataset.read(X.data()); } void HDF5Group::read(const std::string& section, const std::string& tag, SparseMatrix &X) const { auto sparse_group = m_group.getGroup(section).getGroup(tag); std::string format; sparse_group.getAttribute("h5sparse_format").read(format); THROWERROR_ASSERT(( SparseMatrix::IsRowMajor && format == "csr") || \ (!SparseMatrix::IsRowMajor && format == "csc")); std::vector<Eigen::Index> shape(2); sparse_group.getAttribute("h5sparse_shape").read(shape); X.resize(shape.at(0), shape.at(1)); X.makeCompressed(); auto data = sparse_group.getDataSet("data"); THROWERROR_ASSERT(data.getDataType() == h5::AtomicType<SparseMatrix::value_type>()); X.resizeNonZeros(data.getElementCount()); data.read(X.valuePtr()); auto indptr = sparse_group.getDataSet("indptr"); THROWERROR_ASSERT(indptr.getDataType() == h5::AtomicType<SparseMatrix::Index>()); indptr.read(X.outerIndexPtr()); auto indices = sparse_group.getDataSet("indices"); THROWERROR_ASSERT(indices.getDataType() == h5::AtomicType<SparseMatrix::Index>()); indices.read(X.innerIndexPtr()); } void HDF5Group::read(const std::string& section, const std::string& tag, DenseTensor &) const { THROWERROR_NOTIMPL(); } void HDF5Group::read(const std::string& section, const std::string& tag, SparseTensor &) const { THROWERROR_NOTIMPL(); } void HDF5Group::write(const std::string& section, const std::string& tag, const Vector &V) { write(section, tag, Matrix(V)); } void HDF5Group::write(const std::string& section, const std::string& tag, const Matrix &M) { if (!m_group.exist(section)) m_group.createGroup(section); h5::Group group = m_group.getGroup(section); h5::DataSet dataset = group.createDataSet<Matrix::Scalar>(tag, h5::DataSpace({static_cast<size_t>(M.rows()), static_cast<size_t>(M.cols())})); Eigen::Ref< const Eigen::Matrix< Matrix::Scalar, Matrix::RowsAtCompileTime, Matrix::ColsAtCompileTime, Matrix::ColsAtCompileTime==1?Eigen::ColMajor:Eigen::RowMajor, Matrix::MaxRowsAtCompileTime, Matrix::MaxColsAtCompileTime>, 0, Eigen::InnerStride<1>> row_major(M); dataset.write_raw(row_major.data()); } void HDF5Group::write(const std::string& section, const std::string& tag, const SparseMatrix &X) { if (!m_group.exist(section)) m_group.createGroup(section); h5::Group sparse_group = m_group.getGroup(section).createGroup(tag); sparse_group.createAttribute<std::string>("h5sparse_format", (SparseMatrix::IsRowMajor ? "csr" : "csc")); std::vector<Eigen::Index> shape{X.rows(), X.cols()}; sparse_group.createAttribute<Eigen::Index>("h5sparse_shape", h5::DataSpace::From(shape)).write(shape); auto data = sparse_group.createDataSet<SparseMatrix::value_type>("data", h5::DataSpace(X.nonZeros())); data.write(X.valuePtr()); auto indptr = sparse_group.createDataSet<SparseMatrix::Index>("indptr", h5::DataSpace(X.outerSize() + 1)); indptr.write(X.outerIndexPtr()); auto indices = sparse_group.createDataSet<SparseMatrix::Index>("indices", h5::DataSpace(X.nonZeros())); indices.write(X.innerIndexPtr()); } void HDF5Group::write(const std::string& section, const std::string& tag, const DenseTensor &X) { THROWERROR_NOTIMPL(); } void HDF5Group::write(const std::string& section, const std::string& tag, const SparseTensor &X) { THROWERROR_NOTIMPL(); } } // end namespace smurff
use write_raw to write 1D buffer into 2D HDF5 dataset
FIX: use write_raw to write 1D buffer into 2D HDF5 dataset
C++
mit
ExaScience/smurff,ExaScience/smurff,ExaScience/smurff,ExaScience/smurff,ExaScience/smurff,ExaScience/smurff
673f739bce4e9ef6e50435918be13577b0b7ca6f
util/TableManager.hpp
util/TableManager.hpp
#pragma once #include "StorageConfig.hpp" #include "Epoch.hpp" #include "Record.hpp" #include "CommitManager.hpp" #include <crossbow/concurrent_map.hpp> #include <crossbow/string.hpp> #include <thread> #include <mutex> #include <condition_variable> #include <chrono> #include <vector> #include <atomic> #include <tbb/queuing_rw_mutex.h> namespace tbb { size_t tbb_hasher(const crossbow::string& str) { std::hash<crossbow::string> h; return h(str); } } // namespace tbb #include <tbb/concurrent_unordered_map.h> namespace tell { namespace store { class NoGC { public: }; class PageManager; template<class Table, class GC> class TableManager { private: // Private types using Clock = std::chrono::system_clock; private: StorageConfig mConfig; GC& mGC; PageManager& mPageManager; CommitManager& mCommitManager; std::atomic<bool> mShutDown; mutable tbb::queuing_rw_mutex mTablesMutex; tbb::concurrent_unordered_map<crossbow::string, uint64_t> mNames; tbb::concurrent_unordered_map<uint64_t, Table*> mTables; std::atomic<uint64_t> mLastTableIdx; std::condition_variable mStopCondition; mutable std::mutex mGCMutex; std::thread mGCThread; private: void gcThread() { std::unique_lock<std::mutex> lock(mGCMutex); auto begin = Clock::now(); auto duration = std::chrono::seconds(mConfig.gcIntervall); while (!mShutDown.load()) { auto now = Clock::now(); if (begin + duration > now) { mStopCondition.wait_until(lock, begin + duration); } if (mShutDown.load()) return; begin = Clock::now(); std::vector<Table*> tables; tables.reserve(mNames.size()); { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); for (auto& p : mTables) { tables.push_back(p.second); } } mGC.run(tables, mCommitManager.getLowestActiveVersion()); } } public: TableManager(PageManager& pageManager, const StorageConfig& config, GC& gc, CommitManager& commitManager) : mConfig(config) , mGC(gc) , mPageManager(pageManager) , mCommitManager(commitManager) , mShutDown(false) , mLastTableIdx(0) , mGCThread(std::bind(&TableManager::gcThread, this)) { } ~TableManager() { mShutDown.store(true); mStopCondition.notify_all(); mGCThread.join(); for (auto t : mTables) { if (t.second) { t.second->~Table(); allocator::free_now(t.second); } } } public: bool createTable(const crossbow::string& name, const Schema& schema, uint64_t& idx) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); idx = ++mLastTableIdx; auto res = mNames.insert(std::make_pair(name, idx)); if (!res.second) { return false; } mTables[idx] = new(tell::store::malloc(sizeof(Table))) Table(mPageManager, schema); return true; } bool getTableId(const crossbow::string& name, uint64_t& id) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); auto res = mNames.find(name); if (res == mNames.end()) return false; id = res->second; return true; } bool get(uint64_t tableId, uint64_t key, size_t& size, const char*& data, const SnapshotDescriptor& snapshot, bool& isNewest) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); return mTables[tableId]->get(key, size, data, snapshot, isNewest); } bool update(uint64_t tableId, uint64_t key, size_t size, const char* const data, const SnapshotDescriptor& snapshot) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); return mTables[tableId]->update(key, size, data, snapshot); } void insert(uint64_t tableId, uint64_t key, size_t size, const char* const data, const SnapshotDescriptor& snapshot, bool* succeeded = nullptr) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); mTables[tableId]->insert(key, size, data, snapshot, succeeded); } void insert(uint64_t tableId, uint64_t key, const GenericTuple& tuple, const SnapshotDescriptor& snapshot, bool* succeeded = nullptr) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); mTables[tableId]->insert(key, tuple, snapshot, succeeded); } bool remove(uint64_t tableId, uint64_t key, const SnapshotDescriptor& snapshot) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); return mTables[tableId]->remove(key, snapshot); } void forceGC() { // Notifies the GC mStopCondition.notify_all(); } }; } // namespace store } // namespace tell
#pragma once #include "StorageConfig.hpp" #include "Epoch.hpp" #include "Record.hpp" #include "CommitManager.hpp" #include <crossbow/concurrent_map.hpp> #include <crossbow/string.hpp> #include <thread> #include <mutex> #include <condition_variable> #include <chrono> #include <vector> #include <atomic> #include <tbb/queuing_rw_mutex.h> namespace tbb { inline size_t tbb_hasher(const crossbow::string& str) { std::hash<crossbow::string> h; return h(str); } } // namespace tbb #include <tbb/concurrent_unordered_map.h> namespace tell { namespace store { class NoGC { public: }; class PageManager; template<class Table, class GC> class TableManager { private: // Private types using Clock = std::chrono::system_clock; private: StorageConfig mConfig; GC& mGC; PageManager& mPageManager; CommitManager& mCommitManager; std::atomic<bool> mShutDown; mutable tbb::queuing_rw_mutex mTablesMutex; tbb::concurrent_unordered_map<crossbow::string, uint64_t> mNames; tbb::concurrent_unordered_map<uint64_t, Table*> mTables; std::atomic<uint64_t> mLastTableIdx; std::condition_variable mStopCondition; mutable std::mutex mGCMutex; std::thread mGCThread; private: void gcThread() { std::unique_lock<std::mutex> lock(mGCMutex); auto begin = Clock::now(); auto duration = std::chrono::seconds(mConfig.gcIntervall); while (!mShutDown.load()) { auto now = Clock::now(); if (begin + duration > now) { mStopCondition.wait_until(lock, begin + duration); } if (mShutDown.load()) return; begin = Clock::now(); std::vector<Table*> tables; tables.reserve(mNames.size()); { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); for (auto& p : mTables) { tables.push_back(p.second); } } mGC.run(tables, mCommitManager.getLowestActiveVersion()); } } public: TableManager(PageManager& pageManager, const StorageConfig& config, GC& gc, CommitManager& commitManager) : mConfig(config) , mGC(gc) , mPageManager(pageManager) , mCommitManager(commitManager) , mShutDown(false) , mLastTableIdx(0) , mGCThread(std::bind(&TableManager::gcThread, this)) { } ~TableManager() { mShutDown.store(true); mStopCondition.notify_all(); mGCThread.join(); for (auto t : mTables) { if (t.second) { t.second->~Table(); allocator::free_now(t.second); } } } public: bool createTable(const crossbow::string& name, const Schema& schema, uint64_t& idx) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); idx = ++mLastTableIdx; auto res = mNames.insert(std::make_pair(name, idx)); if (!res.second) { return false; } mTables[idx] = new(tell::store::malloc(sizeof(Table))) Table(mPageManager, schema); return true; } bool getTableId(const crossbow::string& name, uint64_t& id) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); auto res = mNames.find(name); if (res == mNames.end()) return false; id = res->second; return true; } bool get(uint64_t tableId, uint64_t key, size_t& size, const char*& data, const SnapshotDescriptor& snapshot, bool& isNewest) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); return mTables[tableId]->get(key, size, data, snapshot, isNewest); } bool update(uint64_t tableId, uint64_t key, size_t size, const char* const data, const SnapshotDescriptor& snapshot) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); return mTables[tableId]->update(key, size, data, snapshot); } void insert(uint64_t tableId, uint64_t key, size_t size, const char* const data, const SnapshotDescriptor& snapshot, bool* succeeded = nullptr) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); mTables[tableId]->insert(key, size, data, snapshot, succeeded); } void insert(uint64_t tableId, uint64_t key, const GenericTuple& tuple, const SnapshotDescriptor& snapshot, bool* succeeded = nullptr) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); mTables[tableId]->insert(key, tuple, snapshot, succeeded); } bool remove(uint64_t tableId, uint64_t key, const SnapshotDescriptor& snapshot) { tbb::queuing_rw_mutex::scoped_lock _(mTablesMutex, false); return mTables[tableId]->remove(key, snapshot); } void forceGC() { // Notifies the GC mStopCondition.notify_all(); } }; } // namespace store } // namespace tell
Make tbb_hasher inline to prevent multiple instantiations
Make tbb_hasher inline to prevent multiple instantiations
C++
apache-2.0
tellproject/tellstore
02c2ba1b62f003af393fe917e39a8a3d91a0b3a8
tools/lldb-mi/MIUtilFileStd.cpp
tools/lldb-mi/MIUtilFileStd.cpp
//===-- MIUtilFileStd.cpp ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// //++ // File: MIUtilFileStd.cpp // // Overview: CMIUtilFileStd implementation. // // Environment: Compilers: Visual C++ 12. // gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1 // Libraries: See MIReadmetxt. // // Copyright: None. //-- // Include compiler configuration #include "MICmnConfig.h" // Third party headers #include <stdio.h> #include <assert.h> #include <string.h> // Dor strerror() // In-house headers: #include "MIUtilFileStd.h" #include "MICmnResources.h" //++ ------------------------------------------------------------------------------------ // Details: CMIUtilFileStd constructor. // Type: Method. // Args: None. // Return: None. // Throws: None. //-- CMIUtilFileStd::CMIUtilFileStd( void ) : m_fileNamePath( CMIUtilString() ) , m_pFileHandle( nullptr ) #if defined( _MSC_VER ) , m_constCharNewLine( "\r\n" ) #else , m_constCharNewLine( "\n" ) #endif // #if defined( _MSC_VER ) , m_bFileError( false ) { } //++ ------------------------------------------------------------------------------------ // Details: CMIUtilFileStd destructor. // Type: Method. // Args: None. // Return: None. // Throws: None. //-- CMIUtilFileStd::~CMIUtilFileStd( void ) { Close(); } //++ ------------------------------------------------------------------------------------ // Details: Open file for writing. On the first call to this function after *this object // is created the file is either created or replace, from then on open only opens // an existing file. // Type: Method. // Args: vFileNamePath - (R) File name path. // vwrbNewCreated - (W) True - file recreated, false - file appended too. // Return: MIstatus::success - Functional succeeded. // MIstatus::failure - Functional failed. // Throws: None. //-- bool CMIUtilFileStd::CreateWrite( const CMIUtilString & vFileNamePath, bool & vwrbNewCreated ) { // Reset m_bFileError = false; vwrbNewCreated = false; if( vFileNamePath.empty() ) { m_bFileError = true; SetErrorDescription( MIRSRC( IDS_UTIL_FILE_ERR_INVALID_PATHNAME ) ); return MIstatus::failure; } // File is already open so exit if( m_pFileHandle != nullptr ) return MIstatus::success; #if !defined( _MSC_VER ) // Open with 'write' and 'binary' mode m_pFileHandle = ::fopen( vFileNamePath.c_str(), "wb" ); #else // Open a file with exclusive write and shared read permissions m_pFileHandle = ::_fsopen( vFileNamePath.c_str(), "wb", _SH_DENYWR ); #endif // !defined( _MSC_VER ) if( m_pFileHandle == nullptr ) { m_bFileError = true; SetErrorDescriptionn( MIRSRC( IDS_UTIL_FILE_ERR_OPENING_FILE ), strerror( errno ), vFileNamePath.c_str() ); return MIstatus::failure; } vwrbNewCreated = true; m_fileNamePath = vFileNamePath; return MIstatus::success; } //++ ------------------------------------------------------------------------------------ // Details: Write data to existing opened file. // Type: Method. // Args: vData - (R) Text data. // Return: MIstatus::success - Functional succeeded. // MIstatus::failure - Functional failed. // Throws: None. //-- bool CMIUtilFileStd::Write( const CMIUtilString & vData ) { if( vData.size() == 0 ) return MIstatus::success; if( m_bFileError ) return MIstatus::failure; if( m_pFileHandle == nullptr ) { m_bFileError = true; SetErrorDescriptionn( MIRSRC( IDE_UTIL_FILE_ERR_WRITING_NOTOPEN ), m_fileNamePath.c_str() ); return MIstatus::failure; } // Get the string size MIuint size = vData.size(); if( ::fwrite( vData.c_str(), 1, size, m_pFileHandle ) == size ) { // Flush the data to the file ::fflush( m_pFileHandle ); return MIstatus::success; } // Not all of the data has been transfered m_bFileError = true; SetErrorDescriptionn( MIRSRC( IDE_UTIL_FILE_ERR_WRITING_FILE ), m_fileNamePath.c_str() ); return MIstatus::failure; } //++ ------------------------------------------------------------------------------------ // Details: Write data to existing opened file. // Type: Method. // Args: vData - (R) Text data. // vCharCnt - (R) Text data length. // Return: MIstatus::success - Functional succeeded. // MIstatus::failure - Functional failed. // Throws: None. //-- bool CMIUtilFileStd::Write( const MIchar * vpData, const MIuint vCharCnt ) { if( vCharCnt == 0 ) return MIstatus::success; if( m_bFileError ) return MIstatus::failure; if( m_pFileHandle == nullptr ) { m_bFileError = true; SetErrorDescriptionn( MIRSRC( IDE_UTIL_FILE_ERR_WRITING_NOTOPEN ), m_fileNamePath.c_str() ); return MIstatus::failure; } if( ::fwrite( vpData, 1, vCharCnt, m_pFileHandle ) == vCharCnt ) { // Flush the data to the file ::fflush( m_pFileHandle ); return MIstatus::success; } // Not all of the data has been transfered m_bFileError = true; SetErrorDescriptionn( MIRSRC( IDE_UTIL_FILE_ERR_WRITING_FILE ), m_fileNamePath.c_str() ); return MIstatus::failure; } //++ ------------------------------------------------------------------------------------ // Details: Close existing opened file. Note Close() must must an open! // Type: Method. // Args: None. // Return: None. // Throws: None. //-- void CMIUtilFileStd::Close( void ) { if( m_pFileHandle == nullptr ) return; ::fclose( m_pFileHandle ); m_pFileHandle = nullptr; //m_bFileError = false; Do not reset as want to remain until next attempt at open or create } //++ ------------------------------------------------------------------------------------ // Details: Retrieve state of whether the file is ok. // Type: Method. // Args: None. // Return: True - file ok. // False - file has a problem. // Throws: None. //-- bool CMIUtilFileStd::IsOk( void ) const { return !m_bFileError; } //++ ------------------------------------------------------------------------------------ // Details: Status on a file existing already. // Type: Method. // Args: vFileNamePath. // Return: True - Exists. // False - Not found. // Throws: None. //-- bool CMIUtilFileStd::IsFileExist( const CMIUtilString & vFileNamePath ) const { if( vFileNamePath.empty() ) return false; FILE * pTmp = nullptr; pTmp = ::fopen( vFileNamePath.c_str(), "wb" ); if( pTmp != nullptr ) { ::fclose( pTmp ); return true; } return false; } //++ ------------------------------------------------------------------------------------ // Details: Retrieve the file current carriage line return characters used. // Type: Method. // Args: None. // Return: CMIUtilString & - Text. // Throws: None. //-- const CMIUtilString & CMIUtilFileStd::GetLineReturn( void ) const { return m_constCharNewLine; } //++ ------------------------------------------------------------------------------------ // Details: Given a file name directory path, strip off the filename and return the path. // It look for either backslash or forward slash. // Type: Method. // Args: vDirectoryPath - (R) Text directory path. // Return: CMIUtilString - Directory path. // Throws: None. //-- CMIUtilString CMIUtilFileStd::StripOffFileName( const CMIUtilString & vDirectoryPath ) const { const MIint nPos = vDirectoryPath.rfind( '\\' ); MIint nPos2 = vDirectoryPath.rfind( '/' ); if( (nPos == (MIint) std::string::npos) && (nPos2 == (MIint) std::string::npos) ) return vDirectoryPath; if( nPos > nPos2 ) nPos2 = nPos; const CMIUtilString strPath( vDirectoryPath.substr( 0, nPos2 ).c_str() ); return strPath; }
//===-- MIUtilFileStd.cpp ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// //++ // File: MIUtilFileStd.cpp // // Overview: CMIUtilFileStd implementation. // // Environment: Compilers: Visual C++ 12. // gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1 // Libraries: See MIReadmetxt. // // Copyright: None. //-- // Include compiler configuration #include "MICmnConfig.h" // Third party headers #include <stdio.h> #include <assert.h> #include <errno.h> #include <string.h> // Dor strerror() // In-house headers: #include "MIUtilFileStd.h" #include "MICmnResources.h" //++ ------------------------------------------------------------------------------------ // Details: CMIUtilFileStd constructor. // Type: Method. // Args: None. // Return: None. // Throws: None. //-- CMIUtilFileStd::CMIUtilFileStd( void ) : m_fileNamePath( CMIUtilString() ) , m_pFileHandle( nullptr ) #if defined( _MSC_VER ) , m_constCharNewLine( "\r\n" ) #else , m_constCharNewLine( "\n" ) #endif // #if defined( _MSC_VER ) , m_bFileError( false ) { } //++ ------------------------------------------------------------------------------------ // Details: CMIUtilFileStd destructor. // Type: Method. // Args: None. // Return: None. // Throws: None. //-- CMIUtilFileStd::~CMIUtilFileStd( void ) { Close(); } //++ ------------------------------------------------------------------------------------ // Details: Open file for writing. On the first call to this function after *this object // is created the file is either created or replace, from then on open only opens // an existing file. // Type: Method. // Args: vFileNamePath - (R) File name path. // vwrbNewCreated - (W) True - file recreated, false - file appended too. // Return: MIstatus::success - Functional succeeded. // MIstatus::failure - Functional failed. // Throws: None. //-- bool CMIUtilFileStd::CreateWrite( const CMIUtilString & vFileNamePath, bool & vwrbNewCreated ) { // Reset m_bFileError = false; vwrbNewCreated = false; if( vFileNamePath.empty() ) { m_bFileError = true; SetErrorDescription( MIRSRC( IDS_UTIL_FILE_ERR_INVALID_PATHNAME ) ); return MIstatus::failure; } // File is already open so exit if( m_pFileHandle != nullptr ) return MIstatus::success; #if !defined( _MSC_VER ) // Open with 'write' and 'binary' mode m_pFileHandle = ::fopen( vFileNamePath.c_str(), "wb" ); #else // Open a file with exclusive write and shared read permissions m_pFileHandle = ::_fsopen( vFileNamePath.c_str(), "wb", _SH_DENYWR ); #endif // !defined( _MSC_VER ) if( m_pFileHandle == nullptr ) { m_bFileError = true; SetErrorDescriptionn( MIRSRC( IDS_UTIL_FILE_ERR_OPENING_FILE ), strerror( errno ), vFileNamePath.c_str() ); return MIstatus::failure; } vwrbNewCreated = true; m_fileNamePath = vFileNamePath; return MIstatus::success; } //++ ------------------------------------------------------------------------------------ // Details: Write data to existing opened file. // Type: Method. // Args: vData - (R) Text data. // Return: MIstatus::success - Functional succeeded. // MIstatus::failure - Functional failed. // Throws: None. //-- bool CMIUtilFileStd::Write( const CMIUtilString & vData ) { if( vData.size() == 0 ) return MIstatus::success; if( m_bFileError ) return MIstatus::failure; if( m_pFileHandle == nullptr ) { m_bFileError = true; SetErrorDescriptionn( MIRSRC( IDE_UTIL_FILE_ERR_WRITING_NOTOPEN ), m_fileNamePath.c_str() ); return MIstatus::failure; } // Get the string size MIuint size = vData.size(); if( ::fwrite( vData.c_str(), 1, size, m_pFileHandle ) == size ) { // Flush the data to the file ::fflush( m_pFileHandle ); return MIstatus::success; } // Not all of the data has been transfered m_bFileError = true; SetErrorDescriptionn( MIRSRC( IDE_UTIL_FILE_ERR_WRITING_FILE ), m_fileNamePath.c_str() ); return MIstatus::failure; } //++ ------------------------------------------------------------------------------------ // Details: Write data to existing opened file. // Type: Method. // Args: vData - (R) Text data. // vCharCnt - (R) Text data length. // Return: MIstatus::success - Functional succeeded. // MIstatus::failure - Functional failed. // Throws: None. //-- bool CMIUtilFileStd::Write( const MIchar * vpData, const MIuint vCharCnt ) { if( vCharCnt == 0 ) return MIstatus::success; if( m_bFileError ) return MIstatus::failure; if( m_pFileHandle == nullptr ) { m_bFileError = true; SetErrorDescriptionn( MIRSRC( IDE_UTIL_FILE_ERR_WRITING_NOTOPEN ), m_fileNamePath.c_str() ); return MIstatus::failure; } if( ::fwrite( vpData, 1, vCharCnt, m_pFileHandle ) == vCharCnt ) { // Flush the data to the file ::fflush( m_pFileHandle ); return MIstatus::success; } // Not all of the data has been transfered m_bFileError = true; SetErrorDescriptionn( MIRSRC( IDE_UTIL_FILE_ERR_WRITING_FILE ), m_fileNamePath.c_str() ); return MIstatus::failure; } //++ ------------------------------------------------------------------------------------ // Details: Close existing opened file. Note Close() must must an open! // Type: Method. // Args: None. // Return: None. // Throws: None. //-- void CMIUtilFileStd::Close( void ) { if( m_pFileHandle == nullptr ) return; ::fclose( m_pFileHandle ); m_pFileHandle = nullptr; //m_bFileError = false; Do not reset as want to remain until next attempt at open or create } //++ ------------------------------------------------------------------------------------ // Details: Retrieve state of whether the file is ok. // Type: Method. // Args: None. // Return: True - file ok. // False - file has a problem. // Throws: None. //-- bool CMIUtilFileStd::IsOk( void ) const { return !m_bFileError; } //++ ------------------------------------------------------------------------------------ // Details: Status on a file existing already. // Type: Method. // Args: vFileNamePath. // Return: True - Exists. // False - Not found. // Throws: None. //-- bool CMIUtilFileStd::IsFileExist( const CMIUtilString & vFileNamePath ) const { if( vFileNamePath.empty() ) return false; FILE * pTmp = nullptr; pTmp = ::fopen( vFileNamePath.c_str(), "wb" ); if( pTmp != nullptr ) { ::fclose( pTmp ); return true; } return false; } //++ ------------------------------------------------------------------------------------ // Details: Retrieve the file current carriage line return characters used. // Type: Method. // Args: None. // Return: CMIUtilString & - Text. // Throws: None. //-- const CMIUtilString & CMIUtilFileStd::GetLineReturn( void ) const { return m_constCharNewLine; } //++ ------------------------------------------------------------------------------------ // Details: Given a file name directory path, strip off the filename and return the path. // It look for either backslash or forward slash. // Type: Method. // Args: vDirectoryPath - (R) Text directory path. // Return: CMIUtilString - Directory path. // Throws: None. //-- CMIUtilString CMIUtilFileStd::StripOffFileName( const CMIUtilString & vDirectoryPath ) const { const MIint nPos = vDirectoryPath.rfind( '\\' ); MIint nPos2 = vDirectoryPath.rfind( '/' ); if( (nPos == (MIint) std::string::npos) && (nPos2 == (MIint) std::string::npos) ) return vDirectoryPath; if( nPos > nPos2 ) nPos2 = nPos; const CMIUtilString strPath( vDirectoryPath.substr( 0, nPos2 ).c_str() ); return strPath; }
Add missing header
Add missing header Presumably included by header leakage on other platforms. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@209630 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb
9ad8cc389cd0bcf99c9c2a2497e0d8a512abae9e
lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp
lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp
//===-- WebAssemblyAsmPrinter.cpp - WebAssembly LLVM assembly writer ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file contains a printer that converts from our internal /// representation of machine-dependent LLVM code to the WebAssembly assembly /// language. /// //===----------------------------------------------------------------------===// #include "WebAssembly.h" #include "InstPrinter/WebAssemblyInstPrinter.h" #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" #include "WebAssemblyMCInstLower.h" #include "WebAssemblyMachineFunctionInfo.h" #include "WebAssemblyRegisterInfo.h" #include "WebAssemblySubtarget.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/CodeGen/Analysis.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/IR/DataLayout.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/Debug.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; #define DEBUG_TYPE "asm-printer" namespace { class WebAssemblyAsmPrinter final : public AsmPrinter { const MachineRegisterInfo *MRI; const WebAssemblyFunctionInfo *MFI; public: WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer) : AsmPrinter(TM, std::move(Streamer)), MRI(nullptr), MFI(nullptr) {} private: const char *getPassName() const override { return "WebAssembly Assembly Printer"; } //===------------------------------------------------------------------===// // MachineFunctionPass Implementation. //===------------------------------------------------------------------===// bool runOnMachineFunction(MachineFunction &MF) override { MRI = &MF.getRegInfo(); MFI = MF.getInfo<WebAssemblyFunctionInfo>(); return AsmPrinter::runOnMachineFunction(MF); } //===------------------------------------------------------------------===// // AsmPrinter Implementation. //===------------------------------------------------------------------===// void EmitJumpTableInfo() override; void EmitConstantPool() override; void EmitFunctionBodyStart() override; void EmitInstruction(const MachineInstr *MI) override; bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS) override; bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS) override; MVT getRegType(unsigned RegNo) const; const char *toString(MVT VT) const; std::string regToString(const MachineOperand &MO); }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Helpers. //===----------------------------------------------------------------------===// MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const { const TargetRegisterClass *TRC = TargetRegisterInfo::isVirtualRegister(RegNo) ? MRI->getRegClass(RegNo) : MRI->getTargetRegisterInfo()->getMinimalPhysRegClass(RegNo); for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64}) if (TRC->hasType(T)) return T; DEBUG(errs() << "Unknown type for register number: " << RegNo); llvm_unreachable("Unknown register type"); return MVT::Other; } std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) { unsigned RegNo = MO.getReg(); assert(TargetRegisterInfo::isVirtualRegister(RegNo) && "Unlowered physical register encountered during assembly printing"); assert(!MFI->isVRegStackified(RegNo)); unsigned WAReg = MFI->getWAReg(RegNo); assert(WAReg != WebAssemblyFunctionInfo::UnusedReg); return '$' + utostr(WAReg); } const char *WebAssemblyAsmPrinter::toString(MVT VT) const { return WebAssembly::TypeToString(VT); } //===----------------------------------------------------------------------===// // WebAssemblyAsmPrinter Implementation. //===----------------------------------------------------------------------===// void WebAssemblyAsmPrinter::EmitConstantPool() { assert(MF->getConstantPool()->getConstants().empty() && "WebAssembly disables constant pools"); } void WebAssemblyAsmPrinter::EmitJumpTableInfo() { // Nothing to do; jump tables are incorporated into the instruction stream. } static void ComputeLegalValueVTs(const Function &F, const TargetMachine &TM, Type *Ty, SmallVectorImpl<MVT> &ValueVTs) { const DataLayout &DL(F.getParent()->getDataLayout()); const WebAssemblyTargetLowering &TLI = *TM.getSubtarget<WebAssemblySubtarget>(F).getTargetLowering(); SmallVector<EVT, 4> VTs; ComputeValueVTs(TLI, DL, Ty, VTs); for (EVT VT : VTs) { unsigned NumRegs = TLI.getNumRegisters(F.getContext(), VT); MVT RegisterVT = TLI.getRegisterType(F.getContext(), VT); for (unsigned i = 0; i != NumRegs; ++i) ValueVTs.push_back(RegisterVT); } } void WebAssemblyAsmPrinter::EmitFunctionBodyStart() { if (!MFI->getParams().empty()) { MCInst Param; Param.setOpcode(WebAssembly::PARAM); for (MVT VT : MFI->getParams()) Param.addOperand(MCOperand::createImm(VT.SimpleTy)); EmitToStreamer(*OutStreamer, Param); } SmallVector<MVT, 4> ResultVTs; const Function &F(*MF->getFunction()); ComputeLegalValueVTs(F, TM, F.getReturnType(), ResultVTs); // If the return type needs to be legalized it will get converted into // passing a pointer. if (ResultVTs.size() == 1) { MCInst Result; Result.setOpcode(WebAssembly::RESULT); Result.addOperand(MCOperand::createImm(ResultVTs.front().SimpleTy)); EmitToStreamer(*OutStreamer, Result); } bool AnyWARegs = false; MCInst Local; Local.setOpcode(WebAssembly::LOCAL); for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) { unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx); unsigned WAReg = MFI->getWAReg(VReg); // Don't declare unused registers. if (WAReg == WebAssemblyFunctionInfo::UnusedReg) continue; // Don't redeclare parameters. if (WAReg < MFI->getParams().size()) continue; // Don't declare stackified registers. if (int(WAReg) < 0) continue; Local.addOperand(MCOperand::createImm(getRegType(VReg).SimpleTy)); AnyWARegs = true; } auto &PhysRegs = MFI->getPhysRegs(); for (unsigned PReg = 0; PReg < PhysRegs.size(); ++PReg) { if (PhysRegs[PReg] == -1U) continue; Local.addOperand(MCOperand::createImm(getRegType(PReg).SimpleTy)); AnyWARegs = true; } if (AnyWARegs) EmitToStreamer(*OutStreamer, Local); AsmPrinter::EmitFunctionBodyStart(); } void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) { DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n'); switch (MI->getOpcode()) { case WebAssembly::ARGUMENT_I32: case WebAssembly::ARGUMENT_I64: case WebAssembly::ARGUMENT_F32: case WebAssembly::ARGUMENT_F64: // These represent values which are live into the function entry, so there's // no instruction to emit. break; case WebAssembly::LOOP_END: // This is a no-op which just exists to tell AsmPrinter.cpp that there's a // fallthrough which nevertheless requires a label for the destination here. break; default: { WebAssemblyMCInstLower MCInstLowering(OutContext, *this); MCInst TmpInst; MCInstLowering.Lower(MI, TmpInst); EmitToStreamer(*OutStreamer, TmpInst); break; } } } bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS) { if (AsmVariant != 0) report_fatal_error("There are no defined alternate asm variants"); // First try the generic code, which knows about modifiers like 'c' and 'n'. if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS)) return false; if (!ExtraCode) { const MachineOperand &MO = MI->getOperand(OpNo); switch (MO.getType()) { case MachineOperand::MO_Immediate: OS << MO.getImm(); return false; case MachineOperand::MO_Register: OS << regToString(MO); return false; case MachineOperand::MO_GlobalAddress: getSymbol(MO.getGlobal())->print(OS, MAI); printOffset(MO.getOffset(), OS); return false; case MachineOperand::MO_ExternalSymbol: GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI); printOffset(MO.getOffset(), OS); return false; case MachineOperand::MO_MachineBasicBlock: MO.getMBB()->getSymbol()->print(OS, MAI); return false; default: break; } } return true; } bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS) { if (AsmVariant != 0) report_fatal_error("There are no defined alternate asm variants"); if (!ExtraCode) { // TODO: For now, we just hard-code 0 as the constant offset; teach // SelectInlineAsmMemoryOperand how to do address mode matching. OS << "0(" + regToString(MI->getOperand(OpNo)) + ')'; return false; } return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS); } // Force static initialization. extern "C" void LLVMInitializeWebAssemblyAsmPrinter() { RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32); RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64); }
//===-- WebAssemblyAsmPrinter.cpp - WebAssembly LLVM assembly writer ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file contains a printer that converts from our internal /// representation of machine-dependent LLVM code to the WebAssembly assembly /// language. /// //===----------------------------------------------------------------------===// #include "WebAssembly.h" #include "InstPrinter/WebAssemblyInstPrinter.h" #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" #include "WebAssemblyMCInstLower.h" #include "WebAssemblyMachineFunctionInfo.h" #include "WebAssemblyRegisterInfo.h" #include "WebAssemblySubtarget.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/CodeGen/Analysis.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/IR/DataLayout.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/Debug.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; #define DEBUG_TYPE "asm-printer" namespace { class WebAssemblyAsmPrinter final : public AsmPrinter { const MachineRegisterInfo *MRI; const WebAssemblyFunctionInfo *MFI; public: WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer) : AsmPrinter(TM, std::move(Streamer)), MRI(nullptr), MFI(nullptr) {} private: const char *getPassName() const override { return "WebAssembly Assembly Printer"; } //===------------------------------------------------------------------===// // MachineFunctionPass Implementation. //===------------------------------------------------------------------===// bool runOnMachineFunction(MachineFunction &MF) override { MRI = &MF.getRegInfo(); MFI = MF.getInfo<WebAssemblyFunctionInfo>(); return AsmPrinter::runOnMachineFunction(MF); } //===------------------------------------------------------------------===// // AsmPrinter Implementation. //===------------------------------------------------------------------===// void EmitJumpTableInfo() override; void EmitConstantPool() override; void EmitFunctionBodyStart() override; void EmitInstruction(const MachineInstr *MI) override; bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS) override; bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS) override; MVT getRegType(unsigned RegNo) const; const char *toString(MVT VT) const; std::string regToString(const MachineOperand &MO); }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Helpers. //===----------------------------------------------------------------------===// MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const { const TargetRegisterClass *TRC = TargetRegisterInfo::isVirtualRegister(RegNo) ? MRI->getRegClass(RegNo) : MRI->getTargetRegisterInfo()->getMinimalPhysRegClass(RegNo); for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64}) if (TRC->hasType(T)) return T; DEBUG(errs() << "Unknown type for register number: " << RegNo); llvm_unreachable("Unknown register type"); return MVT::Other; } std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) { unsigned RegNo = MO.getReg(); assert(TargetRegisterInfo::isVirtualRegister(RegNo) && "Unlowered physical register encountered during assembly printing"); assert(!MFI->isVRegStackified(RegNo)); unsigned WAReg = MFI->getWAReg(RegNo); assert(WAReg != WebAssemblyFunctionInfo::UnusedReg); return '$' + utostr(WAReg); } const char *WebAssemblyAsmPrinter::toString(MVT VT) const { return WebAssembly::TypeToString(VT); } //===----------------------------------------------------------------------===// // WebAssemblyAsmPrinter Implementation. //===----------------------------------------------------------------------===// void WebAssemblyAsmPrinter::EmitConstantPool() { assert(MF->getConstantPool()->getConstants().empty() && "WebAssembly disables constant pools"); } void WebAssemblyAsmPrinter::EmitJumpTableInfo() { // Nothing to do; jump tables are incorporated into the instruction stream. } static void ComputeLegalValueVTs(const Function &F, const TargetMachine &TM, Type *Ty, SmallVectorImpl<MVT> &ValueVTs) { const DataLayout &DL(F.getParent()->getDataLayout()); const WebAssemblyTargetLowering &TLI = *TM.getSubtarget<WebAssemblySubtarget>(F).getTargetLowering(); SmallVector<EVT, 4> VTs; ComputeValueVTs(TLI, DL, Ty, VTs); for (EVT VT : VTs) { unsigned NumRegs = TLI.getNumRegisters(F.getContext(), VT); MVT RegisterVT = TLI.getRegisterType(F.getContext(), VT); for (unsigned i = 0; i != NumRegs; ++i) ValueVTs.push_back(RegisterVT); } } void WebAssemblyAsmPrinter::EmitFunctionBodyStart() { if (!MFI->getParams().empty()) { MCInst Param; Param.setOpcode(WebAssembly::PARAM); for (MVT VT : MFI->getParams()) Param.addOperand(MCOperand::createImm(VT.SimpleTy)); EmitToStreamer(*OutStreamer, Param); } SmallVector<MVT, 4> ResultVTs; const Function &F(*MF->getFunction()); ComputeLegalValueVTs(F, TM, F.getReturnType(), ResultVTs); // If the return type needs to be legalized it will get converted into // passing a pointer. if (ResultVTs.size() == 1) { MCInst Result; Result.setOpcode(WebAssembly::RESULT); Result.addOperand(MCOperand::createImm(ResultVTs.front().SimpleTy)); EmitToStreamer(*OutStreamer, Result); } bool AnyWARegs = false; MCInst Local; Local.setOpcode(WebAssembly::LOCAL); for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) { unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx); unsigned WAReg = MFI->getWAReg(VReg); // Don't declare unused registers. if (WAReg == WebAssemblyFunctionInfo::UnusedReg) continue; // Don't redeclare parameters. if (WAReg < MFI->getParams().size()) continue; // Don't declare stackified registers. if (int(WAReg) < 0) continue; Local.addOperand(MCOperand::createImm(getRegType(VReg).SimpleTy)); AnyWARegs = true; } auto &PhysRegs = MFI->getPhysRegs(); for (unsigned PReg = 0; PReg < PhysRegs.size(); ++PReg) { if (PhysRegs[PReg] == -1U) continue; Local.addOperand(MCOperand::createImm(getRegType(PReg).SimpleTy)); AnyWARegs = true; } if (AnyWARegs) EmitToStreamer(*OutStreamer, Local); AsmPrinter::EmitFunctionBodyStart(); } void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) { DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n'); switch (MI->getOpcode()) { case WebAssembly::ARGUMENT_I32: case WebAssembly::ARGUMENT_I64: case WebAssembly::ARGUMENT_F32: case WebAssembly::ARGUMENT_F64: // These represent values which are live into the function entry, so there's // no instruction to emit. break; case WebAssembly::LOOP_END: // This is a no-op which just exists to tell AsmPrinter.cpp that there's a // fallthrough which nevertheless requires a label for the destination here. break; default: { WebAssemblyMCInstLower MCInstLowering(OutContext, *this); MCInst TmpInst; MCInstLowering.Lower(MI, TmpInst); EmitToStreamer(*OutStreamer, TmpInst); break; } } } bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS) { if (AsmVariant != 0) report_fatal_error("There are no defined alternate asm variants"); // First try the generic code, which knows about modifiers like 'c' and 'n'. if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS)) return false; if (!ExtraCode) { const MachineOperand &MO = MI->getOperand(OpNo); switch (MO.getType()) { case MachineOperand::MO_Immediate: OS << MO.getImm(); return false; case MachineOperand::MO_Register: OS << regToString(MO); return false; case MachineOperand::MO_GlobalAddress: getSymbol(MO.getGlobal())->print(OS, MAI); printOffset(MO.getOffset(), OS); return false; case MachineOperand::MO_ExternalSymbol: GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI); printOffset(MO.getOffset(), OS); return false; case MachineOperand::MO_MachineBasicBlock: MO.getMBB()->getSymbol()->print(OS, MAI); return false; default: break; } } return true; } bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS) { if (AsmVariant != 0) report_fatal_error("There are no defined alternate asm variants"); if (!ExtraCode) { // TODO: For now, we just hard-code 0 as the constant offset; teach // SelectInlineAsmMemoryOperand how to do address mode matching. OS << "0(" + regToString(MI->getOperand(OpNo)) + ')'; return false; } return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS); } // Force static initialization. extern "C" void LLVMInitializeWebAssemblyAsmPrinter() { RegisterAsmPrinter<WebAssemblyAsmPrinter> X(TheWebAssemblyTarget32); RegisterAsmPrinter<WebAssemblyAsmPrinter> Y(TheWebAssemblyTarget64); }
Remove now-unused include
Remove now-unused include git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@255817 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm
10cf24145043d9af4e3649f2baddb7d6490b98ce
include/arrayadapt/arrayadapt.hpp
include/arrayadapt/arrayadapt.hpp
#ifndef HAVE_ARRAYADAPT_ARRAYADAPT_HPP #define HAVE_ARRAYADAPT_ARRAYADAPT_HPP #include <stdint.h> #include <matrix.h> #include <mex.h> #include "../mx_traits.hpp" #include "./detail/get.hpp" #include "./detail/factory.hpp" namespace arrayadapt { /* * */ namespace ptr_access { /* * */ struct real { static inline double* get_ptr(const mxArray *u) { return mxGetPr(u); } }; struct imag { static inline double* get_ptr(const mxArray *u) { return mxGetPi(u); } }; } // namespace ptr_access template <class DataT, size_t kDims> class ArrayAdapter : public detail::Getter<DataT, kDims, ArrayAdapter >, public detail::Factory<DataT, kDims, ArrayAdapter > { /* * */ public: friend class detail::Getter<DataT, kDims, ArrayAdapter >; friend class detail::Factory<DataT, kDims, ArrayAdapter >; typedef DataT value_type; ArrayAdapter() { } // BEWARE!! this guy does not do any bounds checking, even in debug mode! inline DataT& operator[](size_t i) const { return mat_[i]; } protected: explicit ArrayAdapter(void* const mat) : mat_(static_cast<DataT*>(mat)) { } DataT *mat_; size_t dimensions[kDims]; static const size_t num_dims = kDims; }; } // namespace arrayadapt #endif // HAVE_ARRAYADAPT_ARRAYADAPT_HPP
#ifndef HAVE_ARRAYADAPT_ARRAYADAPT_HPP #define HAVE_ARRAYADAPT_ARRAYADAPT_HPP #include <stdint.h> #include <matrix.h> #include <mex.h> #include "../mx_traits.hpp" #include "./detail/get.hpp" #include "./detail/factory.hpp" namespace arrayadapt { /* * */ namespace ptr_access { /* * */ struct real { static inline double* get_ptr(const mxArray *u) { return mxGetPr(u); } }; struct imag { static inline double* get_ptr(const mxArray *u) { return mxGetPi(u); } }; } // namespace ptr_access template <class DataT, size_t kDims> class ArrayAdapter : public detail::Getter<DataT, kDims, ArrayAdapter>, public detail::Factory<DataT, kDims, ArrayAdapter> { /* * */ public: friend struct detail::Getter<DataT, kDims, arrayadapt::ArrayAdapter>; friend struct detail::Factory<DataT, kDims, arrayadapt::ArrayAdapter>; typedef DataT value_type; ArrayAdapter() { } // BEWARE!! this guy does not do any bounds checking, even in debug mode! inline DataT& operator[](size_t i) const { return mat_[i]; } protected: explicit ArrayAdapter(void* const mat) : mat_(static_cast<DataT*>(mat)) { } DataT *mat_; size_t dimensions[kDims]; static const size_t num_dims = kDims; }; } // namespace arrayadapt #endif // HAVE_ARRAYADAPT_ARRAYADAPT_HPP
work around MSVC++ name lookup
work around MSVC++ name lookup
C++
bsd-2-clause
Dunkelschorsch/arrayadapt,Dunkelschorsch/arrayadapt
0c9cade7c9c5e0e78a95e31c5e18fba4c27dd4b6
volume_I/acm_1089.cpp
volume_I/acm_1089.cpp
/* * File: main.cpp * Author: asus * * Created on December 29, 2016, 8:36 PM * * acm.timus.ru * */ #include <cstdio> #include <cstdlib> #include <cstring> struct word { char s[ 16 ]; // s[0] = length of word :) }; word dict[ 100 ]; int ndict; bool word_match(word const& u, word const& v) { if (u.s[8] != v.s[8])return false; int m = 0; for(int i = 0; i != 8; ++i) { m += u.s[ i ] != v.s[ i ]; } return m == 1; } char in[ 65536 * 4 ]; char const*o = 0; char *w ; int solve() { unsigned ans = 0; o = w = in; in[fread(in,1,sizeof(in)-4,stdin)] = 0; memset(dict, 0, sizeof(dict)); //read dict ndict = 0; while(*o && *o != '#') { //read next word int n= 0; while(*o != '\n')dict[ndict].s[ n++ ] = *o++; ++o;//skip '\n'; dict[ndict].s[8] = n; ++ndict; } ++o;//skip '#' if (*o == '\n')++o; while( *o ) { while(*o && !(*o >='a' && *o<='z') )*w++ = *o++;//write non-letter symbols if ( !o[ 0 ] ) break; int n = 0; word d = {}; while(*o >= 'a' && *o <='z' && n < 8 ) d.s[n++] = *o++; if (*o >= 'a' && *o <= 'z') { for(int i= 0; i != 8; ++i)*w++ = d.s[i]; do *w++ = *o++; while(*o >= 'a' && *o <='z'); } else { int i = 0; d.s[ 8 ] = n; // number of symbols. while(i != ndict && ! word_match(dict[i], d))++i; if (i != ndict) { //write dict[i] n = dict[i].s[8]; for(int j= 0; j != n; ++j) *w++ = dict[i].s[j]; ++ans; } else { //write word d itself for(int j= 0; j != n; ++j) *w++ = d.s[j]; } } } //write number of correction { unsigned u = ans, v=ans, n =0; do ++n;while(v/=10); v = n; while(n-->0)w[n] =u%10 + '0', u/=10; w += v; *w++ ='\n'; } //flush if (w != in)fwrite(in, 1, w - in, stdout); return 0; } int main(int argc, char** argv) { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif solve(); return 0; }
/* * File: main.cpp * Author: asus * * Created on December 29, 2016, 8:36 PM * * acm.timus.ru * */ #include <cstdio> #include <cstdlib> #include <cstring> struct word { char s[ 16 ]; // s[8] = length of word :) }; word dict[ 100 ]; int ndict; bool word_match(word const& u, word const& v) { if (u.s[8] != v.s[8])return false; int m = 0; for(int i = 0; i != 8; ++i) { m += u.s[ i ] != v.s[ i ]; } return m == 1; } char in[ 65536 * 4 ]; char const*o = 0; char *w ; int solve() { unsigned ans = 0; o = w = in; in[fread(in,1,sizeof(in)-4,stdin)] = 0; memset(dict, 0, sizeof(dict)); //read dict ndict = 0; while(*o && *o != '#') { //read next word int n= 0; while(*o != '\n')dict[ndict].s[ n++ ] = *o++; ++o;//skip '\n'; dict[ndict].s[8] = n; ++ndict; } ++o;//skip '#' if (*o == '\n')++o; while( *o ) { while(*o && !(*o >='a' && *o<='z') )*w++ = *o++;//write non-letter symbols if ( !o[ 0 ] ) break; int n = 0; word d = {}; while(*o >= 'a' && *o <='z' && n < 8 ) d.s[n++] = *o++; if (*o >= 'a' && *o <= 'z') { for(int i= 0; i != 8; ++i)*w++ = d.s[i]; do *w++ = *o++; while(*o >= 'a' && *o <='z'); } else { int i = 0; d.s[ 8 ] = n; // number of symbols. while(i != ndict && ! word_match(dict[i], d))++i; if (i != ndict) { //write dict[i] n = dict[i].s[8]; for(int j= 0; j != n; ++j) *w++ = dict[i].s[j]; ++ans; } else { //write word d itself for(int j= 0; j != n; ++j) *w++ = d.s[j]; } } } //write number of correction { unsigned u = ans, v=ans, n =0; do ++n;while(v/=10); v = n; while(n-->0)w[n] =u%10 + '0', u/=10; w += v; *w++ ='\n'; } //flush if (w != in)fwrite(in, 1, w - in, stdout); return 0; } int main(int argc, char** argv) { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif solve(); return 0; }
Update acm_1089.cpp
Update acm_1089.cpp
C++
mit
raidenluikang/acm.timus.ru
174a8bec26058e8885c9d7d17da5fe8fb34db05b
include/hpp/core/subchain-path.hh
include/hpp/core/subchain-path.hh
// // Copyright (c) 2016 CNRS // Authors: Joseph Mirabel // // This file is part of hpp-core // hpp-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. // // hpp-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 // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #ifndef HPP_CORE_DOF_EXTRACTED_PATH_HH # define HPP_CORE_DOF_EXTRACTED_PATH_HH # include <hpp/core/path.hh> namespace hpp { namespace core { /// \addtogroup path /// \{ /// Result of the selection of some configuration parameter of an original path /// \note Decorator design pattern /// \todo the configuration parameter cannot be rearranged. class SubchainPath : public Path { public: typedef Path parent_t; virtual ~SubchainPath () throw () {} /// Return a shared pointer to a copy of this virtual PathPtr_t copy () const { return createCopy (weak_.lock ()); } /// Return a shared pointer to a copy of this and set constraints /// /// \param constraints constraints to apply to the copy /// \pre *this should not have constraints. virtual PathPtr_t copy (const ConstraintSetPtr_t& constraints) const { return createCopy (weak_.lock (), constraints); } static SubchainPathPtr_t create (const PathPtr_t& original, const segments_t& intervals) { SubchainPath* ptr = new SubchainPath (original, intervals); SubchainPathPtr_t shPtr (ptr); ptr->init (shPtr); return shPtr; } static SubchainPathPtr_t createCopy (const SubchainPathPtr_t& path) { SubchainPath* ptr = new SubchainPath (*path); SubchainPathPtr_t shPtr (ptr); ptr->init (shPtr); return shPtr; } static SubchainPathPtr_t createCopy (const SubchainPathPtr_t& path, const ConstraintSetPtr_t& constraints) { SubchainPath* ptr = new SubchainPath (*path, constraints); SubchainPathPtr_t shPtr (ptr); ptr->init (shPtr); return shPtr; } virtual bool impl_compute (ConfigurationOut_t result, value_type param) const { bool success = (*original_) (q_, param); if (success) dofExtract (q_, result); return success; } /// Get the initial configuration inline Configuration_t initial () const { Configuration_t q(outputSize()); dofExtract(original_->initial(), q); return q; } /// Get the final configuration inline Configuration_t end () const { Configuration_t q(outputSize()); dofExtract(original_->end(), q); return q; } void dofExtract (ConfigurationIn_t qin, ConfigurationOut_t qout) const { size_type r = 0; for (segments_t::const_iterator _rank = intervals_.begin(); _rank != intervals_.end(); ++_rank) { qout.segment(r, _rank->second) = qin.segment(_rank->first, _rank->second); r += _rank->second; } assert (r == outputSize()); } protected: /// Print path in a stream virtual std::ostream& print (std::ostream &os) const { os << "Dof Extracted Path:" << std::endl; os << "intervals: "; for (segments_t::const_iterator _rank = intervals_.begin(); _rank != intervals_.end(); ++_rank) os << "[ " << _rank->first << ", " << _rank->second << "], " << std::endl; os << "original path:" << std::endl; os << *original_ << std::endl; return os; } /// Constructor /// /// \param original Path to extract, /// \param intervals of the configuration parameters to be extracted SubchainPath (const PathPtr_t& original, const segments_t& intervals) : Path (original->timeRange(), intervalsToSize(intervals), outputSize ()), original_ (original), intervals_ (intervals), q_ (Configuration_t::Zero(original->outputSize())) {} SubchainPath (const SubchainPath& path) : Path (path), original_ (path.original_), intervals_ (path.intervals_), q_ (path.q_), weak_ () { } SubchainPath (const SubchainPath& path, const ConstraintSetPtr_t& constraints) : Path (path, constraints), original_ (path.original_), intervals_ (path.intervals_), weak_ () { } void init (SubchainPathPtr_t self) { parent_t::init (self); weak_ = self; } private: PathPtr_t original_; segments_t intervals_; mutable Configuration_t q_; SubchainPathWkPtr_t weak_; static size_type intervalsToSize(const segments_t& ints) { size_type l = 0; for (segments_t::const_iterator _rank = ints.begin(); _rank != ints.end(); ++_rank) l += _rank->second; return l; } }; // SubchainPath /// \} } // namespace core } // namespace hpp #endif // HPP_CORE_DOF_EXTRACTED_PATH_HH
// // Copyright (c) 2016 CNRS // Authors: Joseph Mirabel // // This file is part of hpp-core // hpp-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. // // hpp-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 // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #ifndef HPP_CORE_DOF_EXTRACTED_PATH_HH # define HPP_CORE_DOF_EXTRACTED_PATH_HH # include <hpp/core/path.hh> # include <hpp/constraints/matrix-view.hh> namespace hpp { namespace core { /// \addtogroup path /// \{ /// Result of the selection of some configuration parameter of an original path /// \note Decorator design pattern /// \todo the configuration parameter cannot be rearranged. class SubchainPath : public Path { public: typedef Path parent_t; virtual ~SubchainPath () throw () {} /// Return a shared pointer to a copy of this virtual PathPtr_t copy () const { return createCopy (weak_.lock ()); } /// Return a shared pointer to a copy of this and set constraints /// /// \param constraints constraints to apply to the copy /// \pre *this should not have constraints. virtual PathPtr_t copy (const ConstraintSetPtr_t& constraints) const { return createCopy (weak_.lock (), constraints); } /// \copydoc SubchainPath::SubchainPath static SubchainPathPtr_t create (const PathPtr_t& original, const segments_t& confIntervals, const segments_t& velIntervals) { SubchainPath* ptr = new SubchainPath (original, confIntervals, velIntervals); SubchainPathPtr_t shPtr (ptr); ptr->init (shPtr); return shPtr; } static SubchainPathPtr_t createCopy (const SubchainPathPtr_t& path) { SubchainPath* ptr = new SubchainPath (*path); SubchainPathPtr_t shPtr (ptr); ptr->init (shPtr); return shPtr; } static SubchainPathPtr_t createCopy (const SubchainPathPtr_t& path, const ConstraintSetPtr_t& constraints) { SubchainPath* ptr = new SubchainPath (*path, constraints); SubchainPathPtr_t shPtr (ptr); ptr->init (shPtr); return shPtr; } virtual bool impl_compute (ConfigurationOut_t result, value_type param) const { bool success = (*original_) (q_, param); if (success) dofExtract (q_, result); return success; } /// Get the initial configuration inline Configuration_t initial () const { Configuration_t q(outputSize()); dofExtract(original_->initial(), q); return q; } /// Get the final configuration inline Configuration_t end () const { Configuration_t q(outputSize()); dofExtract(original_->end(), q); return q; } void dofExtract (ConfigurationIn_t qin, ConfigurationOut_t qout) const { qout = configView_.rview (qin); } protected: /// Print path in a stream virtual std::ostream& print (std::ostream &os) const { os << "Dof Extracted Path:" << std::endl; os << "intervals: " << configView_ << std::endl; os << "original path:" << std::endl; os << *original_ << std::endl; return os; } /// Constructor /// /// \param original Path to extract, /// \param confIntervals of the configuration parameters to be extracted /// \param velIntervals of the configuration parameters to be extracted SubchainPath (const PathPtr_t& original, const segments_t& confIntervals, const segments_t& velIntervals) : Path (original->timeRange(), Eigen::BlockIndex::cardinal(confIntervals), Eigen::BlockIndex::cardinal(velIntervals)), original_ (original), configView_ (confIntervals), q_ (Configuration_t::Zero(original->outputSize())) {} SubchainPath (const SubchainPath& path) : Path (path), original_ (path.original_), configView_ (path.configView_), q_ (path.q_), weak_ () { } SubchainPath (const SubchainPath& path, const ConstraintSetPtr_t& constraints) : Path (path, constraints), original_ (path.original_), configView_ (path.configView_), weak_ () { } void init (SubchainPathPtr_t self) { parent_t::init (self); weak_ = self; } private: PathPtr_t original_; Eigen::RowBlockIndices configView_, velView_; mutable Configuration_t q_; SubchainPathWkPtr_t weak_; }; // SubchainPath /// \} } // namespace core } // namespace hpp #endif // HPP_CORE_DOF_EXTRACTED_PATH_HH
Fix SubchainPath
Fix SubchainPath
C++
bsd-2-clause
humanoid-path-planner/hpp-core
3fdeb9c3a7df08eee96b289583c98c8ecfdeb72f
cvmfs/swissknife_sign.cc
cvmfs/swissknife_sign.cc
/** * This file is part of the CernVM File System * * This tool signs a CernVM-FS manifest with an X.509 certificate. */ #include "cvmfs_config.h" #include "swissknife_sign.h" #include <dirent.h> #include <sys/stat.h> #include <sys/types.h> #include <termios.h> #include <unistd.h> #include <cstdio> #include <cstdlib> #include <iostream> // TODO(jblomer): remove #include <set> #include <string> #include <vector> #include "compression.h" #include "hash.h" #include "logging.h" #include "manifest.h" #include "signature.h" #include "smalloc.h" #include "upload.h" #include "util.h" using namespace std; // NOLINT int swissknife::CommandSign::Main(const swissknife::ArgumentList &args) { string manifest_path = *args.find('m')->second; string spooler_definition = *args.find('r')->second; string temp_dir = *args.find('t')->second; string certificate = ""; if (args.find('c') != args.end()) certificate = *args.find('c')->second; string priv_key = ""; if (args.find('k') != args.end()) priv_key = *args.find('k')->second; string repo_name = ""; if (args.find('n') != args.end()) repo_name = *args.find('n')->second; string pwd = ""; if (args.find('s') != args.end()) pwd = *args.find('s')->second; string meta_info = ""; if (args.find('M') != args.end()) meta_info = *args.find('M')->second; upload::Spooler *spooler = NULL; const bool garbage_collectable = (args.count('g') > 0); const bool bootstrap_shortcuts = (args.count('A') > 0); if (!DirectoryExists(temp_dir)) { LogCvmfs(kLogCvmfs, kLogStderr, "%s does not exist", temp_dir.c_str()); return 1; } if (!InitSigningSignatureManager(certificate, priv_key, pwd)) { return 2; } LogCvmfs(kLogCvmfs, kLogStdout, "Signing %s", manifest_path.c_str()); { // Load Manifest // TODO(rmeusel): UniquePtr manifest::Manifest *manifest = manifest::Manifest::LoadFile(manifest_path); if (!manifest) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to parse manifest"); goto sign_fail; } // Connect to the spooler const upload::SpoolerDefinition sd(spooler_definition, manifest->GetHashAlgorithm()); spooler = upload::Spooler::Construct(sd); // Register callback for retrieving the certificate hash upload::Spooler::CallbackPtr callback = spooler->RegisterListener(&CommandSign::CertificateUploadCallback, this); // Safe certificate (and wait for the upload through a Future) spooler->ProcessCertificate(certificate); const shash::Any certificate_hash = certificate_hash_.Get(); spooler->UnregisterListener(callback); if (certificate_hash.IsNull()) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to upload certificate"); goto sign_fail; } // Safe repository meta info file shash::Any metainfo_hash; if (!meta_info.empty()) { upload::Spooler::CallbackPtr callback = spooler->RegisterListener(&CommandSign::MetainfoUploadCallback, this); spooler->ProcessMetainfo(meta_info); metainfo_hash = metainfo_hash_.Get(); spooler->UnregisterListener(callback); if (metainfo_hash.IsNull()) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to upload meta info"); goto sign_fail; } } // Update manifest manifest->set_certificate(certificate_hash); manifest->set_repository_name(repo_name); manifest->set_publish_timestamp(time(NULL)); manifest->set_garbage_collectability(garbage_collectable); manifest->set_has_alt_catalog_path(bootstrap_shortcuts); if (!metainfo_hash.IsNull()) { manifest->set_meta_info(metainfo_hash); } string signed_manifest = manifest->ExportString(); shash::Any published_hash(manifest->GetHashAlgorithm()); shash::HashMem( reinterpret_cast<const unsigned char *>(signed_manifest.data()), signed_manifest.length(), &published_hash); signed_manifest += "--\n" + published_hash.ToString() + "\n"; // Create alternative bootstrapping symlinks for VOMS secured repos if (manifest->has_alt_catalog_path()) { const bool success = spooler->PlaceBootstrappingShortcut(manifest->certificate()) && spooler->PlaceBootstrappingShortcut(manifest->catalog_hash()) && (manifest->history().IsNull() || spooler->PlaceBootstrappingShortcut(manifest->history())) && (metainfo_hash.IsNull() || spooler->PlaceBootstrappingShortcut(metainfo_hash)); if (!success) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to place VOMS bootstrapping " "symlinks"); delete manifest; goto sign_fail; } } // Sign manifest unsigned char *sig; unsigned sig_size; if (!signature_manager()->Sign(reinterpret_cast<const unsigned char *>( published_hash.ToString().data()), published_hash.GetHexSize(), &sig, &sig_size)) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to sign manifest"); delete manifest; goto sign_fail; } // Write new manifest FILE *fmanifest = fopen(manifest_path.c_str(), "w"); if (!fmanifest) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to open manifest (errno: %d)", errno); delete manifest; goto sign_fail; } if ((fwrite(signed_manifest.data(), 1, signed_manifest.length(), fmanifest) != signed_manifest.length()) || (fwrite(sig, 1, sig_size, fmanifest) != sig_size)) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to write manifest (errno: %d)", errno); fclose(fmanifest); delete manifest; goto sign_fail; } free(sig); fclose(fmanifest); // Upload manifest spooler->Upload(manifest_path, ".cvmfspublished"); spooler->WaitForUpload(); unlink(manifest_path.c_str()); if (spooler->GetNumberOfErrors()) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to commit manifest (errors: %d)", spooler->GetNumberOfErrors()); delete manifest; goto sign_fail; } delete manifest; } delete spooler; return 0; sign_fail: delete spooler; return 1; } void swissknife::CommandSign::CertificateUploadCallback( const upload::SpoolerResult &result) { shash::Any certificate_hash; if (result.return_code == 0) { certificate_hash = result.content_hash; } else { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to upload certificate " "(retcode: %d)", result.return_code); } certificate_hash_.Set(certificate_hash); } void swissknife::CommandSign::MetainfoUploadCallback( const upload::SpoolerResult &result) { shash::Any metainfo_hash; if (result.return_code == 0) { metainfo_hash = result.content_hash; } else { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to upload meta info (retcode: %d)", result.return_code); } metainfo_hash_.Set(metainfo_hash); }
/** * This file is part of the CernVM File System * * This tool signs a CernVM-FS manifest with an X.509 certificate. */ #include "cvmfs_config.h" #include "swissknife_sign.h" #include <dirent.h> #include <sys/stat.h> #include <sys/types.h> #include <termios.h> #include <unistd.h> #include <cstdio> #include <cstdlib> #include <iostream> // TODO(jblomer): remove #include <set> #include <string> #include <vector> #include "compression.h" #include "hash.h" #include "logging.h" #include "manifest.h" #include "signature.h" #include "smalloc.h" #include "upload.h" #include "util.h" using namespace std; // NOLINT int swissknife::CommandSign::Main(const swissknife::ArgumentList &args) { string manifest_path = *args.find('m')->second; string spooler_definition = *args.find('r')->second; string temp_dir = *args.find('t')->second; string certificate = ""; if (args.find('c') != args.end()) certificate = *args.find('c')->second; string priv_key = ""; if (args.find('k') != args.end()) priv_key = *args.find('k')->second; string repo_name = ""; if (args.find('n') != args.end()) repo_name = *args.find('n')->second; string pwd = ""; if (args.find('s') != args.end()) pwd = *args.find('s')->second; string meta_info = ""; if (args.find('M') != args.end()) meta_info = *args.find('M')->second; const bool garbage_collectable = (args.count('g') > 0); const bool bootstrap_shortcuts = (args.count('A') > 0); UniquePtr<upload::Spooler> spooler; UniquePtr<manifest::Manifest> manifest; if (!DirectoryExists(temp_dir)) { LogCvmfs(kLogCvmfs, kLogStderr, "%s does not exist", temp_dir.c_str()); return 1; } if (!InitSigningSignatureManager(certificate, priv_key, pwd)) { return 2; } LogCvmfs(kLogCvmfs, kLogStdout, "Signing %s", manifest_path.c_str()); { // Load Manifest manifest = manifest::Manifest::LoadFile(manifest_path); if (!manifest.IsValid()) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to parse manifest"); return 1; } // Connect to the spooler const upload::SpoolerDefinition sd(spooler_definition, manifest->GetHashAlgorithm()); spooler = upload::Spooler::Construct(sd); if (!spooler.IsValid()) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to setup upload spooler"); return 1; } // Register callback for retrieving the certificate hash upload::Spooler::CallbackPtr callback = spooler->RegisterListener(&CommandSign::CertificateUploadCallback, this); // Safe certificate (and wait for the upload through a Future) spooler->ProcessCertificate(certificate); const shash::Any certificate_hash = certificate_hash_.Get(); spooler->UnregisterListener(callback); if (certificate_hash.IsNull()) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to upload certificate"); return 1; } // Safe repository meta info file shash::Any metainfo_hash; if (!meta_info.empty()) { upload::Spooler::CallbackPtr callback = spooler->RegisterListener(&CommandSign::MetainfoUploadCallback, this); spooler->ProcessMetainfo(meta_info); metainfo_hash = metainfo_hash_.Get(); spooler->UnregisterListener(callback); if (metainfo_hash.IsNull()) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to upload meta info"); return 1; } } // Update manifest manifest->set_certificate(certificate_hash); manifest->set_repository_name(repo_name); manifest->set_publish_timestamp(time(NULL)); manifest->set_garbage_collectability(garbage_collectable); manifest->set_has_alt_catalog_path(bootstrap_shortcuts); if (!metainfo_hash.IsNull()) { manifest->set_meta_info(metainfo_hash); } string signed_manifest = manifest->ExportString(); shash::Any published_hash(manifest->GetHashAlgorithm()); shash::HashMem( reinterpret_cast<const unsigned char *>(signed_manifest.data()), signed_manifest.length(), &published_hash); signed_manifest += "--\n" + published_hash.ToString() + "\n"; // Create alternative bootstrapping symlinks for VOMS secured repos if (manifest->has_alt_catalog_path()) { const bool success = spooler->PlaceBootstrappingShortcut(manifest->certificate()) && spooler->PlaceBootstrappingShortcut(manifest->catalog_hash()) && (manifest->history().IsNull() || spooler->PlaceBootstrappingShortcut(manifest->history())) && (metainfo_hash.IsNull() || spooler->PlaceBootstrappingShortcut(metainfo_hash)); if (!success) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to place VOMS bootstrapping " "symlinks"); return 1; } } // Sign manifest unsigned char *sig; unsigned sig_size; if (!signature_manager()->Sign(reinterpret_cast<const unsigned char *>( published_hash.ToString().data()), published_hash.GetHexSize(), &sig, &sig_size)) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to sign manifest"); return 1; } // Write new manifest FILE *fmanifest = fopen(manifest_path.c_str(), "w"); if (!fmanifest) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to open manifest (errno: %d)", errno); return 1; } if ((fwrite(signed_manifest.data(), 1, signed_manifest.length(), fmanifest) != signed_manifest.length()) || (fwrite(sig, 1, sig_size, fmanifest) != sig_size)) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to write manifest (errno: %d)", errno); fclose(fmanifest); return 1; } free(sig); fclose(fmanifest); // Upload manifest spooler->Upload(manifest_path, ".cvmfspublished"); spooler->WaitForUpload(); unlink(manifest_path.c_str()); if (spooler->GetNumberOfErrors()) { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to commit manifest (errors: %d)", spooler->GetNumberOfErrors()); return 1; } } return 0; } void swissknife::CommandSign::CertificateUploadCallback( const upload::SpoolerResult &result) { shash::Any certificate_hash; if (result.return_code == 0) { certificate_hash = result.content_hash; } else { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to upload certificate " "(retcode: %d)", result.return_code); } certificate_hash_.Set(certificate_hash); } void swissknife::CommandSign::MetainfoUploadCallback( const upload::SpoolerResult &result) { shash::Any metainfo_hash; if (result.return_code == 0) { metainfo_hash = result.content_hash; } else { LogCvmfs(kLogCvmfs, kLogStderr, "Failed to upload meta info (retcode: %d)", result.return_code); } metainfo_hash_.Set(metainfo_hash); }
use UniquePtr and get rid of effing goto
Refactor: use UniquePtr and get rid of effing goto
C++
bsd-3-clause
DrDaveD/cvmfs,trshaffer/cvmfs,DrDaveD/cvmfs,cvmfs/cvmfs,reneme/cvmfs,reneme/cvmfs,alhowaidi/cvmfsNDN,trshaffer/cvmfs,alhowaidi/cvmfsNDN,alhowaidi/cvmfsNDN,Gangbiao/cvmfs,Gangbiao/cvmfs,reneme/cvmfs,alhowaidi/cvmfsNDN,Gangbiao/cvmfs,DrDaveD/cvmfs,cvmfs/cvmfs,DrDaveD/cvmfs,trshaffer/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs,reneme/cvmfs,cvmfs/cvmfs,DrDaveD/cvmfs,Gangbiao/cvmfs,reneme/cvmfs,djw8605/cvmfs,trshaffer/cvmfs,alhowaidi/cvmfsNDN,DrDaveD/cvmfs,djw8605/cvmfs,djw8605/cvmfs,djw8605/cvmfs,trshaffer/cvmfs,Gangbiao/cvmfs,DrDaveD/cvmfs,djw8605/cvmfs
17477fc65fe469fefcea455ac5d24733f4fd961c
modules/heat_conduction/src/interfacekernels/ConjugateHeatTransfer.C
modules/heat_conduction/src/interfacekernels/ConjugateHeatTransfer.C
#include "ConjugateHeatTransfer.h" #include "metaphysicl/raw_type.h" using MetaPhysicL::raw_value; registerMooseObject("HeatConductionApp", ConjugateHeatTransfer); InputParameters ConjugateHeatTransfer::validParams() { InputParameters params = InterfaceKernel::validParams(); params.addRequiredParam<MaterialPropertyName>("htc", "heat transfer coefficient"); params.addRequiredCoupledVar("T_fluid", "The fluid temperature. It is not always identical to neighbor_var, " "e.g. when the fluid heat equation is solved for internal energy"); params.addClassDescription( "This InterfaceKernel models conjugate heat transfer. Fluid side must " "be master side and solid side must be slave side. T_fluid is provided in case that variable " "(== fluid energy variable) is not temperature but e.g. internal energy."); return params; } ConjugateHeatTransfer::ConjugateHeatTransfer(const InputParameters & parameters) : InterfaceKernel(parameters), _h(getADMaterialProperty<Real>("htc")) _T_fluid(coupledValue("T_fluid")), _apply_element_jacobian(_var.name() == getParam<std::vector<VariableName>>("T_fluid")[0]) { } Real ConjugateHeatTransfer::computeQpResidual(Moose::DGResidualType type) { switch (type) { case Moose::Element: return raw_value(_h[_qp]) * (_T_fluid[_qp] - _neighbor_value[_qp]) * _test[_i][_qp]; case Moose::Neighbor: return raw_value(_h[_qp]) * (_neighbor_value[_qp] - _T_fluid[_qp]) * _test_neighbor[_i][_qp]; default: return 0.0; } } Real ConjugateHeatTransfer::computeQpJacobian(Moose::DGJacobianType type) { switch (type) { case Moose::ElementElement: return _apply_element_jacobian ? raw_value(_h[_qp]) * _phi[_j][_qp] * _test[_i][_qp] : 0; case Moose::NeighborNeighbor: return raw_value(_h[_qp]) * _phi_neighbor[_j][_qp] * _test_neighbor[_i][_qp]; case Moose::NeighborElement: return _apply_element_jacobian ? raw_value(_h[_qp]) * -_phi[_j][_qp] * _test_neighbor[_i][_qp] : 0; case Moose::ElementNeighbor: return raw_value(_h[_qp]) * -_phi_neighbor[_j][_qp] * _test[_i][_qp]; default: return 0.0; } }
#include "ConjugateHeatTransfer.h" #include "metaphysicl/raw_type.h" using MetaPhysicL::raw_value; registerMooseObject("HeatConductionApp", ConjugateHeatTransfer); InputParameters ConjugateHeatTransfer::validParams() { InputParameters params = InterfaceKernel::validParams(); params.addRequiredParam<MaterialPropertyName>("htc", "heat transfer coefficient"); params.addRequiredCoupledVar("T_fluid", "The fluid temperature. It is not always identical to neighbor_var, " "e.g. when the fluid heat equation is solved for internal energy"); params.addClassDescription( "This InterfaceKernel models conjugate heat transfer. Fluid side must " "be master side and solid side must be slave side. T_fluid is provided in case that variable " "(== fluid energy variable) is not temperature but e.g. internal energy."); return params; } ConjugateHeatTransfer::ConjugateHeatTransfer(const InputParameters & parameters) : InterfaceKernel(parameters), _h(getADMaterialProperty<Real>("htc")), _T_fluid(coupledValue("T_fluid")), _apply_element_jacobian(_var.name() == getParam<std::vector<VariableName>>("T_fluid")[0]) { } Real ConjugateHeatTransfer::computeQpResidual(Moose::DGResidualType type) { switch (type) { case Moose::Element: return raw_value(_h[_qp]) * (_T_fluid[_qp] - _neighbor_value[_qp]) * _test[_i][_qp]; case Moose::Neighbor: return raw_value(_h[_qp]) * (_neighbor_value[_qp] - _T_fluid[_qp]) * _test_neighbor[_i][_qp]; default: return 0.0; } } Real ConjugateHeatTransfer::computeQpJacobian(Moose::DGJacobianType type) { switch (type) { case Moose::ElementElement: return _apply_element_jacobian ? raw_value(_h[_qp]) * _phi[_j][_qp] * _test[_i][_qp] : 0; case Moose::NeighborNeighbor: return raw_value(_h[_qp]) * _phi_neighbor[_j][_qp] * _test_neighbor[_i][_qp]; case Moose::NeighborElement: return _apply_element_jacobian ? raw_value(_h[_qp]) * -_phi[_j][_qp] * _test_neighbor[_i][_qp] : 0; case Moose::ElementNeighbor: return raw_value(_h[_qp]) * -_phi_neighbor[_j][_qp] * _test[_i][_qp]; default: return 0.0; } }
Add a comma
Add a comma refs #15114
C++
lgpl-2.1
idaholab/moose,harterj/moose,nuclear-wizard/moose,laagesen/moose,jessecarterMOOSE/moose,dschwen/moose,bwspenc/moose,sapitts/moose,jessecarterMOOSE/moose,andrsd/moose,milljm/moose,SudiptaBiswas/moose,dschwen/moose,jessecarterMOOSE/moose,lindsayad/moose,dschwen/moose,harterj/moose,bwspenc/moose,dschwen/moose,SudiptaBiswas/moose,milljm/moose,jessecarterMOOSE/moose,harterj/moose,SudiptaBiswas/moose,milljm/moose,andrsd/moose,jessecarterMOOSE/moose,andrsd/moose,harterj/moose,laagesen/moose,sapitts/moose,idaholab/moose,laagesen/moose,andrsd/moose,andrsd/moose,dschwen/moose,nuclear-wizard/moose,idaholab/moose,sapitts/moose,lindsayad/moose,idaholab/moose,lindsayad/moose,idaholab/moose,bwspenc/moose,bwspenc/moose,sapitts/moose,nuclear-wizard/moose,SudiptaBiswas/moose,lindsayad/moose,harterj/moose,bwspenc/moose,SudiptaBiswas/moose,milljm/moose,laagesen/moose,lindsayad/moose,nuclear-wizard/moose,sapitts/moose,milljm/moose,laagesen/moose
db9bc5877716aa57fb93d0bfe809f2c4053bfc7a
tests/General.cc
tests/General.cc
#include <iostream> #include <string> #include <thread> #include "gtest/gtest.h" #include "sigs.h" TEST(General, instantiate) { sigs::Signal<void()> s; sigs::Signal<void(int)> s2; sigs::Signal<int()> s3; } inline void addOne(int &i) { i++; } TEST(General, function) { sigs::Signal<void(int &)> s; s.connect(addOne); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, multipleFunctions) { sigs::Signal<void(int &)> s; s.connect(addOne); s.connect(addOne); s.connect(addOne); int i = 0; s(i); EXPECT_EQ(i, 3); } TEST(General, functor) { class AddOneFunctor { public: void operator()(int &i) const { i++; } }; sigs::Signal<void(int &)> s; s.connect(AddOneFunctor()); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, instanceMethod) { class Foo { public: void test(int &i) const { i++; } }; sigs::Signal<void(int &)> s; Foo foo; s.connect(&foo, &Foo::test); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, lambda) { sigs::Signal<void(int &)> s; s.connect([](int &i) { i++; }); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, connectionDisconnectDirectly) { sigs::Signal<void(int &)> s; auto conn = s.connect([](int &i) { i++; }); int i = 0; s(i); EXPECT_EQ(i, 1); conn->disconnect(); s(i); EXPECT_EQ(i, 1); } TEST(General, connectionDisconnectOnSignal) { sigs::Signal<void(int &)> s; auto conn = s.connect([](int &i) { i++; }); int i = 0; s(i); EXPECT_EQ(i, 1); s.disconnect(conn); s(i); EXPECT_EQ(i, 1); } TEST(General, connectSignalToSignal) { sigs::Signal<void(int &)> s1; s1.connect([](int &i) { i++; }); decltype(s1) s2; s2.connect(s1); int i = 0; s2(i); EXPECT_EQ(i, 1); } TEST(General, disconnectSignalFromSignal) { sigs::Signal<void(int &)> s1; s1.connect([](int &i) { i++; }); decltype(s1) s2; s2.connect(s1); s2.disconnect(s1); int i = 0; s2(i); EXPECT_EQ(i, 0); } // Check for debug assertion. #ifndef NDEBUG TEST(General, disconnectSignalFromSelf) { sigs::Signal<void()> s; EXPECT_DEATH(s.disconnect(s), "Disconnecting from self has no effect."); } #endif TEST(General, ambiguousMembers) { class Ambiguous { public: void foo(int i) { value += i; } void foo(float j) { value += static_cast<int>(j); } int value = 0; }; sigs::Signal<void(int)> s; Ambiguous amb; auto conn = s.connect(&amb, sigs::Use<int>::overloadOf(&Ambiguous::foo)); s(42); EXPECT_EQ(amb.value, 42); conn->disconnect(); // This one only works because int can be coerced into float. s.connect(&amb, sigs::Use<float>::overloadOf(&Ambiguous::foo)); s(1); EXPECT_EQ(amb.value, 43); } TEST(General, returnValues) { sigs::Signal<int()> s; s.connect([] { return 1; }); s.connect([] { return 2; }); s.connect([] { return 3; }); int sum = 0; s([&sum](int retVal) { sum += retVal; }); EXPECT_EQ(sum, 1 + 2 + 3); } TEST(General, returnValuesWithSignals) { sigs::Signal<int()> s, s2, s3; s3.connect([] { return 1; }); s2.connect([] { return 2; }); s2.connect([] { return 3; }); s.connect(s2); s.connect(s3); s.connect([] { return 4; }); int sum = 0; s([&sum](int retVal) { sum += retVal; }); EXPECT_EQ(sum, 1 + 2 + 3 + 4); } TEST(General, returnValuesBlocked) { sigs::Signal<int()> s; s.connect([] { return 1; }); s.setBlocked(true); int sum = 0; s([&sum](int retVal) { sum += retVal; }); EXPECT_EQ(sum, 0); } TEST(General, sameSlotManyConnections) { int calls = 0; const auto slot = [&calls] { calls++; }; sigs::Signal<void()> s; s.connect(slot); s(); EXPECT_EQ(calls, 1); s.connect(slot); s(); EXPECT_EQ(calls, 3); // This yielded 4 calls when eraseEntries() didn't clear correctly. s.clear(); s(); EXPECT_EQ(calls, 3); } TEST(General, clearEquivalentToAllDisconnects) { int calls = 0; const auto slot = [&calls] { calls++; }; sigs::Signal<void()> s; { calls = 0; auto conn1 = s.connect(slot); auto conn2 = s.connect(slot); s(); EXPECT_EQ(calls, 2); s.clear(); s(); EXPECT_EQ(calls, 2); } { calls = 0; auto conn1 = s.connect(slot); auto conn2 = s.connect(slot); s(); EXPECT_EQ(calls, 2); s.disconnect(conn1); s.disconnect(conn2); s(); EXPECT_EQ(calls, 2); } } TEST(General, size) { sigs::Signal<void()> s; ASSERT_EQ(s.size(), 0); s.connect([] {}); s.connect([] {}); ASSERT_EQ(s.size(), 2); s.clear(); ASSERT_EQ(s.size(), 0); } TEST(General, empty) { sigs::Signal<void()> s; ASSERT_TRUE(s.empty()); s.connect([] {}); ASSERT_FALSE(s.empty()); s.clear(); ASSERT_TRUE(s.empty()); } TEST(General, disconnectWithNoSlotClearsAll) { sigs::Signal<void()> s; s.connect([] {}); s.connect([] {}); s.disconnect(); ASSERT_TRUE(s.empty()); } TEST(General, blocked) { sigs::Signal<void()> s; ASSERT_FALSE(s.blocked()); s.setBlocked(true); ASSERT_TRUE(s.blocked()); } TEST(General, blockedPreviousValue) { sigs::Signal<void()> s; ASSERT_FALSE(s.setBlocked(true)); ASSERT_TRUE(s.setBlocked(true)); } TEST(General, blockedSlots) { int calls = 0; const auto slot = [&calls] { calls++; }; sigs::Signal<void()> s; s.connect(slot); s(); ASSERT_EQ(calls, 1); s.setBlocked(true); ASSERT_TRUE(s.blocked()); s(); ASSERT_EQ(calls, 1); s.setBlocked(false); ASSERT_FALSE(s.blocked()); s(); ASSERT_EQ(calls, 2); } TEST(General, blockedSignals) { int calls = 0; const auto slot = [&calls] { calls++; }; sigs::Signal<void()> s, s2; s2.connect(slot); s.connect(s2); s(); ASSERT_EQ(calls, 1); // Block outer signal. s.setBlocked(true); ASSERT_TRUE(s.blocked()); ASSERT_FALSE(s2.blocked()); s(); ASSERT_EQ(calls, 1); s.setBlocked(false); ASSERT_FALSE(s.blocked()); s(); ASSERT_EQ(calls, 2); // Block inner signal. s2.setBlocked(true); ASSERT_TRUE(s2.blocked()); ASSERT_FALSE(s.blocked()); s(); ASSERT_EQ(calls, 2); } TEST(General, copyConstructible) { sigs::Signal<void()> s; s.connect([] {}); s.connect([] {}); s.setBlocked(true); decltype(s) s2(s); ASSERT_EQ(s2.size(), 2); ASSERT_TRUE(s2.blocked()); } TEST(General, copyAssignable) { sigs::Signal<void()> s; s.connect([] {}); s.connect([] {}); s.setBlocked(true); decltype(s) s2; s2 = s; ASSERT_EQ(s2.size(), 2); ASSERT_TRUE(s2.blocked()); } TEST(General, dontMoveRvalues) { sigs::Signal<void(std::string)> s; std::string res; auto func = [&res](std::string str) { res += str; }; s.connect(func); s.connect(func); s.connect(func); s("test"); ASSERT_EQ("testtesttest", res); } TEST(General, dontMoveRvaluesReturnValue) { sigs::Signal<int(std::string)> s; std::string res; auto func = [&res](std::string str) -> int { res += str; return 1; }; s.connect(func); s.connect(func); s.connect(func); int sum = 0; s([&sum](int retVal) { sum += retVal; }, "test"); ASSERT_EQ("testtesttest", res); ASSERT_EQ(3, sum); } TEST(General, dontMoveRvaluesSubSignal) { std::string res; auto func = [&res](std::string str) { res += str; }; sigs::Signal<void(std::string)> s; s.connect(func); decltype(s) s2; s2.connect(func); s2.connect(s); s2.connect(func); s2("test"); ASSERT_EQ("testtesttest", res); } TEST(General, threadedInvocation) { int sum = 0; auto func = [&sum] { sum++; }; sigs::Signal<void()> s; s.connect(func); s.connect(func); int n = 3; std::thread t([&s, n] { for (int i = 0; i < n; ++i) { s(); } }); t.join(); ASSERT_EQ(n * 2, sum); } TEST(General, threadedDontMoveRvalues) { int sum = 0; std::string res; auto func = [&](std::string str) { sum++; res += str; }; sigs::Signal<void(std::string)> s; s.connect(func); s.connect(func); int n = 3; std::thread t([&s, n] { for (int i = 0; i < n; ++i) { s("x"); } }); t.join(); ASSERT_EQ(n * 2, sum); ASSERT_EQ(std::string(sum, 'x'), res); }
#include <iostream> #include <string> #include <thread> #include "gtest/gtest.h" #include "sigs.h" TEST(General, instantiate) { sigs::Signal<void()> s; sigs::Signal<void(int)> s2; sigs::Signal<int()> s3; } inline void addOne(int &i) { i++; } TEST(General, function) { sigs::Signal<void(int &)> s; s.connect(addOne); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, multipleFunctions) { sigs::Signal<void(int &)> s; s.connect(addOne); s.connect(addOne); s.connect(addOne); int i = 0; s(i); EXPECT_EQ(i, 3); } TEST(General, functor) { class AddOneFunctor { public: void operator()(int &i) const { i++; } }; sigs::Signal<void(int &)> s; s.connect(AddOneFunctor()); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, instanceMethod) { class Foo { public: void test(int &i) const { i++; } }; sigs::Signal<void(int &)> s; Foo foo; s.connect(&foo, &Foo::test); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, lambda) { sigs::Signal<void(int &)> s; s.connect([](int &i) { i++; }); int i = 0; s(i); EXPECT_EQ(i, 1); } TEST(General, connectionDisconnectDirectly) { sigs::Signal<void(int &)> s; auto conn = s.connect([](int &i) { i++; }); int i = 0; s(i); EXPECT_EQ(i, 1); conn->disconnect(); s(i); EXPECT_EQ(i, 1); } TEST(General, connectionDisconnectOnSignal) { sigs::Signal<void(int &)> s; auto conn = s.connect([](int &i) { i++; }); int i = 0; s(i); EXPECT_EQ(i, 1); s.disconnect(conn); s(i); EXPECT_EQ(i, 1); } TEST(General, specificConnectionDisconnectOnSignal) { sigs::Signal<void(int &)> s; s.connect([](int &i) { i += 2; }); auto conn = s.connect([](int &i) { i += 4; }); s.connect([](int &i) { i += 8; }); int i = 0; s(i); EXPECT_EQ(i, 2 + 4 + 8); // Disconnect middle connection only. s.disconnect(conn); s(i); EXPECT_EQ(i, (2 + 4 + 8) + (2 + 8)); } TEST(General, connectSignalToSignal) { sigs::Signal<void(int &)> s1; s1.connect([](int &i) { i++; }); decltype(s1) s2; s2.connect(s1); int i = 0; s2(i); EXPECT_EQ(i, 1); } TEST(General, disconnectSignalFromSignal) { sigs::Signal<void(int &)> s1; s1.connect([](int &i) { i++; }); decltype(s1) s2; s2.connect(s1); s2.disconnect(s1); int i = 0; s2(i); EXPECT_EQ(i, 0); } // Check for debug assertion. #ifndef NDEBUG TEST(General, disconnectSignalFromSelf) { sigs::Signal<void()> s; EXPECT_DEATH(s.disconnect(s), "Disconnecting from self has no effect."); } #endif TEST(General, ambiguousMembers) { class Ambiguous { public: void foo(int i) { value += i; } void foo(float j) { value += static_cast<int>(j); } int value = 0; }; sigs::Signal<void(int)> s; Ambiguous amb; auto conn = s.connect(&amb, sigs::Use<int>::overloadOf(&Ambiguous::foo)); s(42); EXPECT_EQ(amb.value, 42); conn->disconnect(); // This one only works because int can be coerced into float. s.connect(&amb, sigs::Use<float>::overloadOf(&Ambiguous::foo)); s(1); EXPECT_EQ(amb.value, 43); } TEST(General, returnValues) { sigs::Signal<int()> s; s.connect([] { return 1; }); s.connect([] { return 2; }); s.connect([] { return 3; }); int sum = 0; s([&sum](int retVal) { sum += retVal; }); EXPECT_EQ(sum, 1 + 2 + 3); } TEST(General, returnValuesWithSignals) { sigs::Signal<int()> s, s2, s3; s3.connect([] { return 1; }); s2.connect([] { return 2; }); s2.connect([] { return 3; }); s.connect(s2); s.connect(s3); s.connect([] { return 4; }); int sum = 0; s([&sum](int retVal) { sum += retVal; }); EXPECT_EQ(sum, 1 + 2 + 3 + 4); } TEST(General, returnValuesBlocked) { sigs::Signal<int()> s; s.connect([] { return 1; }); s.setBlocked(true); int sum = 0; s([&sum](int retVal) { sum += retVal; }); EXPECT_EQ(sum, 0); } TEST(General, sameSlotManyConnections) { int calls = 0; const auto slot = [&calls] { calls++; }; sigs::Signal<void()> s; s.connect(slot); s(); EXPECT_EQ(calls, 1); s.connect(slot); s(); EXPECT_EQ(calls, 3); // This yielded 4 calls when eraseEntries() didn't clear correctly. s.clear(); s(); EXPECT_EQ(calls, 3); } TEST(General, clearEquivalentToAllDisconnects) { int calls = 0; const auto slot = [&calls] { calls++; }; sigs::Signal<void()> s; { calls = 0; auto conn1 = s.connect(slot); auto conn2 = s.connect(slot); s(); EXPECT_EQ(calls, 2); s.clear(); s(); EXPECT_EQ(calls, 2); } { calls = 0; auto conn1 = s.connect(slot); auto conn2 = s.connect(slot); s(); EXPECT_EQ(calls, 2); s.disconnect(conn1); s.disconnect(conn2); s(); EXPECT_EQ(calls, 2); } } TEST(General, size) { sigs::Signal<void()> s; ASSERT_EQ(s.size(), 0); s.connect([] {}); s.connect([] {}); ASSERT_EQ(s.size(), 2); s.clear(); ASSERT_EQ(s.size(), 0); } TEST(General, empty) { sigs::Signal<void()> s; ASSERT_TRUE(s.empty()); s.connect([] {}); ASSERT_FALSE(s.empty()); s.clear(); ASSERT_TRUE(s.empty()); } TEST(General, disconnectWithNoSlotClearsAll) { sigs::Signal<void()> s; s.connect([] {}); s.connect([] {}); s.disconnect(); ASSERT_TRUE(s.empty()); } TEST(General, blocked) { sigs::Signal<void()> s; ASSERT_FALSE(s.blocked()); s.setBlocked(true); ASSERT_TRUE(s.blocked()); } TEST(General, blockedPreviousValue) { sigs::Signal<void()> s; ASSERT_FALSE(s.setBlocked(true)); ASSERT_TRUE(s.setBlocked(true)); } TEST(General, blockedSlots) { int calls = 0; const auto slot = [&calls] { calls++; }; sigs::Signal<void()> s; s.connect(slot); s(); ASSERT_EQ(calls, 1); s.setBlocked(true); ASSERT_TRUE(s.blocked()); s(); ASSERT_EQ(calls, 1); s.setBlocked(false); ASSERT_FALSE(s.blocked()); s(); ASSERT_EQ(calls, 2); } TEST(General, blockedSignals) { int calls = 0; const auto slot = [&calls] { calls++; }; sigs::Signal<void()> s, s2; s2.connect(slot); s.connect(s2); s(); ASSERT_EQ(calls, 1); // Block outer signal. s.setBlocked(true); ASSERT_TRUE(s.blocked()); ASSERT_FALSE(s2.blocked()); s(); ASSERT_EQ(calls, 1); s.setBlocked(false); ASSERT_FALSE(s.blocked()); s(); ASSERT_EQ(calls, 2); // Block inner signal. s2.setBlocked(true); ASSERT_TRUE(s2.blocked()); ASSERT_FALSE(s.blocked()); s(); ASSERT_EQ(calls, 2); } TEST(General, copyConstructible) { sigs::Signal<void()> s; s.connect([] {}); s.connect([] {}); s.setBlocked(true); decltype(s) s2(s); ASSERT_EQ(s2.size(), 2); ASSERT_TRUE(s2.blocked()); } TEST(General, copyAssignable) { sigs::Signal<void()> s; s.connect([] {}); s.connect([] {}); s.setBlocked(true); decltype(s) s2; s2 = s; ASSERT_EQ(s2.size(), 2); ASSERT_TRUE(s2.blocked()); } TEST(General, dontMoveRvalues) { sigs::Signal<void(std::string)> s; std::string res; auto func = [&res](std::string str) { res += str; }; s.connect(func); s.connect(func); s.connect(func); s("test"); ASSERT_EQ("testtesttest", res); } TEST(General, dontMoveRvaluesReturnValue) { sigs::Signal<int(std::string)> s; std::string res; auto func = [&res](std::string str) -> int { res += str; return 1; }; s.connect(func); s.connect(func); s.connect(func); int sum = 0; s([&sum](int retVal) { sum += retVal; }, "test"); ASSERT_EQ("testtesttest", res); ASSERT_EQ(3, sum); } TEST(General, dontMoveRvaluesSubSignal) { std::string res; auto func = [&res](std::string str) { res += str; }; sigs::Signal<void(std::string)> s; s.connect(func); decltype(s) s2; s2.connect(func); s2.connect(s); s2.connect(func); s2("test"); ASSERT_EQ("testtesttest", res); } TEST(General, threadedInvocation) { int sum = 0; auto func = [&sum] { sum++; }; sigs::Signal<void()> s; s.connect(func); s.connect(func); int n = 3; std::thread t([&s, n] { for (int i = 0; i < n; ++i) { s(); } }); t.join(); ASSERT_EQ(n * 2, sum); } TEST(General, threadedDontMoveRvalues) { int sum = 0; std::string res; auto func = [&](std::string str) { sum++; res += str; }; sigs::Signal<void(std::string)> s; s.connect(func); s.connect(func); int n = 3; std::thread t([&s, n] { for (int i = 0; i < n; ++i) { s("x"); } }); t.join(); ASSERT_EQ(n * 2, sum); ASSERT_EQ(std::string(sum, 'x'), res); }
Improve code coverage
Improve code coverage
C++
mit
netromdk/sigs,netromdk/sigs,netromdk/sigs
f8f213da1502148e183182e6be03179ffcc9e182
YorozuyaGS/Trade.cpp
YorozuyaGS/Trade.cpp
#include "stdafx.h" #include <ATF/global.hpp> #include <ATF/$FE149BD64943A35FB471F74C3D3B2245.hpp> #include "Trade.h" #include "ItemCheckHelper.h" namespace GameServer { namespace Fixes { using namespace ATF; void CTrade::load() { auto& core = CATFCore::get_instance(); core.set_hook(&CPlayer::pc_DTradeOKRequest, &CTrade::pc_DTradeOKRequest); } void CTrade::unload() { auto& core = CATFCore::get_instance(); core.unset_hook(&CPlayer::pc_DTradeOKRequest); } void CTrade::loop() { } ModuleVersion_t CTrade::get_version() { return usVersion; } ModuleName_t CTrade::get_name() { static const ModuleName_t name = "fix_trade"; return name; } void CTrade::configure(const rapidjson::Value & nodeConfig) { UNREFERENCED_PARAMETER(nodeConfig); } void WINAPIV CTrade::pc_DTradeOKRequest( ATF::CPlayer* pObj, unsigned int* pdwKey, ATF::info::CPlayerpc_DTradeOKRequest1687_ptr next) { bool bCheckPassed = false; CPlayer* pDst = &global::g_Player[pObj->m_pmTrd.wDTradeDstIndex]; auto fnCheckExchange = [](CPlayer* pPlayer) -> bool { bool result = true; for (int i = 0; i < pPlayer->m_pmTrd.bySellItemNum; ++i) { if (pPlayer->m_pmTrd.DItemNode[i].byStorageCode >= STORAGE_POS::STORAGE_NUM) { result = false; break; } auto pStoragePtr = pPlayer->m_Param.m_pStoragePtr[pPlayer->m_pmTrd.DItemNode[i].byStorageCode]; auto pItem = pStoragePtr->GetPtrFromSerial(pPlayer->m_pmTrd.DItemNode[i].dwSerial); if (!ItemCheckHelper::IsExchangable(pItem)) { result = false; break; } } return result; }; do { if (!pObj->m_pmTrd.bDTradeMode || !pObj->m_pmTrd.bDTradeLock) { bCheckPassed = true; break; } if (!pDst->m_pmTrd.bDTradeMode || !pDst->m_pmTrd.bDTradeOK || !pDst->m_pmTrd.bDTradeLock) { bCheckPassed = true; break; } if (pObj->m_pmTrd.bySellItemNum > pDst->m_Param.m_dbInven.GetNumEmptyCon()) break; if (pDst->m_pmTrd.bySellItemNum > pObj->m_Param.m_dbInven.GetNumEmptyCon()) break; if (pObj->m_pmTrd.dwDTrade_Dalant > pObj->m_Param.GetDalant() || pDst->m_pmTrd.dwDTrade_Dalant > pDst->m_Param.GetDalant()) break; if (pObj->m_pmTrd.dwDTrade_Gold > pObj->m_Param.GetGold() || pDst->m_pmTrd.dwDTrade_Gold > pDst->m_Param.GetGold()) break; if (fnCheckExchange(pObj)) break; if (fnCheckExchange(pDst)) break; bCheckPassed = true; } while (false); if (bCheckPassed) next(pObj, pdwKey); } } }
#include "stdafx.h" #include <ATF/global.hpp> #include <ATF/$FE149BD64943A35FB471F74C3D3B2245.hpp> #include "Trade.h" #include "ItemCheckHelper.h" namespace GameServer { namespace Fixes { using namespace ATF; void CTrade::load() { auto& core = CATFCore::get_instance(); core.set_hook(&CPlayer::pc_DTradeOKRequest, &CTrade::pc_DTradeOKRequest); } void CTrade::unload() { auto& core = CATFCore::get_instance(); core.unset_hook(&CPlayer::pc_DTradeOKRequest); } void CTrade::loop() { } ModuleVersion_t CTrade::get_version() { return usVersion; } ModuleName_t CTrade::get_name() { static const ModuleName_t name = "fix_trade"; return name; } void CTrade::configure(const rapidjson::Value & nodeConfig) { UNREFERENCED_PARAMETER(nodeConfig); } void WINAPIV CTrade::pc_DTradeOKRequest( ATF::CPlayer* pObj, unsigned int* pdwKey, ATF::info::CPlayerpc_DTradeOKRequest1687_ptr next) { bool bCheckPassed = false; CPlayer* pDst = nullptr; auto fnCheckExchange = [](CPlayer* pPlayer) -> bool { bool result = true; for (int i = 0; i < pPlayer->m_pmTrd.bySellItemNum; ++i) { if (pPlayer->m_pmTrd.DItemNode[i].byStorageCode >= STORAGE_POS::STORAGE_NUM) { result = false; break; } auto pStoragePtr = pPlayer->m_Param.m_pStoragePtr[pPlayer->m_pmTrd.DItemNode[i].byStorageCode]; auto pItem = pStoragePtr->GetPtrFromSerial(pPlayer->m_pmTrd.DItemNode[i].dwSerial); if (!ItemCheckHelper::IsExchangable(pItem)) { result = false; break; } } return result; }; do { if (!ATF::global::DTradeEqualPerson(pObj, &pDst)) { bCheckPassed = true; break; } if (!pObj->m_pmTrd.bDTradeMode || !pObj->m_pmTrd.bDTradeLock) { bCheckPassed = true; break; } if (!pDst->m_pmTrd.bDTradeMode || !pDst->m_pmTrd.bDTradeOK || !pDst->m_pmTrd.bDTradeLock) { bCheckPassed = true; break; } if (pObj->m_pmTrd.bySellItemNum > pDst->m_Param.m_dbInven.GetNumEmptyCon()) break; if (pDst->m_pmTrd.bySellItemNum > pObj->m_Param.m_dbInven.GetNumEmptyCon()) break; if (pObj->m_pmTrd.dwDTrade_Dalant > pObj->m_Param.GetDalant() || pDst->m_pmTrd.dwDTrade_Dalant > pDst->m_Param.GetDalant()) break; if (pObj->m_pmTrd.dwDTrade_Gold > pObj->m_Param.GetGold() || pDst->m_pmTrd.dwDTrade_Gold > pDst->m_Param.GetGold()) break; if (fnCheckExchange(pObj)) break; if (fnCheckExchange(pDst)) break; bCheckPassed = true; } while (false); if (bCheckPassed) next(pObj, pdwKey); else { pObj->m_pmTrd.Init(); pObj->SendMsg_DTradeCloseInform(0); if (pDst) { pDst->m_pmTrd.Init(); pDst->SendMsg_DTradeCloseInform(0); } } } } }
Update fix trade
Update fix trade
C++
mit
goodwinxp/Yorozuya,goodwinxp/Yorozuya
471ebcaf50add6feb2492016680d680019590905
base/src/TVirtualFFT.cxx
base/src/TVirtualFFT.cxx
// @(#)root/base:$Id$ // Author: Anna Kreshuk 10/04/2006 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // TVirtualFFT // // TVirtualFFT is an interface class for Fast Fourier Transforms. // // // // The default FFT library is FFTW. To use it, FFTW3 library should already // be installed, and ROOT should be have fftw3 module enabled, with the directories // of fftw3 include file and library specified (see installation instructions). // Function SetDefaultFFT() allows to change the default library. // // Available transform types: // FFT: // - "C2CFORWARD" - a complex input/output discrete Fourier transform (DFT) // in one or more dimensions, -1 in the exponent // - "C2CBACKWARD"- a complex input/output discrete Fourier transform (DFT) // in one or more dimensions, +1 in the exponent // - "R2C" - a real-input/complex-output discrete Fourier transform (DFT) // in one or more dimensions, // - "C2R" - inverse transforms to "R2C", taking complex input // (storing the non-redundant half of a logically Hermitian array) // to real output // - "R2HC" - a real-input DFT with output in ¡Èhalfcomplex¡É format, // i.e. real and imaginary parts for a transform of size n stored as // r0, r1, r2, ..., rn/2, i(n+1)/2-1, ..., i2, i1 // - "HC2R" - computes the reverse of FFTW_R2HC, above // - "DHT" - computes a discrete Hartley transform // // Sine/cosine transforms: // Different types of transforms are specified by parameter kind of the SineCosine() static // function. 4 different kinds of sine and cosine transforms are available // DCT-I (REDFT00 in FFTW3 notation)- kind=0 // DCT-II (REDFT10 in FFTW3 notation)- kind=1 // DCT-III(REDFT01 in FFTW3 notation)- kind=2 // DCT-IV (REDFT11 in FFTW3 notation)- kind=3 // DST-I (RODFT00 in FFTW3 notation)- kind=4 // DST-II (RODFT10 in FFTW3 notation)- kind=5 // DST-III(RODFT01 in FFTW3 notation)- kind=6 // DST-IV (RODFT11 in FFTW3 notation)- kind=7 // Formulas and detailed descriptions can be found in the chapter // "What FFTW really computes" of the FFTW manual // // NOTE: FFTW computes unnormalized transforms, so doing a transform, followed by its // inverse will give the original array, multiplied by normalization constant // (transform size(N) for FFT, 2*(N-1) for DCT-I, 2*(N+1) for DST-I, 2*N for // other sine/cosine transforms) // // How to use it: // Call to the static function FFT returns a pointer to a fast fourier transform // with requested parameters. Call to the static function SineCosine returns a // pointer to a sine or cosine transform with requested parameters. Example: // { // Int_t N = 10; Double_t *in = new Double_t[N]; // TVirtualFFT *fftr2c = TVirtualFFT::FFT(1, &N, "R2C"); // fftr2c->SetPoints(in); // fftr2c->Transform(); // Double_t re, im; // for (Int_t i=0; i<N; i++) // fftr2c->GetPointComplex(i, re, im); // ... // fftr2c->SetPoints(in2); // ... // fftr2c->SetPoints(in3); // ... // } // Different options are explained in the function comments // // // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TVirtualFFT.h" #include "TPluginManager.h" #include "TEnv.h" TVirtualFFT *TVirtualFFT::fgFFT = 0; TString TVirtualFFT::fgDefault = ""; ClassImp(TVirtualFFT) //_____________________________________________________________________________ TVirtualFFT::~TVirtualFFT() { //destructor if (this==fgFFT) fgFFT = 0; } //_____________________________________________________________________________ TVirtualFFT* TVirtualFFT::FFT(Int_t ndim, Int_t *n, Option_t *option) { //Returns a pointer to the FFT of requested size and type. //Parameters: // -ndim : number of transform dimensions // -n : sizes of each dimension (an array at least ndim long) // -option : consists of 3 parts - flag option and an option to create a new TVirtualFFT // 1) transform type option: // Available transform types are: // C2CForward, C2CBackward, C2R, R2C, R2HC, HC2R, DHT // see class description for details // 2) flag option: choosing how much time should be spent in planning the transform: // Possible options: // "ES" (from "estimate") - no time in preparing the transform, // but probably sub-optimal performance // "M" (from "measure") - some time spend in finding the optimal way // to do the transform // "P" (from "patient") - more time spend in finding the optimal way // to do the transform // "EX" (from "exhaustive") - the most optimal way is found // This option should be chosen depending on how many transforms of the // same size and type are going to be done. // Planning is only done once, for the first transform of this size and type. // 3) option allowing to choose between the global fgFFT and a new TVirtualFFT object // "" - default, changes and returns the global fgFFT variable // "K" (from "keep")- without touching the global fgFFT, // creates and returns a new TVirtualFFT*. User is then responsible for deleting it. // Examples of valid options: "R2C ES K", "C2CF M", "DHT P K", etc. Int_t inputtype=0, currenttype=0; TString opt = option; opt.ToUpper(); //find the tranform flag Option_t *flag; flag = "ES"; if (opt.Contains("ES")) flag = "ES"; if (opt.Contains("M")) flag = "M"; if (opt.Contains("P")) flag = "P"; if (opt.Contains("EX")) flag = "EX"; Int_t ndiff = 0; if (!opt.Contains("K")) { if (fgFFT){ //if the global transform exists, check if it should be changed if (fgFFT->GetNdim()!=ndim) ndiff++; else { Int_t *ncurrent = fgFFT->GetN(); for (Int_t i=0; i<ndim; i++){ if (n[i]!=ncurrent[i]) ndiff++; } } Option_t *t = fgFFT->GetType(); if (!opt.Contains(t)) { if (opt.Contains("HC") || opt.Contains("DHT")) inputtype = 1; if (strcmp(t,"R2HC")==0 || strcmp(t,"HC2R")==0 || strcmp(t,"DHT")==0) currenttype=1; if (!(inputtype==1 && currenttype==1)) ndiff++; } if (ndiff>0){ delete fgFFT; fgFFT = 0; } } } Int_t sign = 0; if (opt.Contains("C2CB") || opt.Contains("C2R")) sign = 1; if (opt.Contains("C2CF") || opt.Contains("R2C")) sign = -1; TVirtualFFT *fft = 0; if (opt.Contains("K") || !fgFFT) { TPluginHandler *h; TString pluginname; if (fgDefault.Length()==0) fgDefault="fftw"; if (strcmp(fgDefault.Data(),"fftw")==0) { if (opt.Contains("C2C")) pluginname = "fftwc2c"; if (opt.Contains("C2R")) pluginname = "fftwc2r"; if (opt.Contains("R2C")) pluginname = "fftwr2c"; if (opt.Contains("HC") || opt.Contains("DHT")) pluginname = "fftwr2r"; if ((h=gROOT->GetPluginManager()->FindHandler("TVirtualFFT", pluginname))) { if (h->LoadPlugin()==-1) { printf("handler not found\n"); return 0; } fft = (TVirtualFFT*)h->ExecPlugin(3, ndim, n, kFALSE); Int_t *kind = new Int_t[1]; if (pluginname=="fftwr2r") { if (opt.Contains("R2HC")) kind[0] = 10; if (opt.Contains("HC2R")) kind[0] = 11; if (opt.Contains("DHT")) kind[0] = 12; } fft->Init(flag, sign, kind); if (!opt.Contains("K")) { fgFFT = fft; } delete [] kind; return fft; } else { printf("plugin not found\n"); return 0; } } } else { //if the global transform already exists and just needs to be reinitialised //with different parameters if (fgFFT->GetSign()!=sign || !opt.Contains(fgFFT->GetTransformFlag()) || !opt.Contains(fgFFT->GetType())) { Int_t *kind = new Int_t[1]; if (inputtype==1) { if (opt.Contains("R2HC")) kind[0] = 10; if (opt.Contains("HC2R")) kind[0] = 11; if (opt.Contains("DHT")) kind[0] = 12; } fgFFT->Init(flag, sign, kind); delete [] kind; } } return fgFFT; } //_____________________________________________________________________________ TVirtualFFT* TVirtualFFT::SineCosine(Int_t ndim, Int_t *n, Int_t *r2rkind, Option_t *option) { //Returns a pointer to a sine or cosine transform of requested size and kind // //Parameters: // -ndim : number of transform dimensions // -n : sizes of each dimension (an array at least ndim long) // -r2rkind : transform kind for each dimension // 4 different kinds of sine and cosine transforms are available // DCT-I - kind=0 // DCT-II - kind=1 // DCT-III - kind=2 // DCT-IV - kind=3 // DST-I - kind=4 // DST-II - kind=5 // DST-III - kind=6 // DST-IV - kind=7 // -option : consists of 2 parts - flag option and an option to create a new TVirtualFFT // - flag option: choosing how much time should be spent in planning the transform: // Possible options: // "ES" (from "estimate") - no time in preparing the transform, // but probably sub-optimal performance // "M" (from "measure") - some time spend in finding the optimal way // to do the transform // "P" (from "patient") - more time spend in finding the optimal way // to do the transform // "EX" (from "exhaustive") - the most optimal way is found // This option should be chosen depending on how many transforms of the // same size and type are going to be done. // Planning is only done once, for the first transform of this size and type. // - option allowing to choose between the global fgFFT and a new TVirtualFFT object // "" - default, changes and returns the global fgFFT variable // "K" (from "keep")- without touching the global fgFFT, // creates and returns a new TVirtualFFT*. User is then responsible for deleting it. // Examples of valid options: "ES K", "EX", etc TString opt = option; //find the tranform flag Option_t *flag; flag = "ES"; if (opt.Contains("ES")) flag = "ES"; if (opt.Contains("M")) flag = "M"; if (opt.Contains("P")) flag = "P"; if (opt.Contains("EX")) flag = "EX"; if (!opt.Contains("K")) { if (fgFFT){ Int_t ndiff = 0; if (fgFFT->GetNdim()!=ndim || strcmp(fgFFT->GetType(),"R2R")!=0) ndiff++; else { Int_t *ncurrent = fgFFT->GetN(); for (Int_t i=0; i<ndim; i++) { if (n[i] != ncurrent[i]) ndiff++; } } if (ndiff>0) { delete fgFFT; fgFFT = 0; } } } TVirtualFFT *fft = 0; if (!fgFFT || opt.Contains("K")) { TPluginHandler *h; TString pluginname; if (fgDefault.Length()==0) fgDefault="fftw"; if (strcmp(fgDefault.Data(),"fftw")==0) { pluginname = "fftwr2r"; if ((h=gROOT->GetPluginManager()->FindHandler("TVirtualFFT", pluginname))) { if (h->LoadPlugin()==-1){ printf("handler not found\n"); return 0; } fft = (TVirtualFFT*)h->ExecPlugin(3, ndim, n, kFALSE); fft->Init(flag, 0, r2rkind); if (!opt.Contains("K")) fgFFT = fft; return fft; } else { printf("handler not found\n"); return 0; } } } //if (fgFFT->GetTransformFlag()!=flag) fgFFT->Init(flag,0, r2rkind); return fgFFT; } //_____________________________________________________________________________ TVirtualFFT* TVirtualFFT::GetCurrentTransform() { // static: return current fgFFT if (fgFFT) return fgFFT; else{ printf("fgFFT is not defined yet\n"); return 0; } } //_____________________________________________________________________________ void TVirtualFFT::SetTransform(TVirtualFFT* fft) { // static: set the current transfrom to parameter fgFFT = fft; } //_____________________________________________________________________________ const char *TVirtualFFT::GetDefaultFFT() { // static: return the name of the default fft return fgDefault.Data(); } //______________________________________________________________________________ void TVirtualFFT::SetDefaultFFT(const char *name) { // static: set name of default fft if (fgDefault == name) return; delete fgFFT; fgFFT = 0; fgDefault = name; }
// @(#)root/base:$Id$ // Author: Anna Kreshuk 10/04/2006 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // TVirtualFFT // // TVirtualFFT is an interface class for Fast Fourier Transforms. // // // // The default FFT library is FFTW. To use it, FFTW3 library should already // be installed, and ROOT should be have fftw3 module enabled, with the directories // of fftw3 include file and library specified (see installation instructions). // Function SetDefaultFFT() allows to change the default library. // // Available transform types: // FFT: // - "C2CFORWARD" - a complex input/output discrete Fourier transform (DFT) // in one or more dimensions, -1 in the exponent // - "C2CBACKWARD"- a complex input/output discrete Fourier transform (DFT) // in one or more dimensions, +1 in the exponent // - "R2C" - a real-input/complex-output discrete Fourier transform (DFT) // in one or more dimensions, // - "C2R" - inverse transforms to "R2C", taking complex input // (storing the non-redundant half of a logically Hermitian array) // to real output // - "R2HC" - a real-input DFT with output in ¡Èhalfcomplex¡É format, // i.e. real and imaginary parts for a transform of size n stored as // r0, r1, r2, ..., rn/2, i(n+1)/2-1, ..., i2, i1 // - "HC2R" - computes the reverse of FFTW_R2HC, above // - "DHT" - computes a discrete Hartley transform // // Sine/cosine transforms: // Different types of transforms are specified by parameter kind of the SineCosine() static // function. 4 different kinds of sine and cosine transforms are available // DCT-I (REDFT00 in FFTW3 notation)- kind=0 // DCT-II (REDFT10 in FFTW3 notation)- kind=1 // DCT-III(REDFT01 in FFTW3 notation)- kind=2 // DCT-IV (REDFT11 in FFTW3 notation)- kind=3 // DST-I (RODFT00 in FFTW3 notation)- kind=4 // DST-II (RODFT10 in FFTW3 notation)- kind=5 // DST-III(RODFT01 in FFTW3 notation)- kind=6 // DST-IV (RODFT11 in FFTW3 notation)- kind=7 // Formulas and detailed descriptions can be found in the chapter // "What FFTW really computes" of the FFTW manual // // NOTE: FFTW computes unnormalized transforms, so doing a transform, followed by its // inverse will give the original array, multiplied by normalization constant // (transform size(N) for FFT, 2*(N-1) for DCT-I, 2*(N+1) for DST-I, 2*N for // other sine/cosine transforms) // // How to use it: // Call to the static function FFT returns a pointer to a fast fourier transform // with requested parameters. Call to the static function SineCosine returns a // pointer to a sine or cosine transform with requested parameters. Example: // { // Int_t N = 10; Double_t *in = new Double_t[N]; // TVirtualFFT *fftr2c = TVirtualFFT::FFT(1, &N, "R2C"); // fftr2c->SetPoints(in); // fftr2c->Transform(); // Double_t re, im; // for (Int_t i=0; i<N; i++) // fftr2c->GetPointComplex(i, re, im); // ... // fftr2c->SetPoints(in2); // ... // fftr2c->SetPoints(in3); // ... // } // Different options are explained in the function comments // // // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TVirtualFFT.h" #include "TPluginManager.h" #include "TEnv.h" TVirtualFFT *TVirtualFFT::fgFFT = 0; TString TVirtualFFT::fgDefault = ""; ClassImp(TVirtualFFT) //_____________________________________________________________________________ TVirtualFFT::~TVirtualFFT() { //destructor if (this==fgFFT) fgFFT = 0; } //_____________________________________________________________________________ TVirtualFFT* TVirtualFFT::FFT(Int_t ndim, Int_t *n, Option_t *option) { //Returns a pointer to the FFT of requested size and type. //Parameters: // -ndim : number of transform dimensions // -n : sizes of each dimension (an array at least ndim long) // -option : consists of 3 parts - flag option and an option to create a new TVirtualFFT // 1) transform type option: // Available transform types are: // C2CForward, C2CBackward, C2R, R2C, R2HC, HC2R, DHT // see class description for details // 2) flag option: choosing how much time should be spent in planning the transform: // Possible options: // "ES" (from "estimate") - no time in preparing the transform, // but probably sub-optimal performance // "M" (from "measure") - some time spend in finding the optimal way // to do the transform // "P" (from "patient") - more time spend in finding the optimal way // to do the transform // "EX" (from "exhaustive") - the most optimal way is found // This option should be chosen depending on how many transforms of the // same size and type are going to be done. // Planning is only done once, for the first transform of this size and type. // 3) option allowing to choose between the global fgFFT and a new TVirtualFFT object // "" - default, changes and returns the global fgFFT variable // "K" (from "keep")- without touching the global fgFFT, // creates and returns a new TVirtualFFT*. User is then responsible for deleting it. // Examples of valid options: "R2C ES K", "C2CF M", "DHT P K", etc. Int_t inputtype=0, currenttype=0; TString opt = option; opt.ToUpper(); //find the tranform flag Option_t *flag; flag = "ES"; if (opt.Contains("ES")) flag = "ES"; if (opt.Contains("M")) flag = "M"; if (opt.Contains("P")) flag = "P"; if (opt.Contains("EX")) flag = "EX"; Int_t ndiff = 0; if (!opt.Contains("K")) { if (fgFFT){ //if the global transform exists, check if it should be changed if (fgFFT->GetNdim()!=ndim) ndiff++; else { Int_t *ncurrent = fgFFT->GetN(); for (Int_t i=0; i<ndim; i++){ if (n[i]!=ncurrent[i]) ndiff++; } } Option_t *t = fgFFT->GetType(); if (!opt.Contains(t)) { if (opt.Contains("HC") || opt.Contains("DHT")) inputtype = 1; if (strcmp(t,"R2HC")==0 || strcmp(t,"HC2R")==0 || strcmp(t,"DHT")==0) currenttype=1; if (!(inputtype==1 && currenttype==1)) ndiff++; } if (ndiff>0){ delete fgFFT; fgFFT = 0; } } } Int_t sign = 0; if (opt.Contains("C2CB") || opt.Contains("C2R")) sign = 1; if (opt.Contains("C2CF") || opt.Contains("R2C")) sign = -1; TVirtualFFT *fft = 0; if (opt.Contains("K") || !fgFFT) { TPluginHandler *h; TString pluginname; if (fgDefault.Length()==0) fgDefault="fftw"; if (strcmp(fgDefault.Data(),"fftw")==0) { if (opt.Contains("C2C")) pluginname = "fftwc2c"; if (opt.Contains("C2R")) pluginname = "fftwc2r"; if (opt.Contains("R2C")) pluginname = "fftwr2c"; if (opt.Contains("HC") || opt.Contains("DHT")) pluginname = "fftwr2r"; if ((h=gROOT->GetPluginManager()->FindHandler("TVirtualFFT", pluginname))) { if (h->LoadPlugin()==-1) { printf("handler not found\n"); return 0; } fft = (TVirtualFFT*)h->ExecPlugin(3, ndim, n, kFALSE); Int_t *kind = new Int_t[1]; if (pluginname=="fftwr2r") { if (opt.Contains("R2HC")) kind[0] = 10; if (opt.Contains("HC2R")) kind[0] = 11; if (opt.Contains("DHT")) kind[0] = 12; } if (fft) fft->Init(flag, sign, kind); if (!opt.Contains("K")) { fgFFT = fft; } delete [] kind; return fft; } else { printf("plugin not found\n"); return 0; } } } else { //if the global transform already exists and just needs to be reinitialised //with different parameters if (fgFFT->GetSign()!=sign || !opt.Contains(fgFFT->GetTransformFlag()) || !opt.Contains(fgFFT->GetType())) { Int_t *kind = new Int_t[1]; if (inputtype==1) { if (opt.Contains("R2HC")) kind[0] = 10; if (opt.Contains("HC2R")) kind[0] = 11; if (opt.Contains("DHT")) kind[0] = 12; } fgFFT->Init(flag, sign, kind); delete [] kind; } } return fgFFT; } //_____________________________________________________________________________ TVirtualFFT* TVirtualFFT::SineCosine(Int_t ndim, Int_t *n, Int_t *r2rkind, Option_t *option) { //Returns a pointer to a sine or cosine transform of requested size and kind // //Parameters: // -ndim : number of transform dimensions // -n : sizes of each dimension (an array at least ndim long) // -r2rkind : transform kind for each dimension // 4 different kinds of sine and cosine transforms are available // DCT-I - kind=0 // DCT-II - kind=1 // DCT-III - kind=2 // DCT-IV - kind=3 // DST-I - kind=4 // DST-II - kind=5 // DST-III - kind=6 // DST-IV - kind=7 // -option : consists of 2 parts - flag option and an option to create a new TVirtualFFT // - flag option: choosing how much time should be spent in planning the transform: // Possible options: // "ES" (from "estimate") - no time in preparing the transform, // but probably sub-optimal performance // "M" (from "measure") - some time spend in finding the optimal way // to do the transform // "P" (from "patient") - more time spend in finding the optimal way // to do the transform // "EX" (from "exhaustive") - the most optimal way is found // This option should be chosen depending on how many transforms of the // same size and type are going to be done. // Planning is only done once, for the first transform of this size and type. // - option allowing to choose between the global fgFFT and a new TVirtualFFT object // "" - default, changes and returns the global fgFFT variable // "K" (from "keep")- without touching the global fgFFT, // creates and returns a new TVirtualFFT*. User is then responsible for deleting it. // Examples of valid options: "ES K", "EX", etc TString opt = option; //find the tranform flag Option_t *flag; flag = "ES"; if (opt.Contains("ES")) flag = "ES"; if (opt.Contains("M")) flag = "M"; if (opt.Contains("P")) flag = "P"; if (opt.Contains("EX")) flag = "EX"; if (!opt.Contains("K")) { if (fgFFT){ Int_t ndiff = 0; if (fgFFT->GetNdim()!=ndim || strcmp(fgFFT->GetType(),"R2R")!=0) ndiff++; else { Int_t *ncurrent = fgFFT->GetN(); for (Int_t i=0; i<ndim; i++) { if (n[i] != ncurrent[i]) ndiff++; } } if (ndiff>0) { delete fgFFT; fgFFT = 0; } } } TVirtualFFT *fft = 0; if (!fgFFT || opt.Contains("K")) { TPluginHandler *h; TString pluginname; if (fgDefault.Length()==0) fgDefault="fftw"; if (strcmp(fgDefault.Data(),"fftw")==0) { pluginname = "fftwr2r"; if ((h=gROOT->GetPluginManager()->FindHandler("TVirtualFFT", pluginname))) { if (h->LoadPlugin()==-1){ printf("handler not found\n"); return 0; } fft = (TVirtualFFT*)h->ExecPlugin(3, ndim, n, kFALSE); fft->Init(flag, 0, r2rkind); if (!opt.Contains("K")) fgFFT = fft; return fft; } else { printf("handler not found\n"); return 0; } } } //if (fgFFT->GetTransformFlag()!=flag) fgFFT->Init(flag,0, r2rkind); return fgFFT; } //_____________________________________________________________________________ TVirtualFFT* TVirtualFFT::GetCurrentTransform() { // static: return current fgFFT if (fgFFT) return fgFFT; else{ printf("fgFFT is not defined yet\n"); return 0; } } //_____________________________________________________________________________ void TVirtualFFT::SetTransform(TVirtualFFT* fft) { // static: set the current transfrom to parameter fgFFT = fft; } //_____________________________________________________________________________ const char *TVirtualFFT::GetDefaultFFT() { // static: return the name of the default fft return fgDefault.Data(); } //______________________________________________________________________________ void TVirtualFFT::SetDefaultFFT(const char *name) { // static: set name of default fft if (fgDefault == name) return; delete fgFFT; fgFFT = 0; fgDefault = name; }
Add a protection in case the FFT plugin is not found
Add a protection in case the FFT plugin is not found git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@22936 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
Y--/root,davidlt/root,sawenzel/root,Duraznos/root,omazapa/root-old,davidlt/root,zzxuanyuan/root-compressor-dummy,olifre/root,perovic/root,zzxuanyuan/root,strykejern/TTreeReader,pspe/root,arch1tect0r/root,arch1tect0r/root,zzxuanyuan/root-compressor-dummy,satyarth934/root,CristinaCristescu/root,dfunke/root,sirinath/root,mattkretz/root,esakellari/root,dfunke/root,mkret2/root,evgeny-boger/root,esakellari/my_root_for_test,lgiommi/root,karies/root,arch1tect0r/root,CristinaCristescu/root,mattkretz/root,sbinet/cxx-root,alexschlueter/cern-root,krafczyk/root,smarinac/root,mkret2/root,mkret2/root,buuck/root,mhuwiler/rootauto,veprbl/root,nilqed/root,sawenzel/root,gbitzes/root,Dr15Jones/root,sbinet/cxx-root,zzxuanyuan/root-compressor-dummy,veprbl/root,strykejern/TTreeReader,gganis/root,smarinac/root,agarciamontoro/root,omazapa/root-old,sawenzel/root,Y--/root,CristinaCristescu/root,gganis/root,mkret2/root,ffurano/root5,olifre/root,pspe/root,cxx-hep/root-cern,georgtroska/root,bbockelm/root,esakellari/root,mhuwiler/rootauto,BerserkerTroll/root,mkret2/root,zzxuanyuan/root,buuck/root,karies/root,zzxuanyuan/root,gbitzes/root,karies/root,zzxuanyuan/root-compressor-dummy,strykejern/TTreeReader,pspe/root,olifre/root,vukasinmilosevic/root,mattkretz/root,agarciamontoro/root,root-mirror/root,abhinavmoudgil95/root,esakellari/root,sirinath/root,root-mirror/root,krafczyk/root,thomaskeck/root,gganis/root,perovic/root,ffurano/root5,cxx-hep/root-cern,davidlt/root,olifre/root,pspe/root,root-mirror/root,sirinath/root,thomaskeck/root,BerserkerTroll/root,sirinath/root,BerserkerTroll/root,simonpf/root,gbitzes/root,karies/root,lgiommi/root,olifre/root,bbockelm/root,dfunke/root,mhuwiler/rootauto,sbinet/cxx-root,Y--/root,ffurano/root5,omazapa/root,perovic/root,0x0all/ROOT,bbockelm/root,strykejern/TTreeReader,pspe/root,tc3t/qoot,0x0all/ROOT,gbitzes/root,root-mirror/root,sirinath/root,zzxuanyuan/root-compressor-dummy,cxx-hep/root-cern,0x0all/ROOT,tc3t/qoot,omazapa/root-old,simonpf/root,Y--/root,zzxuanyuan/root,veprbl/root,veprbl/root,krafczyk/root,thomaskeck/root,tc3t/qoot,Duraznos/root,CristinaCristescu/root,beniz/root,zzxuanyuan/root,omazapa/root,Duraznos/root,dfunke/root,zzxuanyuan/root,satyarth934/root,Duraznos/root,zzxuanyuan/root,gbitzes/root,omazapa/root-old,abhinavmoudgil95/root,ffurano/root5,satyarth934/root,buuck/root,satyarth934/root,alexschlueter/cern-root,bbockelm/root,perovic/root,mattkretz/root,abhinavmoudgil95/root,esakellari/root,pspe/root,Duraznos/root,smarinac/root,Y--/root,veprbl/root,Y--/root,smarinac/root,georgtroska/root,smarinac/root,sawenzel/root,sbinet/cxx-root,alexschlueter/cern-root,Y--/root,BerserkerTroll/root,tc3t/qoot,0x0all/ROOT,mkret2/root,Dr15Jones/root,buuck/root,simonpf/root,satyarth934/root,omazapa/root-old,agarciamontoro/root,krafczyk/root,thomaskeck/root,strykejern/TTreeReader,nilqed/root,vukasinmilosevic/root,sirinath/root,CristinaCristescu/root,sawenzel/root,CristinaCristescu/root,karies/root,evgeny-boger/root,evgeny-boger/root,jrtomps/root,agarciamontoro/root,evgeny-boger/root,pspe/root,gbitzes/root,arch1tect0r/root,jrtomps/root,mkret2/root,perovic/root,veprbl/root,0x0all/ROOT,kirbyherm/root-r-tools,esakellari/my_root_for_test,jrtomps/root,nilqed/root,gbitzes/root,davidlt/root,arch1tect0r/root,tc3t/qoot,lgiommi/root,omazapa/root-old,beniz/root,veprbl/root,root-mirror/root,buuck/root,kirbyherm/root-r-tools,krafczyk/root,vukasinmilosevic/root,omazapa/root,agarciamontoro/root,lgiommi/root,esakellari/my_root_for_test,root-mirror/root,0x0all/ROOT,sirinath/root,lgiommi/root,gganis/root,root-mirror/root,BerserkerTroll/root,perovic/root,sbinet/cxx-root,mkret2/root,arch1tect0r/root,Duraznos/root,agarciamontoro/root,satyarth934/root,sbinet/cxx-root,simonpf/root,alexschlueter/cern-root,abhinavmoudgil95/root,davidlt/root,karies/root,arch1tect0r/root,omazapa/root,esakellari/my_root_for_test,zzxuanyuan/root,satyarth934/root,simonpf/root,buuck/root,pspe/root,sbinet/cxx-root,bbockelm/root,buuck/root,abhinavmoudgil95/root,sawenzel/root,gganis/root,karies/root,strykejern/TTreeReader,kirbyherm/root-r-tools,Dr15Jones/root,zzxuanyuan/root-compressor-dummy,mhuwiler/rootauto,simonpf/root,perovic/root,agarciamontoro/root,olifre/root,zzxuanyuan/root-compressor-dummy,mattkretz/root,lgiommi/root,mkret2/root,omazapa/root-old,root-mirror/root,zzxuanyuan/root,CristinaCristescu/root,lgiommi/root,root-mirror/root,alexschlueter/cern-root,pspe/root,thomaskeck/root,arch1tect0r/root,vukasinmilosevic/root,0x0all/ROOT,arch1tect0r/root,esakellari/root,esakellari/my_root_for_test,esakellari/my_root_for_test,zzxuanyuan/root-compressor-dummy,Duraznos/root,lgiommi/root,satyarth934/root,agarciamontoro/root,Y--/root,satyarth934/root,cxx-hep/root-cern,agarciamontoro/root,tc3t/qoot,davidlt/root,nilqed/root,arch1tect0r/root,sirinath/root,bbockelm/root,mhuwiler/rootauto,dfunke/root,mkret2/root,omazapa/root-old,sirinath/root,beniz/root,0x0all/ROOT,sbinet/cxx-root,jrtomps/root,beniz/root,strykejern/TTreeReader,omazapa/root-old,root-mirror/root,smarinac/root,BerserkerTroll/root,sawenzel/root,root-mirror/root,perovic/root,sawenzel/root,alexschlueter/cern-root,Y--/root,davidlt/root,bbockelm/root,abhinavmoudgil95/root,kirbyherm/root-r-tools,davidlt/root,gganis/root,mhuwiler/rootauto,karies/root,esakellari/my_root_for_test,lgiommi/root,buuck/root,perovic/root,gganis/root,olifre/root,krafczyk/root,mattkretz/root,georgtroska/root,vukasinmilosevic/root,cxx-hep/root-cern,pspe/root,karies/root,kirbyherm/root-r-tools,esakellari/root,BerserkerTroll/root,simonpf/root,georgtroska/root,abhinavmoudgil95/root,evgeny-boger/root,BerserkerTroll/root,satyarth934/root,simonpf/root,thomaskeck/root,evgeny-boger/root,dfunke/root,karies/root,omazapa/root,gbitzes/root,olifre/root,mattkretz/root,krafczyk/root,smarinac/root,jrtomps/root,jrtomps/root,Dr15Jones/root,krafczyk/root,georgtroska/root,karies/root,buuck/root,gbitzes/root,mhuwiler/rootauto,ffurano/root5,agarciamontoro/root,CristinaCristescu/root,omazapa/root,alexschlueter/cern-root,kirbyherm/root-r-tools,omazapa/root,vukasinmilosevic/root,omazapa/root-old,jrtomps/root,pspe/root,evgeny-boger/root,evgeny-boger/root,CristinaCristescu/root,Duraznos/root,sbinet/cxx-root,smarinac/root,omazapa/root,omazapa/root,tc3t/qoot,zzxuanyuan/root,gganis/root,gganis/root,zzxuanyuan/root,jrtomps/root,davidlt/root,sbinet/cxx-root,lgiommi/root,nilqed/root,thomaskeck/root,gbitzes/root,thomaskeck/root,CristinaCristescu/root,bbockelm/root,georgtroska/root,agarciamontoro/root,olifre/root,esakellari/root,krafczyk/root,esakellari/root,vukasinmilosevic/root,mattkretz/root,mhuwiler/rootauto,dfunke/root,nilqed/root,cxx-hep/root-cern,sirinath/root,zzxuanyuan/root,lgiommi/root,mhuwiler/rootauto,beniz/root,tc3t/qoot,omazapa/root,georgtroska/root,thomaskeck/root,Duraznos/root,gbitzes/root,thomaskeck/root,veprbl/root,mhuwiler/rootauto,kirbyherm/root-r-tools,evgeny-boger/root,bbockelm/root,beniz/root,beniz/root,dfunke/root,vukasinmilosevic/root,simonpf/root,vukasinmilosevic/root,perovic/root,georgtroska/root,omazapa/root-old,gganis/root,sawenzel/root,esakellari/root,nilqed/root,smarinac/root,Y--/root,jrtomps/root,esakellari/root,olifre/root,tc3t/qoot,mattkretz/root,BerserkerTroll/root,nilqed/root,ffurano/root5,veprbl/root,Dr15Jones/root,beniz/root,mkret2/root,tc3t/qoot,Y--/root,olifre/root,CristinaCristescu/root,perovic/root,buuck/root,zzxuanyuan/root-compressor-dummy,davidlt/root,georgtroska/root,vukasinmilosevic/root,dfunke/root,nilqed/root,evgeny-boger/root,bbockelm/root,omazapa/root,esakellari/root,veprbl/root,cxx-hep/root-cern,Duraznos/root,sbinet/cxx-root,Dr15Jones/root,zzxuanyuan/root-compressor-dummy,abhinavmoudgil95/root,mattkretz/root,satyarth934/root,smarinac/root,krafczyk/root,esakellari/my_root_for_test,nilqed/root,nilqed/root,georgtroska/root,veprbl/root,esakellari/my_root_for_test,davidlt/root,0x0all/ROOT,esakellari/my_root_for_test,Duraznos/root,evgeny-boger/root,jrtomps/root,krafczyk/root,BerserkerTroll/root,sirinath/root,beniz/root,georgtroska/root,sawenzel/root,mhuwiler/rootauto,beniz/root,simonpf/root,sawenzel/root,bbockelm/root,arch1tect0r/root,BerserkerTroll/root,abhinavmoudgil95/root,ffurano/root5,abhinavmoudgil95/root,zzxuanyuan/root-compressor-dummy,gganis/root,buuck/root,jrtomps/root,abhinavmoudgil95/root,dfunke/root,simonpf/root,cxx-hep/root-cern,Dr15Jones/root,vukasinmilosevic/root,dfunke/root,mattkretz/root,beniz/root
aa05e8e661c52aef8ecaa241e63171148fa96d84
sdk/tools/ecppc/variable.cpp
sdk/tools/ecppc/variable.cpp
/* * Copyright (C) 2003 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * 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 "tnt/ecppc/variable.h" #include <sstream> #include <cctype> namespace tnt { namespace ecppc { Variable::Variable(const std::string& arg, const std::string& value_) { // 'name' might be prefixed by a type // the variablename is the last word in 'name' // type is the rest before the variablename // examples: // " int var " // " var" // " ns :: someclass param" std::ostringstream a; std::string::size_type e = arg.size(); while (e > 0 && std::isspace(arg.at(e - 1))) --e; // e points past the last character of our arg if (e > 1 && arg.at(e - 2) == '[' && arg.at(e-1) == ']') { isvector = true; e -= 2; while (e > 0 && std::isspace(arg.at(e - 1))) --e; } else isvector = false; std::string::size_type b = e; while (b > 0 && !std::isspace(arg.at(b - 1))) --b; // b points to the first character of our arg std::string::size_type t = b; while (t > 0 && std::isspace(arg.at(t - 1))) --t; // t points past the last character of the type name = std::string(arg.begin() + b, arg.begin() + e); type = std::string(arg.begin(), arg.begin() + t); value = value_; } void Variable::getParamCodeVector(std::ostream& o, const std::string& qparam) const { std::string ltype = type; if (ltype.empty()) ltype = "std::string"; o << "typedef std::vector<" << ltype << "> " << name << "_type;\n" << name << "_type " << name << " = qparam.argst(\"" << name << "\", \"" << ltype << "\");\n"; } void Variable::getParamCode(std::ostream& o, const std::string& qparam) const { if (isvector) getParamCodeVector(o, qparam); else if (!type.empty()) { // we have a type // print out type and name o << type << ' ' << name << " = "; if (value.empty()) { // no default-value o << qparam << ".argt<" << type << ">(\"" << name << "\", \"" << type << "\");\n"; } else { // with default-value o << qparam << ".arg<" << type << ">(\"" << name << "\", (" << value << "));\n"; } } else { // type defaults to std::string o << "std::string " << name << " = " << qparam << ".param(\"" << name << '"'; if (!value.empty()) o << ", (" << value << ')'; o << ");\n"; } } void Variable::getConfigInit(std::ostream& o) const { o << " config.config.getMember(\"" << name << "\", _component_::" << name << ");\n"; } void Variable::getConfigDecl(std::ostream& o) const { std::string t = type.empty() ? "std::string" : type; o << t << " _component_::" << name; if (!value.empty()) o << " = " << value; o << ";\n"; } void Variable::getConfigHDecl(std::ostream& o) const { std::string t = type.empty() ? "std::string" : type; o << " static " << t << " " << name << ";\n"; } } }
/* * Copyright (C) 2003 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * 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 "tnt/ecppc/variable.h" #include <sstream> #include <cctype> namespace tnt { namespace ecppc { Variable::Variable(const std::string& arg, const std::string& value_) { // 'name' might be prefixed by a type // the variablename is the last word in 'name' // type is the rest before the variablename // examples: // " int var " // " var" // " ns :: someclass param" std::ostringstream a; std::string::size_type e = arg.size(); while (e > 0 && std::isspace(arg.at(e - 1))) --e; // e points past the last character of our arg if (e > 1 && arg.at(e - 2) == '[' && arg.at(e-1) == ']') { isvector = true; e -= 2; while (e > 0 && std::isspace(arg.at(e - 1))) --e; } else isvector = false; std::string::size_type b = e; while (b > 0 && !std::isspace(arg.at(b - 1))) --b; // b points to the first character of our arg std::string::size_type t = b; while (t > 0 && std::isspace(arg.at(t - 1))) --t; // t points past the last character of the type name = std::string(arg.begin() + b, arg.begin() + e); type = std::string(arg.begin(), arg.begin() + t); value = value_; } void Variable::getParamCodeVector(std::ostream& o, const std::string& qparam) const { std::string ltype = type; if (ltype.empty()) ltype = "std::string"; o << "typedef std::vector<" << ltype << "> " << name << "_type;\n" << name << "_type " << name << " = qparam.argst<" << ltype << ">(\"" << name << "\", \"" << ltype << "\");\n"; } void Variable::getParamCode(std::ostream& o, const std::string& qparam) const { if (isvector) getParamCodeVector(o, qparam); else if (!type.empty()) { // we have a type // print out type and name o << type << ' ' << name << " = "; if (value.empty()) { // no default-value o << qparam << ".argt<" << type << ">(\"" << name << "\", \"" << type << "\");\n"; } else { // with default-value o << qparam << ".arg<" << type << ">(\"" << name << "\", (" << value << "));\n"; } } else { // type defaults to std::string o << "std::string " << name << " = " << qparam << ".param(\"" << name << '"'; if (!value.empty()) o << ", (" << value << ')'; o << ");\n"; } } void Variable::getConfigInit(std::ostream& o) const { o << " config.config.getMember(\"" << name << "\", _component_::" << name << ");\n"; } void Variable::getConfigDecl(std::ostream& o) const { std::string t = type.empty() ? "std::string" : type; o << t << " _component_::" << name; if (!value.empty()) o << " = " << value; o << ";\n"; } void Variable::getConfigHDecl(std::ostream& o) const { std::string t = type.empty() ? "std::string" : type; o << " static " << t << " " << name << ";\n"; } } }
fix fetching vector of query parameters
fix fetching vector of query parameters
C++
lgpl-2.1
OlafRadicke/tntnet,OlafRadicke/tntnet,maekitalo/tntnet,maekitalo/tntnet,OlafRadicke/tntnet,maekitalo/tntnet,OlafRadicke/tntnet,OlafRadicke/tntnet,maekitalo/tntnet,maekitalo/tntnet,maekitalo/tntnet
aa306af3d7c47de3c7937c98d3aa919eb8da6f34
src/library/compiler/preprocess.cpp
src/library/compiler/preprocess.cpp
/* Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "kernel/declaration.h" #include "kernel/type_checker.h" #include "kernel/replace_fn.h" #include "kernel/instantiate.h" #include "kernel/for_each_fn.h" #include "kernel/scope_pos_info_provider.h" #include "library/trace.h" #include "library/projection.h" #include "library/constants.h" #include "library/aux_recursors.h" #include "library/user_recursors.h" #include "library/util.h" #include "library/quote.h" #include "library/noncomputable.h" #include "library/context_cache.h" #include "library/module.h" #include "library/vm/vm.h" #include "library/compiler/util.h" #include "library/compiler/preprocess.h" #include "library/compiler/compiler_step_visitor.h" #include "library/compiler/comp_irrelevant.h" #include "library/compiler/nat_value.h" #include "library/compiler/eta_expansion.h" #include "library/compiler/inliner.h" #include "library/compiler/elim_recursors.h" #include "library/compiler/erase_irrelevant.h" #include "library/compiler/reduce_arity.h" #include "library/compiler/lambda_lifting.h" #include "library/compiler/simp_inductive.h" #include "library/compiler/elim_unused_lets.h" #include "library/compiler/extract_values.h" #include "library/compiler/cse.h" namespace lean { class expand_aux_fn : public compiler_step_visitor { enum class recursor_kind { Aux, CasesOn, NotRecursor }; /* We only expand auxiliary recursors and user-defined recursors. However, we don't unfold recursors of the form C.cases_on if C != eq. */ recursor_kind get_recursor_app_kind(expr const & e) const { if (!is_app(e)) return recursor_kind::NotRecursor; expr const & fn = get_app_fn(e); if (!is_constant(fn)) return recursor_kind::NotRecursor; name const & n = const_name(fn); if (is_cases_on_recursor(env(), n) && n != get_eq_cases_on_name()) { return recursor_kind::CasesOn; } else if (::lean::is_aux_recursor(env(), n) || is_user_defined_recursor(env(), n)) { return recursor_kind::Aux; } else { return recursor_kind::NotRecursor; } } bool is_aux_recursor(expr const & e) const { return get_recursor_app_kind(e) == recursor_kind::Aux; } expr visit_cases_on(expr const & e) { /* Try to reduce cases_on. Remark: we only unfold reducible constants. */ type_context_old::transparency_scope scope(ctx(), transparency_mode::Reducible); if (auto r1 = ctx().reduce_aux_recursor(e)) { if (auto r2 = ctx().norm_ext(*r1)) { return compiler_step_visitor::visit(*r2); } } return compiler_step_visitor::visit_app(e); } bool is_not_vm_function(expr const & e) { expr const & fn = get_app_fn(e); if (!is_constant(fn)) return false; name const & n = const_name(fn); declaration d = env().get(n); if (!d.is_definition() || d.is_theorem() || is_projection(env(), n) || is_no_confusion(env(), n) || ::lean::is_aux_recursor(env(), n) || is_user_defined_recursor(env(), n)) return false; return !is_vm_function(env(), n); } bool is_pack_unpack(expr const & e) { return ::lean::is_pack_unpack(m_env, e); } bool is_noncomputable_const(expr const & e) { return is_constant(e) && is_noncomputable(env(), const_name(e)); } bool is_inline(expr const & e) { return is_constant(e) && ::lean::is_inline(env(), const_name(e)); } bool should_unfold(expr const & e) { return (is_not_vm_function(e) && !ctx().is_proof(e) && !is_pack_unpack(e) && !is_noncomputable_const(e)) || (is_inline(e)); } expr unfold(expr const & e) { if (auto r = unfold_term(env(), e)) { return visit(*r); } else { throw exception(sstream() << "failed to generate bytecode, VM does not have code for '" << get_app_fn(e) << "'"); } } virtual expr visit_constant(expr const & e) override { type_context_old::nozeta_scope scope(ctx()); if (should_unfold(e)) return visit(unfold(e)); else return e; } virtual expr visit_app(expr const & e) override { type_context_old::nozeta_scope scope(ctx()); switch (get_recursor_app_kind(e)) { case recursor_kind::NotRecursor: { if (should_unfold(e)) return visit(unfold(e)); expr new_e; { type_context_old::transparency_scope scope(ctx(), transparency_mode::Reducible); new_e = copy_tag(e, ctx().whnf_head_pred(e, [&](expr const &) { return false; })); } if (is_eqp(new_e, e)) return compiler_step_visitor::visit_app(new_e); else return compiler_step_visitor::visit(new_e); } case recursor_kind::CasesOn: return visit_cases_on(e); case recursor_kind::Aux: expr new_e; { type_context_old::transparency_scope scope(ctx(), transparency_mode::Reducible); new_e = copy_tag(e, ctx().whnf_head_pred(e, [&](expr const & e) { return is_aux_recursor(e); })); } return compiler_step_visitor::visit(new_e); } lean_unreachable(); } public: expand_aux_fn(environment const & env, abstract_context_cache & cache):compiler_step_visitor(env, cache) {} }; static expr expand_aux(environment const & env, abstract_context_cache & cache, expr const & e) { return expand_aux_fn(env, cache)(e); } static name * g_tmp_prefix = nullptr; class preprocess_fn { environment m_env; options m_opts; context_cache m_cache; bool check(declaration const & d, expr const & v) { bool memoize = true; bool trusted_only = false; type_checker tc(m_env, memoize, trusted_only); expr t = tc.check(v, d.get_univ_params()); if (!tc.is_def_eq(d.get_type(), t)) throw exception("preprocess failed"); return true; } void display(buffer<procedure> const & procs) { for (auto const & p : procs) { tout() << ">> " << p.m_name << "\n" << p.m_code << "\n"; } } void erase_irrelevant(buffer<procedure> & procs) { for (procedure & p : procs) { p.m_code = ::lean::erase_irrelevant(m_env, m_cache, p.m_code); } } #if 0 void dump_pos_info(expr const & v) { std::cout << v << "\n\n"; for_each(v, [&](expr const & e, unsigned) { auto pip = get_pos_info_provider(); if (!pip) return false; if (auto p = pip->get_pos_info(e)) std::cout << "pos[" << ((unsigned)e.kind()) << "]: " << p->first << ":" << p->second << "\n" << e << "\n"; return true; }); std::cout << "------------\n"; } void dump_pos_info(buffer<pair<name, expr>> & procs) { for (auto p : procs) dump_pos_info(p.second); } #endif /* If type of d is a proposition or return a type, we don't need to compile it. We can just generate (fun args, neutral_expr) This procedure returns true if type of d is a proposition or return a type, and store the dummy code above in */ bool compile_irrelevant(declaration const & d, buffer<procedure> & procs) { type_context_old ctx(m_env, transparency_mode::All); expr type = d.get_type(); type_context_old::tmp_locals locals(ctx); while (true) { type = ctx.relaxed_whnf(type); if (!is_pi(type)) break; expr local = locals.push_local_from_binding(type); type = instantiate(binding_body(type), local); } if (ctx.is_prop(type) || is_sort(type)) { expr r = locals.mk_lambda(mk_neutral_expr()); procs.emplace_back(d.get_name(), optional<pos_info>(), r); return true; } else { return false; } } public: preprocess_fn(environment const & env, options const & opts): m_env(env), m_opts(opts) {} void operator()(declaration const & d, buffer<procedure> & procs) { if (compile_irrelevant(d, procs)) return; expr v = d.get_value(); lean_trace(name({"compiler", "input"}), tout() << "\n" << v << "\n";); v = inline_simple_definitions(m_env, m_opts, m_cache, v); lean_cond_assert("compiler", check(d, v)); lean_trace(name({"compiler", "inline"}), tout() << "\n" << v << "\n";); v = expand_aux(m_env, m_cache, v); lean_cond_assert("compiler", check(d, v)); lean_trace(name({"compiler", "expand_aux"}), tout() << "\n" << v << "\n";); v = mark_comp_irrelevant_subterms(m_env, m_cache, v); lean_cond_assert("compiler", check(d, v)); v = find_nat_values(m_env, v); lean_cond_assert("compiler", check(d, v)); v = eta_expand(m_env, m_cache, v); lean_cond_assert("compiler", check(d, v)); lean_trace(name({"compiler", "eta_expansion"}), tout() << "\n" << v << "\n";); v = elim_recursors(m_env, m_cache, d.get_name(), v, procs); procs.emplace_back(d.get_name(), get_decl_pos_info(m_env, d.get_name()), v); lean_cond_assert("compiler", check(d, procs.back().m_code)); lean_trace(name({"compiler", "elim_recursors"}), tout() << "\n"; display(procs);); erase_irrelevant(procs); lean_trace(name({"compiler", "erase_irrelevant"}), tout() << "\n"; display(procs);); reduce_arity(m_env, m_cache, procs); lean_trace(name({"compiler", "reduce_arity"}), tout() << "\n"; display(procs);); erase_trivial_structures(m_env, m_cache, procs); lean_trace(name({"compiler", "erase_trivial_structures"}), tout() << "\n"; display(procs);); lambda_lifting(m_env, m_cache, d.get_name(), procs); lean_trace(name({"compiler", "lambda_lifting"}), tout() << "\n"; display(procs);); simp_inductive(m_env, m_cache, procs); lean_trace(name({"compiler", "simplify_inductive"}), tout() << "\n"; display(procs);); elim_unused_lets(m_env, m_cache, procs); lean_trace(name({"compiler", "elim_unused_lets"}), tout() << "\n"; display(procs);); extract_values(m_env, m_cache, d.get_name(), procs); lean_trace(name({"compiler", "extract_values"}), tout() << "\n"; display(procs);); cse(m_env, m_cache, procs); lean_trace(name({"compiler", "cse"}), tout() << "\n"; display(procs);); lean_trace(name({"compiler", "preprocess"}), tout() << "\n"; display(procs);); } }; void preprocess(environment const & env, options const & opts, declaration const & d, buffer<procedure> & result) { return preprocess_fn(env, opts)(d, result); } void preprocess(environment const & env, options const & opts, buffer<declaration> const & ds, buffer<procedure> & result) { for (declaration const & d : ds) { buffer<procedure> procs; preprocess(env, opts, d, procs); result.append(procs); } } void initialize_preprocess() { register_trace_class("compiler"); register_trace_class({"compiler", "input"}); register_trace_class({"compiler", "expand_aux"}); register_trace_class({"compiler", "eta_expansion"}); register_trace_class({"compiler", "simplify_pr1"}); register_trace_class({"compiler", "inline"}); register_trace_class({"compiler", "elim_recursors"}); register_trace_class({"compiler", "erase_irrelevant"}); register_trace_class({"compiler", "reduce_arity"}); register_trace_class({"compiler", "erase_trivial_structures"}); register_trace_class({"compiler", "lambda_lifting"}); register_trace_class({"compiler", "simplify_inductive"}); register_trace_class({"compiler", "elim_unused_lets"}); register_trace_class({"compiler", "extract_values"}); register_trace_class({"compiler", "cse"}); register_trace_class({"compiler", "preprocess"}); g_tmp_prefix = new name(name::mk_internal_unique_name()); } void finalize_preprocess() { delete g_tmp_prefix; } }
/* Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "kernel/declaration.h" #include "kernel/type_checker.h" #include "kernel/replace_fn.h" #include "kernel/instantiate.h" #include "kernel/for_each_fn.h" #include "kernel/scope_pos_info_provider.h" #include "library/trace.h" #include "library/projection.h" #include "library/constants.h" #include "library/aux_recursors.h" #include "library/user_recursors.h" #include "library/util.h" #include "library/quote.h" #include "library/noncomputable.h" #include "library/context_cache.h" #include "library/module.h" #include "library/vm/vm.h" #include "library/compiler/util.h" #include "library/compiler/preprocess.h" #include "library/compiler/compiler_step_visitor.h" #include "library/compiler/comp_irrelevant.h" #include "library/compiler/nat_value.h" #include "library/compiler/eta_expansion.h" #include "library/compiler/inliner.h" #include "library/compiler/elim_recursors.h" #include "library/compiler/erase_irrelevant.h" #include "library/compiler/reduce_arity.h" #include "library/compiler/lambda_lifting.h" #include "library/compiler/simp_inductive.h" #include "library/compiler/elim_unused_lets.h" #include "library/compiler/extract_values.h" #include "library/compiler/cse.h" #include "library/string.h" namespace lean { class expand_aux_fn : public compiler_step_visitor { enum class recursor_kind { Aux, CasesOn, NotRecursor }; /* We only expand auxiliary recursors and user-defined recursors. However, we don't unfold recursors of the form C.cases_on if C != eq. */ recursor_kind get_recursor_app_kind(expr const & e) const { if (!is_app(e)) return recursor_kind::NotRecursor; expr const & fn = get_app_fn(e); if (!is_constant(fn)) return recursor_kind::NotRecursor; name const & n = const_name(fn); if (is_cases_on_recursor(env(), n) && n != get_eq_cases_on_name()) { return recursor_kind::CasesOn; } else if (::lean::is_aux_recursor(env(), n) || is_user_defined_recursor(env(), n)) { return recursor_kind::Aux; } else { return recursor_kind::NotRecursor; } } bool is_aux_recursor(expr const & e) const { return get_recursor_app_kind(e) == recursor_kind::Aux; } expr visit_cases_on(expr const & e) { /* Try to reduce cases_on. Remark: we only unfold reducible constants. */ type_context_old::transparency_scope scope(ctx(), transparency_mode::Reducible); if (auto r1 = ctx().reduce_aux_recursor(e)) { if (auto r2 = ctx().norm_ext(*r1)) { return compiler_step_visitor::visit(*r2); } } return compiler_step_visitor::visit_app(e); } bool is_not_vm_function(expr const & e) { expr const & fn = get_app_fn(e); if (!is_constant(fn)) return false; name const & n = const_name(fn); declaration d = env().get(n); if (!d.is_definition() || d.is_theorem() || is_projection(env(), n) || is_no_confusion(env(), n) || ::lean::is_aux_recursor(env(), n) || is_user_defined_recursor(env(), n)) return false; return !is_vm_function(env(), n); } bool is_pack_unpack(expr const & e) { return ::lean::is_pack_unpack(m_env, e); } bool is_noncomputable_const(expr const & e) { return is_constant(e) && is_noncomputable(env(), const_name(e)); } bool is_inline(expr const & e) { return is_constant(e) && ::lean::is_inline(env(), const_name(e)); } bool should_unfold(expr const & e) { return (is_not_vm_function(e) && !ctx().is_proof(e) && !is_pack_unpack(e) && !is_noncomputable_const(e)) || (is_inline(e)); } expr unfold(expr const & e) { if (auto r = unfold_term(env(), e)) { return visit(*r); } else { throw exception(sstream() << "failed to generate bytecode, VM does not have code for '" << get_app_fn(e) << "'"); } } virtual expr visit_constant(expr const & e) override { type_context_old::nozeta_scope scope(ctx()); if (should_unfold(e)) return visit(unfold(e)); else return e; } virtual expr visit_app(expr const & e) override { type_context_old::nozeta_scope scope(ctx()); switch (get_recursor_app_kind(e)) { case recursor_kind::NotRecursor: { if (should_unfold(e)) return visit(unfold(e)); expr new_e; { type_context_old::transparency_scope scope(ctx(), transparency_mode::Reducible); new_e = copy_tag(e, ctx().whnf_head_pred(e, [&](expr const &) { return false; })); } if (is_eqp(new_e, e)) return compiler_step_visitor::visit_app(new_e); else return compiler_step_visitor::visit(new_e); } case recursor_kind::CasesOn: return visit_cases_on(e); case recursor_kind::Aux: expr new_e; { type_context_old::transparency_scope scope(ctx(), transparency_mode::Reducible); new_e = copy_tag(e, ctx().whnf_head_pred(e, [&](expr const & e) { return is_aux_recursor(e); })); } return compiler_step_visitor::visit(new_e); } lean_unreachable(); } public: expand_aux_fn(environment const & env, abstract_context_cache & cache):compiler_step_visitor(env, cache) {} }; static expr expand_aux(environment const & env, abstract_context_cache & cache, expr const & e) { return expand_aux_fn(env, cache)(e); } expr find_string_values(expr const & e) { return replace(e, [] (expr const & e) -> optional<expr> { if (auto v = to_string(e)) return some_expr(copy_tag(e, from_string(*v))); return {}; }); } static name * g_tmp_prefix = nullptr; class preprocess_fn { environment m_env; options m_opts; context_cache m_cache; bool check(declaration const & d, expr const & v) { bool memoize = true; bool trusted_only = false; type_checker tc(m_env, memoize, trusted_only); expr t = tc.check(v, d.get_univ_params()); if (!tc.is_def_eq(d.get_type(), t)) throw exception("preprocess failed"); return true; } void display(buffer<procedure> const & procs) { for (auto const & p : procs) { tout() << ">> " << p.m_name << "\n" << p.m_code << "\n"; } } void erase_irrelevant(buffer<procedure> & procs) { for (procedure & p : procs) { p.m_code = ::lean::erase_irrelevant(m_env, m_cache, p.m_code); } } #if 0 void dump_pos_info(expr const & v) { std::cout << v << "\n\n"; for_each(v, [&](expr const & e, unsigned) { auto pip = get_pos_info_provider(); if (!pip) return false; if (auto p = pip->get_pos_info(e)) std::cout << "pos[" << ((unsigned)e.kind()) << "]: " << p->first << ":" << p->second << "\n" << e << "\n"; return true; }); std::cout << "------------\n"; } void dump_pos_info(buffer<pair<name, expr>> & procs) { for (auto p : procs) dump_pos_info(p.second); } #endif /* If type of d is a proposition or return a type, we don't need to compile it. We can just generate (fun args, neutral_expr) This procedure returns true if type of d is a proposition or return a type, and store the dummy code above in */ bool compile_irrelevant(declaration const & d, buffer<procedure> & procs) { type_context_old ctx(m_env, transparency_mode::All); expr type = d.get_type(); type_context_old::tmp_locals locals(ctx); while (true) { type = ctx.relaxed_whnf(type); if (!is_pi(type)) break; expr local = locals.push_local_from_binding(type); type = instantiate(binding_body(type), local); } if (ctx.is_prop(type) || is_sort(type)) { expr r = locals.mk_lambda(mk_neutral_expr()); procs.emplace_back(d.get_name(), optional<pos_info>(), r); return true; } else { return false; } } public: preprocess_fn(environment const & env, options const & opts): m_env(env), m_opts(opts) {} void operator()(declaration const & d, buffer<procedure> & procs) { if (compile_irrelevant(d, procs)) return; expr v = d.get_value(); lean_trace(name({"compiler", "input"}), tout() << "\n" << v << "\n";); v = inline_simple_definitions(m_env, m_opts, m_cache, v); lean_cond_assert("compiler", check(d, v)); lean_trace(name({"compiler", "inline"}), tout() << "\n" << v << "\n";); v = expand_aux(m_env, m_cache, v); lean_cond_assert("compiler", check(d, v)); lean_trace(name({"compiler", "expand_aux"}), tout() << "\n" << v << "\n";); v = mark_comp_irrelevant_subterms(m_env, m_cache, v); lean_cond_assert("compiler", check(d, v)); v = find_string_values(v); v = find_nat_values(m_env, v); lean_cond_assert("compiler", check(d, v)); v = eta_expand(m_env, m_cache, v); lean_cond_assert("compiler", check(d, v)); lean_trace(name({"compiler", "eta_expansion"}), tout() << "\n" << v << "\n";); v = elim_recursors(m_env, m_cache, d.get_name(), v, procs); procs.emplace_back(d.get_name(), get_decl_pos_info(m_env, d.get_name()), v); lean_cond_assert("compiler", check(d, procs.back().m_code)); lean_trace(name({"compiler", "elim_recursors"}), tout() << "\n"; display(procs);); erase_irrelevant(procs); lean_trace(name({"compiler", "erase_irrelevant"}), tout() << "\n"; display(procs);); reduce_arity(m_env, m_cache, procs); lean_trace(name({"compiler", "reduce_arity"}), tout() << "\n"; display(procs);); erase_trivial_structures(m_env, m_cache, procs); lean_trace(name({"compiler", "erase_trivial_structures"}), tout() << "\n"; display(procs);); lambda_lifting(m_env, m_cache, d.get_name(), procs); lean_trace(name({"compiler", "lambda_lifting"}), tout() << "\n"; display(procs);); simp_inductive(m_env, m_cache, procs); lean_trace(name({"compiler", "simplify_inductive"}), tout() << "\n"; display(procs);); elim_unused_lets(m_env, m_cache, procs); lean_trace(name({"compiler", "elim_unused_lets"}), tout() << "\n"; display(procs);); extract_values(m_env, m_cache, d.get_name(), procs); lean_trace(name({"compiler", "extract_values"}), tout() << "\n"; display(procs);); cse(m_env, m_cache, procs); lean_trace(name({"compiler", "cse"}), tout() << "\n"; display(procs);); lean_trace(name({"compiler", "preprocess"}), tout() << "\n"; display(procs);); } }; void preprocess(environment const & env, options const & opts, declaration const & d, buffer<procedure> & result) { return preprocess_fn(env, opts)(d, result); } void preprocess(environment const & env, options const & opts, buffer<declaration> const & ds, buffer<procedure> & result) { for (declaration const & d : ds) { buffer<procedure> procs; preprocess(env, opts, d, procs); result.append(procs); } } void initialize_preprocess() { register_trace_class("compiler"); register_trace_class({"compiler", "input"}); register_trace_class({"compiler", "expand_aux"}); register_trace_class({"compiler", "eta_expansion"}); register_trace_class({"compiler", "simplify_pr1"}); register_trace_class({"compiler", "inline"}); register_trace_class({"compiler", "elim_recursors"}); register_trace_class({"compiler", "erase_irrelevant"}); register_trace_class({"compiler", "reduce_arity"}); register_trace_class({"compiler", "erase_trivial_structures"}); register_trace_class({"compiler", "lambda_lifting"}); register_trace_class({"compiler", "simplify_inductive"}); register_trace_class({"compiler", "elim_unused_lets"}); register_trace_class({"compiler", "extract_values"}); register_trace_class({"compiler", "cse"}); register_trace_class({"compiler", "preprocess"}); g_tmp_prefix = new name(name::mk_internal_unique_name()); } void finalize_preprocess() { delete g_tmp_prefix; } }
convert string expressions into macros (#187)
fix(library/compiler): convert string expressions into macros (#187)
C++
apache-2.0
digama0/lean,leanprover-community/lean,leanprover-community/lean,digama0/lean,leanprover-community/lean,dselsam/lean,leanprover-community/lean,leanprover-community/lean,digama0/lean,fpvandoorn/lean,fpvandoorn/lean,digama0/lean,fpvandoorn/lean,dselsam/lean,fpvandoorn/lean,dselsam/lean,dselsam/lean,dselsam/lean,leanprover-community/lean,dselsam/lean,digama0/lean,fpvandoorn/lean,digama0/lean,fpvandoorn/lean
1ce793eecd01aaa18fae2269c1445e581007a359
src/cpp/desktop/DesktopMain.cpp
src/cpp/desktop/DesktopMain.cpp
/* * DesktopMain.cpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <QtGui> #include <QPushButton> #include <boost/bind.hpp> #include <boost/function.hpp> #include <boost/scoped_ptr.hpp> #include <core/Log.hpp> #include <core/system/FileScanner.hpp> #include <core/SafeConvert.hpp> #include <core/StringUtils.hpp> #include <core/system/System.hpp> #include <core/system/Environment.hpp> #include <core/r_util/RProjectFile.hpp> #include <core/r_util/RUserData.hpp> #include "DesktopApplicationLaunch.hpp" #include "DesktopSlotBinders.hpp" #include "DesktopDetectRHome.hpp" #include "DesktopUtils.hpp" #include "DesktopSessionLauncher.hpp" #include "DesktopProgressActivator.hpp" #include "DesktopNetworkProxyFactory.hpp" #include "DesktopActivationOverlay.hpp" QProcess* pRSessionProcess; QString sharedSecret; using namespace rstudio; using namespace rstudio::core; using namespace rstudio::desktop; namespace { void initializeSharedSecret() { sharedSecret = QString::number(rand()) + QString::number(rand()) + QString::number(rand()); std::string value = sharedSecret.toUtf8().constData(); core::system::setenv("RS_SHARED_SECRET", value); } void initializeWorkingDirectory(int argc, char* argv[], const QString& filename) { // bail if we've already got a working directory as a result of // a call to openSessionInNewWindow if (!core::system::getenv(kRStudioInitialWorkingDir).empty()) return; // calculate what our initial working directory should be std::string workingDir; // if there is a filename passed to us then use it's path if (filename != QString()) { FilePath filePath(filename.toUtf8().constData()); if (filePath.exists()) { if (filePath.isDirectory()) workingDir = filePath.absolutePath(); else workingDir = filePath.parent().absolutePath(); } } // do additinal detection if necessary if (workingDir.empty()) { // get current path FilePath currentPath = FilePath::safeCurrentPath( core::system::userHomePath()); #if defined(_WIN32) || defined(__APPLE__) // detect whether we were launched from the system application menu // (e.g. Dock, Program File icon, etc.). we do this by checking // whether the executable path is within the current path. if we // weren't launched from the system app menu that set the initial // wd to the current path FilePath exePath; Error error = core::system::executablePath(argv[0], &exePath); if (!error) { if (!exePath.isWithin(currentPath)) workingDir = currentPath.absolutePath(); } else { LOG_ERROR(error); } #else // on linux we take the current working dir if we were launched // from within a terminal if (core::system::stdoutIsTerminal() && (currentPath != core::system::userHomePath())) { workingDir = currentPath.absolutePath(); } #endif } // set the working dir if we have one if (!workingDir.empty()) core::system::setenv(kRStudioInitialWorkingDir, workingDir); } void setInitialProject(const FilePath& projectFile, QString* pFilename) { core::system::setenv(kRStudioInitialProject, projectFile.absolutePath()); pFilename->clear(); } void initializeStartupEnvironment(QString* pFilename) { // if the filename ends with .RData or .rda then this is an // environment file. if it ends with .Rproj then it is // a project file. we handle both cases by setting an environment // var and then resetting the pFilename so it isn't processed // using the standard open file logic FilePath filePath(pFilename->toUtf8().constData()); if (filePath.exists()) { std::string ext = filePath.extensionLowerCase(); // if it is a directory or just an .rdata file then we can see // whether there is a project file we can automatically attach to if (filePath.isDirectory()) { FilePath projectFile = r_util::projectFromDirectory(filePath); if (!projectFile.empty()) { setInitialProject(projectFile, pFilename); } } else if (ext == ".rproj") { setInitialProject(filePath, pFilename); } else if (ext == ".rdata" || ext == ".rda") { core::system::setenv(kRStudioInitialEnvironment, filePath.absolutePath()); pFilename->clear(); } } } QString verifyAndNormalizeFilename(const QString &filename) { if (filename.isNull() || filename.isEmpty()) return QString(); QFileInfo fileInfo(filename); if (fileInfo.exists()) return fileInfo.absoluteFilePath(); else return QString(); } bool isNonProjectFilename(const QString &filename) { if (filename.isNull() || filename.isEmpty()) return false; FilePath filePath(filename.toUtf8().constData()); return filePath.exists() && filePath.extensionLowerCase() != ".rproj"; } bool useChromiumDevtools() { // disable by default due to security concerns // https://bugreports.qt.io/browse/QTBUG-50725 bool useDevtools = false; #ifndef NDEBUG // but enable by default for development builds useDevtools = true; #endif // enable when environment variable is set if (!core::system::getenv("RSTUDIO_USE_CHROMIUM_DEVTOOLS").empty()) { useDevtools = true; } return useDevtools; } } // anonymous namespace int main(int argc, char* argv[]) { core::system::initHook(); try { initializeLang(); if (useChromiumDevtools()) { // use QTcpSocket to find an open port. this is unfortunately a bit racey // but AFAICS there isn't a better solution for port selection QByteArray port; QTcpSocket* pSocket = new QTcpSocket(); if (pSocket->bind()) { quint16 port = pSocket->localPort(); desktopInfo().setChromiumDevtoolsPort(port); core::system::setenv("QTWEBENGINE_REMOTE_DEBUGGING", safe_convert::numberToString(port)); pSocket->close(); } } // initialize log core::system::initializeLog("rdesktop", core::system::kLogLevelWarning, desktop::userLogPath()); // ignore SIGPIPE Error error = core::system::ignoreSignal(core::system::SigPipe); if (error) LOG_ERROR(error); // set application attributes QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); // prepare command line arguments static std::vector<char*> arguments(argv, argv + argc); #ifndef NDEBUG // disable web security for development builds (so we can // get access to sourcemaps) static char disableWebSecurity[] = "--disable-web-security"; arguments.push_back(disableWebSecurity); #endif // disable chromium renderer accessibility by default (it can cause // slowdown when used in conjunction with some applications; see e.g. // https://github.com/rstudio/rstudio/issues/1990) if (core::system::getenv("RSTUDIO_ACCESSIBILITY").empty()) { static char disableRendererAccessibility[] = "--disable-renderer-accessibility"; arguments.push_back(disableRendererAccessibility); } // re-assign command line arguments argc = (int) arguments.size(); argv = &arguments[0]; // prepare application for launch boost::scoped_ptr<QApplication> pApp; boost::scoped_ptr<ApplicationLaunch> pAppLaunch; ApplicationLaunch::init(QString::fromUtf8("RStudio"), argc, argv, &pApp, &pAppLaunch); // determine the filename that was passed to us QString filename; #ifdef __APPLE__ // get filename from OpenFile apple-event (pump to ensure delivery) pApp->processEvents(); filename = verifyAndNormalizeFilename( pAppLaunch->startupOpenFileRequest()); #endif // allow all platforms (including OSX) to check the command line. // we include OSX because the way Qt handles apple events is to // re-route them to the first instance to register for events. in // this case (for projects) we use this to initiate a launch // of the application with the project filename on the command line if (filename.isEmpty()) { // get filename from command line arguments if (pApp->arguments().size() > 1) { QString arg = pApp->arguments().last(); if (arg != QString::fromUtf8(kRunDiagnosticsOption)) filename = verifyAndNormalizeFilename(arg); } } // if we have a filename and it is NOT a project file then see // if we can open it within an existing instance if (isNonProjectFilename(filename)) { if (pAppLaunch->sendMessage(filename)) return 0; } else { // try to register ourselves as a peer for others pAppLaunch->attemptToRegisterPeer(); } // init options from command line desktop::options().initFromCommandLine(pApp->arguments()); // reset log if we are in run-diagnostics mode if (desktop::options().runDiagnostics()) { desktop::reattachConsoleIfNecessary(); initializeStderrLog("rdesktop", core::system::kLogLevelWarning); } initializeSharedSecret(); initializeWorkingDirectory(argc, argv, filename); initializeStartupEnvironment(&filename); Options& options = desktop::options(); if (!prepareEnvironment(options)) return 1; // get install path FilePath installPath; error = core::system::installPath("..", argv[0], &installPath); if (error) { LOG_ERROR(error); return EXIT_FAILURE; } #ifdef _WIN32 RVersion version = detectRVersion(false); #endif // calculate paths to config file, rsession, and desktop scripts FilePath confPath, sessionPath, scriptsPath; bool devMode = false; // check for debug configuration FilePath currentPath = FilePath::safeCurrentPath(installPath); if (currentPath.complete("conf/rdesktop-dev.conf").exists()) { confPath = currentPath.complete("conf/rdesktop-dev.conf"); sessionPath = currentPath.complete("session/rsession"); scriptsPath = currentPath.complete("desktop"); devMode = true; #ifdef _WIN32 if (version.architecture() == ArchX64) sessionPath = installPath.complete("session/x64/rsession"); #endif } // if there is no conf path then release mode if (confPath.empty()) { // default paths (then tweak) sessionPath = installPath.complete("bin/rsession"); scriptsPath = installPath.complete("bin"); // check for win64 binary on windows #ifdef _WIN32 if (version.architecture() == ArchX64) sessionPath = installPath.complete("bin/x64/rsession"); #endif // check for running in a bundle on OSX #ifdef __APPLE__ if (installPath.complete("Info.plist").exists()) { sessionPath = installPath.complete("MacOS/rsession"); scriptsPath = installPath.complete("MacOS"); } #endif } core::system::fixupExecutablePath(&sessionPath); auto* pProxyFactory = new NetworkProxyFactory(); QNetworkProxyFactory::setApplicationProxyFactory(pProxyFactory); // set the scripts path in options desktop::options().setScriptsPath(scriptsPath); // launch session SessionLauncher sessionLauncher(sessionPath, confPath, filename, pAppLaunch.get()); sessionLauncher.launchFirstSession(installPath, devMode, pApp->arguments()); ProgressActivator progressActivator; int result = pApp->exec(); desktop::activation().releaseLicense(); options.cleanUpScratchTempDir(); return result; } CATCH_UNEXPECTED_EXCEPTION } #ifdef _WIN32 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { return main(__argc, __argv); } #endif
/* * DesktopMain.cpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <QtGui> #include <QPushButton> #include <boost/bind.hpp> #include <boost/function.hpp> #include <boost/scoped_ptr.hpp> #include <core/Log.hpp> #include <core/system/FileScanner.hpp> #include <core/SafeConvert.hpp> #include <core/StringUtils.hpp> #include <core/system/System.hpp> #include <core/system/Environment.hpp> #include <core/r_util/RProjectFile.hpp> #include <core/r_util/RUserData.hpp> #include "DesktopApplicationLaunch.hpp" #include "DesktopSlotBinders.hpp" #include "DesktopDetectRHome.hpp" #include "DesktopUtils.hpp" #include "DesktopSessionLauncher.hpp" #include "DesktopProgressActivator.hpp" #include "DesktopNetworkProxyFactory.hpp" #include "DesktopActivationOverlay.hpp" QProcess* pRSessionProcess; QString sharedSecret; using namespace rstudio; using namespace rstudio::core; using namespace rstudio::desktop; namespace { void initializeSharedSecret() { sharedSecret = QString::number(rand()) + QString::number(rand()) + QString::number(rand()); std::string value = sharedSecret.toUtf8().constData(); core::system::setenv("RS_SHARED_SECRET", value); } void initializeWorkingDirectory(int argc, char* argv[], const QString& filename) { // bail if we've already got a working directory as a result of // a call to openSessionInNewWindow if (!core::system::getenv(kRStudioInitialWorkingDir).empty()) return; // calculate what our initial working directory should be std::string workingDir; // if there is a filename passed to us then use it's path if (filename != QString()) { FilePath filePath(filename.toUtf8().constData()); if (filePath.exists()) { if (filePath.isDirectory()) workingDir = filePath.absolutePath(); else workingDir = filePath.parent().absolutePath(); } } // do additinal detection if necessary if (workingDir.empty()) { // get current path FilePath currentPath = FilePath::safeCurrentPath( core::system::userHomePath()); #if defined(_WIN32) || defined(__APPLE__) // detect whether we were launched from the system application menu // (e.g. Dock, Program File icon, etc.). we do this by checking // whether the executable path is within the current path. if we // weren't launched from the system app menu that set the initial // wd to the current path FilePath exePath; Error error = core::system::executablePath(argv[0], &exePath); if (!error) { if (!exePath.isWithin(currentPath)) workingDir = currentPath.absolutePath(); } else { LOG_ERROR(error); } #else // on linux we take the current working dir if we were launched // from within a terminal if (core::system::stdoutIsTerminal() && (currentPath != core::system::userHomePath())) { workingDir = currentPath.absolutePath(); } #endif } // set the working dir if we have one if (!workingDir.empty()) core::system::setenv(kRStudioInitialWorkingDir, workingDir); } void setInitialProject(const FilePath& projectFile, QString* pFilename) { core::system::setenv(kRStudioInitialProject, projectFile.absolutePath()); pFilename->clear(); } void initializeStartupEnvironment(QString* pFilename) { // if the filename ends with .RData or .rda then this is an // environment file. if it ends with .Rproj then it is // a project file. we handle both cases by setting an environment // var and then resetting the pFilename so it isn't processed // using the standard open file logic FilePath filePath(pFilename->toUtf8().constData()); if (filePath.exists()) { std::string ext = filePath.extensionLowerCase(); // if it is a directory or just an .rdata file then we can see // whether there is a project file we can automatically attach to if (filePath.isDirectory()) { FilePath projectFile = r_util::projectFromDirectory(filePath); if (!projectFile.empty()) { setInitialProject(projectFile, pFilename); } } else if (ext == ".rproj") { setInitialProject(filePath, pFilename); } else if (ext == ".rdata" || ext == ".rda") { core::system::setenv(kRStudioInitialEnvironment, filePath.absolutePath()); pFilename->clear(); } } } QString verifyAndNormalizeFilename(const QString &filename) { if (filename.isNull() || filename.isEmpty()) return QString(); QFileInfo fileInfo(filename); if (fileInfo.exists()) return fileInfo.absoluteFilePath(); else return QString(); } bool isNonProjectFilename(const QString &filename) { if (filename.isNull() || filename.isEmpty()) return false; FilePath filePath(filename.toUtf8().constData()); return filePath.exists() && filePath.extensionLowerCase() != ".rproj"; } bool useChromiumDevtools() { // disable by default due to security concerns // https://bugreports.qt.io/browse/QTBUG-50725 bool useDevtools = false; #ifndef NDEBUG // but enable by default for development builds useDevtools = true; #endif // enable when environment variable is set if (!core::system::getenv("RSTUDIO_USE_CHROMIUM_DEVTOOLS").empty()) { useDevtools = true; } return useDevtools; } } // anonymous namespace int main(int argc, char* argv[]) { core::system::initHook(); try { initializeLang(); if (useChromiumDevtools()) { // use QTcpSocket to find an open port. this is unfortunately a bit racey // but AFAICS there isn't a better solution for port selection QByteArray port; QTcpSocket* pSocket = new QTcpSocket(); if (pSocket->bind()) { quint16 port = pSocket->localPort(); desktopInfo().setChromiumDevtoolsPort(port); core::system::setenv("QTWEBENGINE_REMOTE_DEBUGGING", safe_convert::numberToString(port)); pSocket->close(); } } // initialize log core::system::initializeLog("rdesktop", core::system::kLogLevelWarning, desktop::userLogPath()); // ignore SIGPIPE Error error = core::system::ignoreSignal(core::system::SigPipe); if (error) LOG_ERROR(error); // set application attributes QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); // prepare command line arguments static std::vector<char*> arguments(argv, argv + argc); #ifndef NDEBUG // disable web security for development builds (so we can // get access to sourcemaps) static char disableWebSecurity[] = "--disable-web-security"; arguments.push_back(disableWebSecurity); #endif // disable chromium renderer accessibility by default (it can cause // slowdown when used in conjunction with some applications; see e.g. // https://github.com/rstudio/rstudio/issues/1990) if (core::system::getenv("RSTUDIO_ACCESSIBILITY").empty()) { static char disableRendererAccessibility[] = "--disable-renderer-accessibility"; arguments.push_back(disableRendererAccessibility); } // re-assign command line arguments argc = (int) arguments.size(); argv = &arguments[0]; // prepare application for launch boost::scoped_ptr<QApplication> pApp; boost::scoped_ptr<ApplicationLaunch> pAppLaunch; ApplicationLaunch::init(QString::fromUtf8("RStudio"), argc, argv, &pApp, &pAppLaunch); // determine the filename that was passed to us QString filename; #ifdef __APPLE__ // get filename from OpenFile apple-event (pump to ensure delivery) pApp->processEvents(); filename = verifyAndNormalizeFilename( pAppLaunch->startupOpenFileRequest()); #endif // allow all platforms (including OSX) to check the command line. // we include OSX because the way Qt handles apple events is to // re-route them to the first instance to register for events. in // this case (for projects) we use this to initiate a launch // of the application with the project filename on the command line if (filename.isEmpty()) { // get filename from command line arguments if (pApp->arguments().size() > 1) { QString arg = pApp->arguments().at(1); if (arg != QString::fromUtf8(kRunDiagnosticsOption)) filename = verifyAndNormalizeFilename(arg); } } // if we have a filename and it is NOT a project file then see // if we can open it within an existing instance if (isNonProjectFilename(filename)) { if (pAppLaunch->sendMessage(filename)) return 0; } else { // try to register ourselves as a peer for others pAppLaunch->attemptToRegisterPeer(); } // init options from command line desktop::options().initFromCommandLine(pApp->arguments()); // reset log if we are in run-diagnostics mode if (desktop::options().runDiagnostics()) { desktop::reattachConsoleIfNecessary(); initializeStderrLog("rdesktop", core::system::kLogLevelWarning); } initializeSharedSecret(); initializeWorkingDirectory(argc, argv, filename); initializeStartupEnvironment(&filename); Options& options = desktop::options(); if (!prepareEnvironment(options)) return 1; // get install path FilePath installPath; error = core::system::installPath("..", argv[0], &installPath); if (error) { LOG_ERROR(error); return EXIT_FAILURE; } #ifdef _WIN32 RVersion version = detectRVersion(false); #endif // calculate paths to config file, rsession, and desktop scripts FilePath confPath, sessionPath, scriptsPath; bool devMode = false; // check for debug configuration FilePath currentPath = FilePath::safeCurrentPath(installPath); if (currentPath.complete("conf/rdesktop-dev.conf").exists()) { confPath = currentPath.complete("conf/rdesktop-dev.conf"); sessionPath = currentPath.complete("session/rsession"); scriptsPath = currentPath.complete("desktop"); devMode = true; #ifdef _WIN32 if (version.architecture() == ArchX64) sessionPath = installPath.complete("session/x64/rsession"); #endif } // if there is no conf path then release mode if (confPath.empty()) { // default paths (then tweak) sessionPath = installPath.complete("bin/rsession"); scriptsPath = installPath.complete("bin"); // check for win64 binary on windows #ifdef _WIN32 if (version.architecture() == ArchX64) sessionPath = installPath.complete("bin/x64/rsession"); #endif // check for running in a bundle on OSX #ifdef __APPLE__ if (installPath.complete("Info.plist").exists()) { sessionPath = installPath.complete("MacOS/rsession"); scriptsPath = installPath.complete("MacOS"); } #endif } core::system::fixupExecutablePath(&sessionPath); auto* pProxyFactory = new NetworkProxyFactory(); QNetworkProxyFactory::setApplicationProxyFactory(pProxyFactory); // set the scripts path in options desktop::options().setScriptsPath(scriptsPath); // launch session SessionLauncher sessionLauncher(sessionPath, confPath, filename, pAppLaunch.get()); sessionLauncher.launchFirstSession(installPath, devMode, pApp->arguments()); ProgressActivator progressActivator; int result = pApp->exec(); desktop::activation().releaseLicense(); options.cleanUpScratchTempDir(); return result; } CATCH_UNEXPECTED_EXCEPTION } #ifdef _WIN32 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { return main(__argc, __argv); } #endif
fix opening project file in osx to fix #2203 and fix #2205
fix opening project file in osx to fix #2203 and fix #2205
C++
agpl-3.0
JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio
99fdef50c56fdc42a790683fe3e65f06ee2f3adc
src/libraries/GameStatesLib/InitState.cpp
src/libraries/GameStatesLib/InitState.cpp
#include "InitState.hpp" const int rd::InitState::LOGIN_SUCCESSFUL = 1; rd::InitState::InitState(rd::RdNetworkManager *networkManager, rd::RdImageManager *imageManager, rd::RdInputManager *inputManager, rd::RdMentalMap *mentalMap, rd::RdRobotManager *robotManager, AudioManager *audioManager) : ManagerHub(networkManager, imageManager, inputManager, mentalMap, robotManager, audioManager) { state_id = "InitState"; login = false; logged_in = false; } rd::InitState::~InitState() { } bool rd::InitState::setup() { //-- Show Robot Devastation start screen: screen.show(); //-- Start Robot Devastation music theme: audioManager->start(); audioManager->play("RD_THEME", -1); //-- Wait for input (set listener): inputManager->addInputEventListener(this); inputManager->start(); //-- Setup network manager networkManager->addNetworkEventListener(mentalMap); mentalMap->addMentalMapEventListener((RdYarpNetworkManager *)networkManager); networkManager->start(); return true; } bool rd::InitState::loop() { if (login) { //-- Log in networkManager->login(mentalMap->getMyself()); logged_in = true; } return true; } bool rd::InitState::cleanup() { RD_DEBUG("Cleanup!!\n"); audioManager->stopMusic(); inputManager->removeInputEventListeners(); return true; } int rd::InitState::evaluateConditions() { if (logged_in) return LOGIN_SUCCESSFUL; return -1; } bool rd::InitState::onKeyDown(rd::RdKey k) { return true; } bool rd::InitState::onKeyUp(rd::RdKey k) { if (k.getValue() == RdKey::KEY_ENTER) RD_DEBUG("Enter was pressed!\n"); login = true; }
#include "InitState.hpp" const int rd::InitState::LOGIN_SUCCESSFUL = 1; rd::InitState::InitState(rd::RdNetworkManager *networkManager, rd::RdImageManager *imageManager, rd::RdInputManager *inputManager, rd::RdMentalMap *mentalMap, rd::RdRobotManager *robotManager, AudioManager *audioManager) : ManagerHub(networkManager, imageManager, inputManager, mentalMap, robotManager, audioManager) { state_id = "InitState"; login = false; logged_in = false; } rd::InitState::~InitState() { } bool rd::InitState::setup() { //-- Show Robot Devastation start screen: screen.show(); //-- Start Robot Devastation music theme: audioManager->start(); audioManager->play("RD_THEME", -1); //-- Wait for input (set listener): inputManager->addInputEventListener(this); inputManager->start(); //-- Setup network manager networkManager->addNetworkEventListener(mentalMap); mentalMap->addMentalMapEventListener((RdYarpNetworkManager *)networkManager); networkManager->start(); return true; } bool rd::InitState::loop() { if (login) { //-- Log in networkManager->login(mentalMap->getMyself()); logged_in = true; } return true; } bool rd::InitState::cleanup() { RD_DEBUG("Cleanup!!\n"); audioManager->stopMusic(); inputManager->removeInputEventListeners(); return true; } int rd::InitState::evaluateConditions() { if (logged_in) return LOGIN_SUCCESSFUL; return -1; } bool rd::InitState::onKeyDown(rd::RdKey k) { return true; } bool rd::InitState::onKeyUp(rd::RdKey k) { if (k.getValue() == RdKey::KEY_ENTER) { RD_DEBUG("Enter was pressed!\n"); login = true; } }
Fix if-related bug in InitState
Fix if-related bug in InitState
C++
lgpl-2.1
asrob-uc3m/robotDevastation,asrob-uc3m/robotDevastation
8de84643d70fa45130030853fc6452b9e7dfe392
tests/fe/rt_6.cc
tests/fe/rt_6.cc
//---------------------------- rt_6.cc --------------------------- // rt_6.cc,v 1.1 2003/06/09 15:59:07 wolf Exp // Version: // // Copyright (C) 2003, 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. // //---------------------------- rt_6.cc --------------------------- // adaptation of up_and_down for RT elements #include "../tests.h" #include <base/quadrature_lib.h> #include <base/logstream.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/tria_iterator.h> #include <dofs/dof_accessor.h> #include <grid/grid_generator.h> #include <grid/grid_tools.h> #include <fe/fe_nedelec.h> #include <fe/fe_raviart_thomas.h> #include <fe/fe_values.h> #include <vector> #include <fstream> #include <string> #define PRECISION 4 template <int dim> Point<dim> transform (const Point<dim> p) { switch (dim) { case 1: return p; case 2: return Point<dim>(p(0)*(1+p(1)), p(1)*(1+p(0))); case 3: return Point<dim>(p(0)*(1+p(1))*(1+p(2)), p(1)*(1+p(0))*(1+p(2)), p(2)*(1+p(0))*(1+p(1))); default: Assert (false, ExcNotImplemented()); return Point<dim>(); }; } template <int dim> void check_element (const Triangulation<dim> &tr, const FiniteElement<dim> &fe) { DoFHandler<dim> dof_handler(tr); dof_handler.distribute_dofs (fe); // create a mostly arbitrary // function plus a trend on this // grid Vector<double> tmp(dof_handler.n_dofs()); for (unsigned int i=0; i<tmp.size(); ++i) tmp(i) = (i + 13*i%17); // restrict this function to the // next coarser level and // distribute it again to the // higher level Vector<double> x(tmp.size()); Vector<double> v(fe.dofs_per_cell); for (typename DoFHandler<dim>::cell_iterator cell=dof_handler.begin(); cell!=dof_handler.end(); ++cell) if (cell->has_children() && cell->child(0)->active()) { // first make sure that what // we do is reasonable. for // this, _all_ children have // to be active, not only // some of them for (unsigned int c=0; c<GeometryInfo<dim>::children_per_cell; ++c) Assert (cell->child(c)->active(), ExcInternalError()); // then restrict and prolong cell->get_interpolated_dof_values (tmp, v); cell->set_dof_values_by_interpolation (v, x); }; // now x is a function on the fine // grid that is representable on // the coarse grid. so another // cycle should not alter it any // more: Vector<double> x2(x.size()); for (typename DoFHandler<dim>::cell_iterator cell=dof_handler.begin(); cell!=dof_handler.end(); ++cell) if (cell->has_children() && cell->child(0)->active()) { cell->get_interpolated_dof_values (x, v); cell->set_dof_values_by_interpolation (v, x2); }; // then check that this is so: x2 -= x; const double relative_residual = (x2.l2_norm() / x.l2_norm()); const double threshold = 1e-6; deallog << ", dofs_per_cell=" << fe.dofs_per_cell << "; relative residual: " << (relative_residual<threshold ? "ok" : "botched up!") << " (relative residual=" << relative_residual << ")" << std::endl; Assert (relative_residual < threshold*x.l2_norm(), ExcInternalError()); } template <int dim> void test () { // make a coarse triangulation as a // hypercube. if in more than 1d, // distort it so that it is no more // an affine image of the // hypercube, to make things more // difficult. then refine it twice Triangulation<dim> tr; GridGenerator::hyper_cube(tr, 0., 1.); Point<dim> (*p) (Point<dim>) = &transform<dim>; GridTools::transform (p, tr); tr.refine_global (2); // now for a list of finite // elements, for which we want to // test. we happily waste tons of // memory here, but who cares... const FiniteElement<dim> *fe_list[] = { new FE_RaviartThomas<dim>(0), new FE_RaviartThomas<dim>(1) }; for (unsigned int i=0; i<sizeof(fe_list)/sizeof(fe_list[0]); ++i) if (fe_list[i] != 0) { deallog << dim << "d, uniform grid, fe #" << i; check_element (tr, *fe_list[i]); } } int main() { std::ofstream logfile ("rt_6/output"); logfile.precision (PRECISION); logfile.setf(std::ios::fixed); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); test<2>(); return 0; }
//---------------------------- rt_6.cc --------------------------- // rt_6.cc,v 1.1 2003/06/09 15:59:07 wolf Exp // Version: // // Copyright (C) 2003, 2005, 2006 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. // //---------------------------- rt_6.cc --------------------------- // adaptation of up_and_down for RT elements #include "../tests.h" #include <base/quadrature_lib.h> #include <base/logstream.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/tria_iterator.h> #include <dofs/dof_accessor.h> #include <grid/grid_generator.h> #include <grid/grid_tools.h> #include <fe/fe_nedelec.h> #include <fe/fe_raviart_thomas.h> #include <fe/fe_values.h> #include <vector> #include <fstream> #include <string> #define PRECISION 4 template <int dim> Point<dim> transform (const Point<dim> p) { switch (dim) { case 1: return p; case 2: return Point<dim>(p(0)*(1+p(1)), p(1)*(1+p(0))); case 3: return Point<dim>(p(0)*(1+p(1))*(1+p(2)), p(1)*(1+p(0))*(1+p(2)), p(2)*(1+p(0))*(1+p(1))); default: Assert (false, ExcNotImplemented()); return Point<dim>(); }; } template <int dim> void check_element (const Triangulation<dim> &tr, const FiniteElement<dim> &fe) { DoFHandler<dim> dof_handler(tr); dof_handler.distribute_dofs (fe); // create a mostly arbitrary // function plus a trend on this // grid Vector<double> tmp(dof_handler.n_dofs()); for (unsigned int i=0; i<tmp.size(); ++i) tmp(i) = (i + 13*i%17); // restrict this function to the // next coarser level and // distribute it again to the // higher level Vector<double> x(tmp.size()); Vector<double> v(fe.dofs_per_cell); for (typename DoFHandler<dim>::cell_iterator cell=dof_handler.begin(); cell!=dof_handler.end(); ++cell) if (cell->has_children() && cell->child(0)->active()) { // first make sure that what // we do is reasonable. for // this, _all_ children have // to be active, not only // some of them for (unsigned int c=0; c<GeometryInfo<dim>::children_per_cell; ++c) Assert (cell->child(c)->active(), ExcInternalError()); // then restrict and prolongate cell->get_interpolated_dof_values (tmp, v); cell->set_dof_values_by_interpolation (v, x); }; // now x is a function on the fine // grid that is representable on // the coarse grid. so another // cycle should not alter it any // more: Vector<double> x2(x.size()); for (typename DoFHandler<dim>::cell_iterator cell=dof_handler.begin(); cell!=dof_handler.end(); ++cell) if (cell->has_children() && cell->child(0)->active()) { cell->get_interpolated_dof_values (x, v); cell->set_dof_values_by_interpolation (v, x2); }; // then check that this is so: x2 -= x; const double relative_residual = (x2.l2_norm() / x.l2_norm()); const double threshold = 1e-6; deallog << ", dofs_per_cell=" << fe.dofs_per_cell << "; relative residual: " << (relative_residual<threshold ? "ok" : "botched up!") << " (relative residual=" << relative_residual << ")" << std::endl; } template <int dim> void test () { // make a coarse triangulation as a // hypercube. if in more than 1d, // distort it so that it is no more // an affine image of the // hypercube, to make things more // difficult. then refine it twice Triangulation<dim> tr; GridGenerator::hyper_cube(tr, 0., 1.); Point<dim> (*p) (Point<dim>) = &transform<dim>; GridTools::transform (p, tr); tr.refine_global (2); // now for a list of finite // elements, for which we want to // test. we happily waste tons of // memory here, but who cares... const FiniteElement<dim> *fe_list[] = { new FE_RaviartThomas<dim>(0), new FE_RaviartThomas<dim>(1), new FE_RaviartThomas<dim>(2) }; for (unsigned int i=0; i<sizeof(fe_list)/sizeof(fe_list[0]); ++i) if (fe_list[i] != 0) { deallog << dim << "d, uniform grid, fe #" << i; check_element (tr, *fe_list[i]); } } int main() { std::ofstream logfile ("rt_6/output"); logfile.precision (PRECISION); logfile.setf(std::ios::fixed); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); test<2>(); test<3>(); return 0; }
add tests for higher order and 3D
add tests for higher order and 3D git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@12107 0785d39b-7218-0410-832d-ea1e28bc413d
C++
lgpl-2.1
natashasharma/dealii,jperryhouts/dealii,flow123d/dealii,nicolacavallini/dealii,spco/dealii,andreamola/dealii,EGP-CIG-REU/dealii,naliboff/dealii,nicolacavallini/dealii,lue/dealii,JaeryunYim/dealii,rrgrove6/dealii,naliboff/dealii,pesser/dealii,gpitton/dealii,nicolacavallini/dealii,mtezzele/dealii,andreamola/dealii,nicolacavallini/dealii,spco/dealii,mac-a/dealii,sriharisundar/dealii,sairajat/dealii,angelrca/dealii,JaeryunYim/dealii,johntfoster/dealii,johntfoster/dealii,kalj/dealii,mtezzele/dealii,JaeryunYim/dealii,msteigemann/dealii,Arezou-gh/dealii,angelrca/dealii,mac-a/dealii,kalj/dealii,kalj/dealii,adamkosik/dealii,lpolster/dealii,lpolster/dealii,johntfoster/dealii,rrgrove6/dealii,msteigemann/dealii,YongYang86/dealii,maieneuro/dealii,gpitton/dealii,lpolster/dealii,sriharisundar/dealii,YongYang86/dealii,gpitton/dealii,jperryhouts/dealii,ESeNonFossiIo/dealii,maieneuro/dealii,natashasharma/dealii,lpolster/dealii,natashasharma/dealii,pesser/dealii,nicolacavallini/dealii,danshapero/dealii,angelrca/dealii,andreamola/dealii,lpolster/dealii,rrgrove6/dealii,adamkosik/dealii,kalj/dealii,danshapero/dealii,mtezzele/dealii,natashasharma/dealii,adamkosik/dealii,adamkosik/dealii,gpitton/dealii,shakirbsm/dealii,sairajat/dealii,mac-a/dealii,danshapero/dealii,danshapero/dealii,maieneuro/dealii,andreamola/dealii,Arezou-gh/dealii,pesser/dealii,jperryhouts/dealii,msteigemann/dealii,johntfoster/dealii,sriharisundar/dealii,naliboff/dealii,gpitton/dealii,flow123d/dealii,gpitton/dealii,flow123d/dealii,andreamola/dealii,spco/dealii,ibkim11/dealii,ESeNonFossiIo/dealii,msteigemann/dealii,jperryhouts/dealii,danshapero/dealii,adamkosik/dealii,ibkim11/dealii,YongYang86/dealii,EGP-CIG-REU/dealii,lue/dealii,kalj/dealii,andreamola/dealii,naliboff/dealii,YongYang86/dealii,YongYang86/dealii,mac-a/dealii,lue/dealii,nicolacavallini/dealii,ibkim11/dealii,natashasharma/dealii,ibkim11/dealii,mac-a/dealii,jperryhouts/dealii,lpolster/dealii,YongYang86/dealii,JaeryunYim/dealii,shakirbsm/dealii,sriharisundar/dealii,mtezzele/dealii,shakirbsm/dealii,pesser/dealii,sriharisundar/dealii,maieneuro/dealii,sairajat/dealii,angelrca/dealii,jperryhouts/dealii,andreamola/dealii,Arezou-gh/dealii,lpolster/dealii,lue/dealii,ESeNonFossiIo/dealii,naliboff/dealii,adamkosik/dealii,EGP-CIG-REU/dealii,johntfoster/dealii,ESeNonFossiIo/dealii,angelrca/dealii,gpitton/dealii,rrgrove6/dealii,rrgrove6/dealii,EGP-CIG-REU/dealii,EGP-CIG-REU/dealii,Arezou-gh/dealii,natashasharma/dealii,mac-a/dealii,pesser/dealii,angelrca/dealii,kalj/dealii,sriharisundar/dealii,shakirbsm/dealii,danshapero/dealii,Arezou-gh/dealii,ibkim11/dealii,natashasharma/dealii,sairajat/dealii,naliboff/dealii,maieneuro/dealii,mac-a/dealii,ESeNonFossiIo/dealii,pesser/dealii,sairajat/dealii,spco/dealii,nicolacavallini/dealii,sairajat/dealii,YongYang86/dealii,shakirbsm/dealii,JaeryunYim/dealii,shakirbsm/dealii,msteigemann/dealii,flow123d/dealii,msteigemann/dealii,JaeryunYim/dealii,lue/dealii,naliboff/dealii,ESeNonFossiIo/dealii,angelrca/dealii,maieneuro/dealii,sriharisundar/dealii,johntfoster/dealii,maieneuro/dealii,kalj/dealii,sairajat/dealii,shakirbsm/dealii,rrgrove6/dealii,mtezzele/dealii,jperryhouts/dealii,lue/dealii,ibkim11/dealii,pesser/dealii,adamkosik/dealii,ESeNonFossiIo/dealii,spco/dealii,msteigemann/dealii,ibkim11/dealii,flow123d/dealii,flow123d/dealii,danshapero/dealii,mtezzele/dealii,mtezzele/dealii,flow123d/dealii,EGP-CIG-REU/dealii,johntfoster/dealii,spco/dealii,Arezou-gh/dealii,rrgrove6/dealii,Arezou-gh/dealii,lue/dealii,JaeryunYim/dealii,spco/dealii,EGP-CIG-REU/dealii
4c8731f21e2d520b1b70970066b8668c9b9dac39
src/ofp/rpc/rpcconnectionstdio.cpp
src/ofp/rpc/rpcconnectionstdio.cpp
// Copyright (c) 2015-2018 William W. Fisher (at gmail dot com) // This file is distributed under the MIT License. #include "ofp/rpc/rpcconnectionstdio.h" #include "ofp/rpc/rpcevents.h" #include "ofp/sys/asio_utils.h" #include "ofp/sys/engine.h" #include "ofp/timestamp.h" using ofp::rpc::RpcConnectionStdio; OFP_BEGIN_IGNORE_GLOBAL_CONSTRUCTOR // For `OFP.MESSAGE` notification event. static const llvm::StringRef kMsgPrefix{"{\"params\":", 10}; static const llvm::StringRef kMsgSuffix{",\"method\":\"OFP.MESSAGE\"}", 24}; OFP_END_IGNORE_GLOBAL_CONSTRUCTOR RpcConnectionStdio::RpcConnectionStdio(RpcServer *server, asio::posix::stream_descriptor input, asio::posix::stream_descriptor output, bool binaryProtocol) : RpcConnection{server}, input_{std::move(input)}, output_{std::move(output)}, streambuf_{RPC_MAX_MESSAGE_SIZE}, binaryProtocol_{binaryProtocol} {} void RpcConnectionStdio::writeEvent(llvm::StringRef msg, bool ofp_message) { ++txEvents_; size_t msgSize = ofp_message ? msg.size() + 34 : msg.size(); txBytes_ += msgSize; // TODO(bfish): Make sure the outgoing message doesn't exceed MAX msg size. if (binaryProtocol_) { // Add binary header. Big32 hdr = UInt32_narrow_cast((msgSize << 8) | RPC_EVENT_BINARY_TAG); outgoing_[outgoingIdx_].add(&hdr, sizeof(hdr)); } if (ofp_message) { outgoing_[outgoingIdx_].add(kMsgPrefix.data(), kMsgPrefix.size()); outgoing_[outgoingIdx_].add(msg.data(), msg.size()); outgoing_[outgoingIdx_].add(kMsgSuffix.data(), kMsgSuffix.size()); } else { outgoing_[outgoingIdx_].add(msg.data(), msg.size()); } if (!binaryProtocol_) { const UInt8 delimiter = RPC_EVENT_DELIMITER_CHAR; outgoing_[outgoingIdx_].add(&delimiter, sizeof(delimiter)); } if (!writing_) { asyncWrite(); } } void RpcConnectionStdio::close() { input_.close(); output_.close(); } void RpcConnectionStdio::asyncAccept() { // Start first async read. if (binaryProtocol_) { asyncReadHeader(); } else { asyncReadLine(); } // Start optional metrics timer. Milliseconds metricInterval = server_->metricInterval(); if (metricInterval != 0_ms) { asyncMetrics(metricInterval); } } void RpcConnectionStdio::asyncReadLine() { auto self(shared_from_this()); asio::async_read_until( input_, streambuf_, RPC_EVENT_DELIMITER_CHAR, [this, self](const asio::error_code &err, size_t bytes_transferred) { if (!err) { std::istream is(&streambuf_); std::string line; std::getline(is, line, RPC_EVENT_DELIMITER_CHAR); log::trace_rpc("Read RPC", 0, line.data(), line.size()); handleEvent(line); asyncReadLine(); } else if (err == asio::error::not_found) { // Input line is too big. Send back an error message then allow // connection to close. log_error("RpcConnectionStdio::asyncReadLine: input too large", RPC_MAX_MESSAGE_SIZE, err); rpcRequestInvalid("RPC request is too big"); } else if (err == asio::error::eof) { // Log warning if there are unread bytes in the buffer. auto bytesUnread = streambuf_.size(); if (bytesUnread > 0) { log_warning( "RpcConnectionStdio::asyncReadLine: unread bytes at eof", bytesUnread); } } else if (err != asio::error::operation_aborted) { // Some error other than operation_aborted occurred. Log the // error then allow connection to close. log_error("RpcConnectionStdio::asyncReadLine error", err); } }); } void RpcConnectionStdio::asyncReadHeader() { auto self(this->shared_from_this()); asio::async_read( input_, asio::buffer(&hdrBuf_, sizeof(hdrBuf_)), make_custom_alloc_handler( allocator_, [this, self](const asio::error_code &err, size_t length) { log_debug("rpc::asyncReadHeader callback", err); if (!err) { assert(length == sizeof(hdrBuf_)); UInt32 tagLen = hdrBuf_; UInt8 tag = tagLen & 0x00FFu; UInt32 len = (tagLen >> 8); if (tag != RPC_EVENT_BINARY_TAG) { log_error("RPC invalid header:", UInt32_cast(tag)); rpcRequestInvalid("RPC invalid header"); } else if (len > RPC_MAX_MESSAGE_SIZE) { log_error("RPC request is too big:", len); rpcRequestInvalid("RPC request is too big"); } else { asyncReadMessage(len); } } else { assert(err); log_error("RPC readHeader error", err); } })); } void RpcConnectionStdio::asyncReadMessage(size_t msgLength) { auto self(this->shared_from_this()); log_debug("rpc::asyncReadMessage:", msgLength, "bytes"); eventBuf_.resize(msgLength); asio::async_read( input_, asio::buffer(eventBuf_), make_custom_alloc_handler( allocator_, [this, self](const asio::error_code &err, size_t length) { log_debug("rpc::asyncReadMessage callback", err, length); if (!err) { // assert(length == msgLength); assert(eventBuf_.size() == length); log::trace_rpc("Read RPC", 0, eventBuf_.data(), eventBuf_.size()); handleEvent(eventBuf_); asyncReadHeader(); } else { assert(err); log_error("RPC readMessage error", err); } })); } void RpcConnectionStdio::asyncWrite() { assert(!writing_); int idx = outgoingIdx_; outgoingIdx_ = !outgoingIdx_; writing_ = true; const UInt8 *data = outgoing_[idx].data(); size_t size = outgoing_[idx].size(); auto self(shared_from_this()); log::trace_rpc("Write RPC", 0, data, size); asio::async_write( output_, asio::buffer(data, size), [this, self](const asio::error_code &err, size_t bytes_transferred) { if (!err) { assert(bytes_transferred == outgoing_[!outgoingIdx_].size()); writing_ = false; outgoing_[!outgoingIdx_].clear(); if (!outgoing_[outgoingIdx_].empty()) { // Start another async write for the other output buffer. asyncWrite(); } } }); }
// Copyright (c) 2015-2018 William W. Fisher (at gmail dot com) // This file is distributed under the MIT License. #include "ofp/rpc/rpcconnectionstdio.h" #include "ofp/rpc/rpcevents.h" #include "ofp/sys/asio_utils.h" #include "ofp/sys/engine.h" #include "ofp/timestamp.h" using ofp::rpc::RpcConnectionStdio; // For `OFP.MESSAGE` notification event. constexpr llvm::StringLiteral kMsgPrefix{"{\"params\":"}; constexpr llvm::StringLiteral kMsgSuffix{",\"method\":\"OFP.MESSAGE\"}"}; RpcConnectionStdio::RpcConnectionStdio(RpcServer *server, asio::posix::stream_descriptor input, asio::posix::stream_descriptor output, bool binaryProtocol) : RpcConnection{server}, input_{std::move(input)}, output_{std::move(output)}, streambuf_{RPC_MAX_MESSAGE_SIZE}, binaryProtocol_{binaryProtocol} {} void RpcConnectionStdio::writeEvent(llvm::StringRef msg, bool ofp_message) { ++txEvents_; size_t msgSize = ofp_message ? msg.size() + 34 : msg.size(); txBytes_ += msgSize; // TODO(bfish): Make sure the outgoing message doesn't exceed MAX msg size. if (binaryProtocol_) { // Add binary header. Big32 hdr = UInt32_narrow_cast((msgSize << 8) | RPC_EVENT_BINARY_TAG); outgoing_[outgoingIdx_].add(&hdr, sizeof(hdr)); } if (ofp_message) { outgoing_[outgoingIdx_].add(kMsgPrefix.data(), kMsgPrefix.size()); outgoing_[outgoingIdx_].add(msg.data(), msg.size()); outgoing_[outgoingIdx_].add(kMsgSuffix.data(), kMsgSuffix.size()); } else { outgoing_[outgoingIdx_].add(msg.data(), msg.size()); } if (!binaryProtocol_) { const UInt8 delimiter = RPC_EVENT_DELIMITER_CHAR; outgoing_[outgoingIdx_].add(&delimiter, sizeof(delimiter)); } if (!writing_) { asyncWrite(); } } void RpcConnectionStdio::close() { input_.close(); output_.close(); } void RpcConnectionStdio::asyncAccept() { // Start first async read. if (binaryProtocol_) { asyncReadHeader(); } else { asyncReadLine(); } // Start optional metrics timer. Milliseconds metricInterval = server_->metricInterval(); if (metricInterval != 0_ms) { asyncMetrics(metricInterval); } } void RpcConnectionStdio::asyncReadLine() { auto self(shared_from_this()); asio::async_read_until( input_, streambuf_, RPC_EVENT_DELIMITER_CHAR, [this, self](const asio::error_code &err, size_t bytes_transferred) { if (!err) { std::istream is(&streambuf_); std::string line; std::getline(is, line, RPC_EVENT_DELIMITER_CHAR); log::trace_rpc("Read RPC", 0, line.data(), line.size()); handleEvent(line); asyncReadLine(); } else if (err == asio::error::not_found) { // Input line is too big. Send back an error message then allow // connection to close. log_error("RpcConnectionStdio::asyncReadLine: input too large", RPC_MAX_MESSAGE_SIZE, err); rpcRequestInvalid("RPC request is too big"); } else if (err == asio::error::eof) { // Log warning if there are unread bytes in the buffer. auto bytesUnread = streambuf_.size(); if (bytesUnread > 0) { log_warning( "RpcConnectionStdio::asyncReadLine: unread bytes at eof", bytesUnread); } } else if (err != asio::error::operation_aborted) { // Some error other than operation_aborted occurred. Log the // error then allow connection to close. log_error("RpcConnectionStdio::asyncReadLine error", err); } }); } void RpcConnectionStdio::asyncReadHeader() { auto self(this->shared_from_this()); asio::async_read( input_, asio::buffer(&hdrBuf_, sizeof(hdrBuf_)), make_custom_alloc_handler( allocator_, [this, self](const asio::error_code &err, size_t length) { log_debug("rpc::asyncReadHeader callback", err); if (!err) { assert(length == sizeof(hdrBuf_)); UInt32 tagLen = hdrBuf_; UInt8 tag = tagLen & 0x00FFu; UInt32 len = (tagLen >> 8); if (tag != RPC_EVENT_BINARY_TAG) { log_error("RPC invalid header:", UInt32_cast(tag)); rpcRequestInvalid("RPC invalid header"); } else if (len > RPC_MAX_MESSAGE_SIZE) { log_error("RPC request is too big:", len); rpcRequestInvalid("RPC request is too big"); } else { asyncReadMessage(len); } } else { assert(err); log_error("RPC readHeader error", err); } })); } void RpcConnectionStdio::asyncReadMessage(size_t msgLength) { auto self(this->shared_from_this()); log_debug("rpc::asyncReadMessage:", msgLength, "bytes"); eventBuf_.resize(msgLength); asio::async_read( input_, asio::buffer(eventBuf_), make_custom_alloc_handler( allocator_, [this, self](const asio::error_code &err, size_t length) { log_debug("rpc::asyncReadMessage callback", err, length); if (!err) { // assert(length == msgLength); assert(eventBuf_.size() == length); log::trace_rpc("Read RPC", 0, eventBuf_.data(), eventBuf_.size()); handleEvent(eventBuf_); asyncReadHeader(); } else { assert(err); log_error("RPC readMessage error", err); } })); } void RpcConnectionStdio::asyncWrite() { assert(!writing_); int idx = outgoingIdx_; outgoingIdx_ = !outgoingIdx_; writing_ = true; const UInt8 *data = outgoing_[idx].data(); size_t size = outgoing_[idx].size(); auto self(shared_from_this()); log::trace_rpc("Write RPC", 0, data, size); asio::async_write( output_, asio::buffer(data, size), [this, self](const asio::error_code &err, size_t bytes_transferred) { if (!err) { assert(bytes_transferred == outgoing_[!outgoingIdx_].size()); writing_ = false; outgoing_[!outgoingIdx_].clear(); if (!outgoing_[outgoingIdx_].empty()) { // Start another async write for the other output buffer. asyncWrite(); } } }); }
Use llvm::StringLiteral.
Use llvm::StringLiteral.
C++
mit
byllyfish/libofp,byllyfish/libofp,byllyfish/oftr,byllyfish/oftr,byllyfish/libofp,byllyfish/oftr,byllyfish/oftr,byllyfish/oftr
e8d59212969569209cb29a86fbc70641a8e2182e
lib/sanitizer_common/sanitizer_symbolizer_mac.cc
lib/sanitizer_common/sanitizer_symbolizer_mac.cc
//===-- sanitizer_symbolizer_mac.cc ---------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is shared between various sanitizers' runtime libraries. // // Implementation of Mac-specific "atos" symbolizer. //===----------------------------------------------------------------------===// #include "sanitizer_platform.h" #if SANITIZER_MAC #include "sanitizer_allocator_internal.h" #include "sanitizer_mac.h" #include "sanitizer_symbolizer_mac.h" namespace __sanitizer { #include <dlfcn.h> #include <errno.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> #include <util.h> bool DlAddrSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) { Dl_info info; int result = dladdr((const void *)addr, &info); if (!result) return false; const char *demangled = DemangleCXXABI(info.dli_sname); stack->info.function = demangled ? internal_strdup(demangled) : nullptr; return true; } bool DlAddrSymbolizer::SymbolizeData(uptr addr, DataInfo *datainfo) { Dl_info info; int result = dladdr((const void *)addr, &info); if (!result) return false; const char *demangled = DemangleCXXABI(info.dli_sname); datainfo->name = internal_strdup(demangled); datainfo->start = (uptr)info.dli_saddr; return true; } class AtosSymbolizerProcess : public SymbolizerProcess { public: explicit AtosSymbolizerProcess(const char *path, pid_t parent_pid) : SymbolizerProcess(path, /*use_forkpty*/ true) { // Put the string command line argument in the object so that it outlives // the call to GetArgV. internal_snprintf(pid_str_, sizeof(pid_str_), "%d", parent_pid); } private: bool ReachedEndOfOutput(const char *buffer, uptr length) const override { return (length >= 1 && buffer[length - 1] == '\n'); } void GetArgV(const char *path_to_binary, const char *(&argv)[kArgVMax]) const override { int i = 0; argv[i++] = path_to_binary; argv[i++] = "-p"; argv[i++] = &pid_str_[0]; if (GetMacosVersion() == MACOS_VERSION_MAVERICKS) { // On Mavericks atos prints a deprecation warning which we suppress by // passing -d. The warning isn't present on other OSX versions, even the // newer ones. argv[i++] = "-d"; } argv[i++] = nullptr; } char pid_str_[16]; }; static const char *kAtosErrorMessages[] = { "atos cannot examine process", "unable to get permission to examine process", "An admin user name and password is required", "could not load inserted library", "architecture mismatch between analysis process", }; static bool IsAtosErrorMessage(const char *str) { for (uptr i = 0; i < ARRAY_SIZE(kAtosErrorMessages); i++) { if (internal_strstr(str, kAtosErrorMessages[i])) { return true; } } return false; } static bool ParseCommandOutput(const char *str, uptr addr, char **out_name, char **out_module, char **out_file, uptr *line, uptr *start_address) { // Trim ending newlines. char *trim; ExtractTokenUpToDelimiter(str, "\n", &trim); // The line from `atos` is in one of these formats: // myfunction (in library.dylib) (sourcefile.c:17) // myfunction (in library.dylib) + 0x1fe // myfunction (in library.dylib) + 15 // 0xdeadbeef (in library.dylib) + 0x1fe // 0xdeadbeef (in library.dylib) + 15 // 0xdeadbeef (in library.dylib) // 0xdeadbeef if (IsAtosErrorMessage(trim)) { Report("atos returned an error: %s\n", trim); InternalFree(trim); return false; } const char *rest = trim; char *symbol_name; rest = ExtractTokenUpToDelimiter(rest, " (in ", &symbol_name); if (rest[0] == '\0') { InternalFree(symbol_name); InternalFree(trim); return false; } if (internal_strncmp(symbol_name, "0x", 2) != 0) *out_name = symbol_name; else InternalFree(symbol_name); rest = ExtractTokenUpToDelimiter(rest, ") ", out_module); if (rest[0] == '(') { if (out_file) { rest++; rest = ExtractTokenUpToDelimiter(rest, ":", out_file); char *extracted_line_number; rest = ExtractTokenUpToDelimiter(rest, ")", &extracted_line_number); if (line) *line = (uptr)internal_atoll(extracted_line_number); InternalFree(extracted_line_number); } } else if (rest[0] == '+') { rest += 2; uptr offset = internal_atoll(rest); if (start_address) *start_address = addr - offset; } InternalFree(trim); return true; } AtosSymbolizer::AtosSymbolizer(const char *path, LowLevelAllocator *allocator) : process_(new(*allocator) AtosSymbolizerProcess(path, getpid())) {} bool AtosSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) { if (!process_) return false; char command[32]; internal_snprintf(command, sizeof(command), "0x%zx\n", addr); const char *buf = process_->SendCommand(command); if (!buf) return false; uptr line; if (!ParseCommandOutput(buf, addr, &stack->info.function, &stack->info.module, &stack->info.file, &line, nullptr)) { process_ = nullptr; return false; } stack->info.line = (int)line; return true; } bool AtosSymbolizer::SymbolizeData(uptr addr, DataInfo *info) { if (!process_) return false; char command[32]; internal_snprintf(command, sizeof(command), "0x%zx\n", addr); const char *buf = process_->SendCommand(command); if (!buf) return false; if (!ParseCommandOutput(buf, addr, &info->name, &info->module, nullptr, nullptr, &info->start)) { process_ = nullptr; return false; } return true; } } // namespace __sanitizer #endif // SANITIZER_MAC
//===-- sanitizer_symbolizer_mac.cc ---------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is shared between various sanitizers' runtime libraries. // // Implementation of Mac-specific "atos" symbolizer. //===----------------------------------------------------------------------===// #include "sanitizer_platform.h" #if SANITIZER_MAC #include "sanitizer_allocator_internal.h" #include "sanitizer_mac.h" #include "sanitizer_symbolizer_mac.h" namespace __sanitizer { #include <dlfcn.h> #include <errno.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> #include <util.h> bool DlAddrSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) { Dl_info info; int result = dladdr((const void *)addr, &info); if (!result) return false; const char *demangled = DemangleCXXABI(info.dli_sname); stack->info.function = demangled ? internal_strdup(demangled) : nullptr; return true; } bool DlAddrSymbolizer::SymbolizeData(uptr addr, DataInfo *datainfo) { Dl_info info; int result = dladdr((const void *)addr, &info); if (!result) return false; const char *demangled = DemangleCXXABI(info.dli_sname); datainfo->name = internal_strdup(demangled); datainfo->start = (uptr)info.dli_saddr; return true; } class AtosSymbolizerProcess : public SymbolizerProcess { public: explicit AtosSymbolizerProcess(const char *path, pid_t parent_pid) : SymbolizerProcess(path, /*use_forkpty*/ true) { // Put the string command line argument in the object so that it outlives // the call to GetArgV. internal_snprintf(pid_str_, sizeof(pid_str_), "%d", parent_pid); } private: bool ReachedEndOfOutput(const char *buffer, uptr length) const override { return (length >= 1 && buffer[length - 1] == '\n'); } void GetArgV(const char *path_to_binary, const char *(&argv)[kArgVMax]) const override { int i = 0; argv[i++] = path_to_binary; argv[i++] = "-p"; argv[i++] = &pid_str_[0]; if (GetMacosVersion() == MACOS_VERSION_MAVERICKS) { // On Mavericks atos prints a deprecation warning which we suppress by // passing -d. The warning isn't present on other OSX versions, even the // newer ones. argv[i++] = "-d"; } argv[i++] = nullptr; } char pid_str_[16]; }; static const char *kAtosErrorMessages[] = { "atos cannot examine process", "unable to get permission to examine process", "An admin user name and password is required", "could not load inserted library", "architecture mismatch between analysis process", }; static bool IsAtosErrorMessage(const char *str) { for (uptr i = 0; i < ARRAY_SIZE(kAtosErrorMessages); i++) { if (internal_strstr(str, kAtosErrorMessages[i])) { return true; } } return false; } static bool ParseCommandOutput(const char *str, uptr addr, char **out_name, char **out_module, char **out_file, uptr *line, uptr *start_address) { // Trim ending newlines. char *trim; ExtractTokenUpToDelimiter(str, "\n", &trim); // The line from `atos` is in one of these formats: // myfunction (in library.dylib) (sourcefile.c:17) // myfunction (in library.dylib) + 0x1fe // myfunction (in library.dylib) + 15 // 0xdeadbeef (in library.dylib) + 0x1fe // 0xdeadbeef (in library.dylib) + 15 // 0xdeadbeef (in library.dylib) // 0xdeadbeef if (IsAtosErrorMessage(trim)) { Report("atos returned an error: %s\n", trim); InternalFree(trim); return false; } const char *rest = trim; char *symbol_name; rest = ExtractTokenUpToDelimiter(rest, " (in ", &symbol_name); if (rest[0] == '\0') { InternalFree(symbol_name); InternalFree(trim); return false; } if (internal_strncmp(symbol_name, "0x", 2) != 0) *out_name = symbol_name; else InternalFree(symbol_name); rest = ExtractTokenUpToDelimiter(rest, ") ", out_module); if (rest[0] == '(') { if (out_file) { rest++; rest = ExtractTokenUpToDelimiter(rest, ":", out_file); char *extracted_line_number; rest = ExtractTokenUpToDelimiter(rest, ")", &extracted_line_number); if (line) *line = (uptr)internal_atoll(extracted_line_number); InternalFree(extracted_line_number); } } else if (rest[0] == '+') { rest += 2; uptr offset = internal_atoll(rest); if (start_address) *start_address = addr - offset; } InternalFree(trim); return true; } AtosSymbolizer::AtosSymbolizer(const char *path, LowLevelAllocator *allocator) : process_(new(*allocator) AtosSymbolizerProcess(path, getpid())) {} bool AtosSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) { if (!process_) return false; if (addr == 0) return false; char command[32]; internal_snprintf(command, sizeof(command), "0x%zx\n", addr); const char *buf = process_->SendCommand(command); if (!buf) return false; uptr line; if (!ParseCommandOutput(buf, addr, &stack->info.function, &stack->info.module, &stack->info.file, &line, nullptr)) { process_ = nullptr; return false; } stack->info.line = (int)line; return true; } bool AtosSymbolizer::SymbolizeData(uptr addr, DataInfo *info) { if (!process_) return false; char command[32]; internal_snprintf(command, sizeof(command), "0x%zx\n", addr); const char *buf = process_->SendCommand(command); if (!buf) return false; if (!ParseCommandOutput(buf, addr, &info->name, &info->module, nullptr, nullptr, &info->start)) { process_ = nullptr; return false; } return true; } } // namespace __sanitizer #endif // SANITIZER_MAC
Make AtosSymbolizer more resilient when symbolicating a zero address
[sanitizer] Make AtosSymbolizer more resilient when symbolicating a zero address git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@265269 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
84f3c56016c6c6f992e21afec3361644b1621710
call/version.cc
call/version.cc
/* * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "call/version.h" namespace webrtc { // The timestamp is always in UTC. const char* const kSourceTimestamp = "WebRTC source stamp 2020-12-25T04:04:51"; void LoadWebRTCVersionInRegister() { // Using volatile to instruct the compiler to not optimize `p` away even // if it looks unused. const char* volatile p = kSourceTimestamp; static_cast<void>(p); } } // namespace webrtc
/* * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "call/version.h" namespace webrtc { // The timestamp is always in UTC. const char* const kSourceTimestamp = "WebRTC source stamp 2020-12-27T04:03:22"; void LoadWebRTCVersionInRegister() { // Using volatile to instruct the compiler to not optimize `p` away even // if it looks unused. const char* volatile p = kSourceTimestamp; static_cast<void>(p); } } // namespace webrtc
Update WebRTC code version (2020-12-27T04:03:22).
Update WebRTC code version (2020-12-27T04:03:22). TBR=26646219319870ca9d01017a011e960429912aaa@webrtc-ci.iam.gserviceaccount.com,[email protected] Bug: None Change-Id: I02e4f440f9cf8f4e68ec5b2aa7923ded8c9d34d4 Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/199381 Reviewed-by: 26646219319870ca9d01017a011e960429912aaa@webrtc-ci.iam.gserviceaccount.com <26646219319870ca9d01017a011e960429912aaa@webrtc-ci.iam.gserviceaccount.com> Commit-Queue: 26646219319870ca9d01017a011e960429912aaa@webrtc-ci.iam.gserviceaccount.com <26646219319870ca9d01017a011e960429912aaa@webrtc-ci.iam.gserviceaccount.com> Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#32882}
C++
bsd-3-clause
TimothyGu/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,TimothyGu/libilbc
61f3e69cd14ae37cb0966cda4b21620978131190
main/src/PolygonTriangularization/poly_triang.cc
main/src/PolygonTriangularization/poly_triang.cc
#include "poly_triang.hh" #include "Utils/statistics.hh" #include "circular.hh" #include "Geo/linear_system.hh" #include "Geo/area.hh" #include <numeric> struct PolygonFilImpl : public PolygonFil { void init(const std::vector<Geo::Vector3>& _plgn); virtual const std::vector<std::array<size_t, 3>>& triangles() const { return sol_.tris_; } virtual const std::vector<Geo::Vector3>& positions() const { return pts_; } virtual double area_compute() const { return sol_.area_; } private: struct Solution { void compute(const std::vector<Geo::Vector3>& _pos); bool concave(size_t _i) const { return _i < concav_.size() && concav_[_i]; } bool contain_concave(size_t _inds[3], Geo::Vector3 _vects[2], const std::vector<Geo::Vector3>& _pts) const; bool find_concave(const std::vector<Geo::Vector3>& _pts, std::vector<bool>& _concav) const; std::vector<std::array<size_t, 3>> tris_; double area_ = 0; std::vector<bool> concav_; std::vector<size_t> indcs_; }; std::vector<Geo::Vector3> pts_; Solution sol_; }; std::shared_ptr<PolygonFil> PolygonFil::make() { return std::make_shared<PolygonFilImpl>(); } void PolygonFilImpl::init(const std::vector<Geo::Vector3>& _plgn) { pts_ = _plgn; sol_.compute(_plgn); Solution sol; if (sol_.find_concave(_plgn, sol.concav_)) sol.compute(_plgn); if (sol.area_ < sol_.area_) sol_ = sol; } void PolygonFilImpl::Solution::compute( const std::vector<Geo::Vector3>& _pts) { indcs_.resize(_pts.size()); std::iota(indcs_.begin(), indcs_.end(), 0); for (;;) { if (indcs_.size() < 3) break; Geo::Vector3 vects[2]; size_t inds[3] = { *(indcs_.end() - 2), indcs_.back(), 0 }; vects[0] = _pts[inds[0]] - _pts[inds[1]]; Utils::StatisticsT<double> min_ang; for (size_t i = 0; i < indcs_.size(); ++i) { inds[2] = indcs_[i]; if (!concave(inds[1])) { vects[1] = _pts[inds[2]] - _pts[inds[1]]; if (!contain_concave(inds, vects, _pts)) { auto angl = Geo::angle(vects[0], vects[1]); min_ang.add(angl, i); } } inds[0] = inds[1]; inds[1] = inds[2]; vects[0] = -vects[1]; } auto idx = min_ang.min_idx(); auto decrease = [this](size_t& _idx) { if (_idx == 0) _idx = indcs_.size(); return --_idx; }; std::array<size_t, 3> tri; tri[2] = indcs_[idx]; tri[1] = indcs_[Circular::decrease(idx, indcs_.size())]; indcs_.erase(indcs_.begin() + idx); tri[0] = indcs_[Circular::decrease(idx, indcs_.size())]; if (min_ang.min() > 0) tris_.push_back(tri); } area_ = 0.; for (const auto& tri : tris_) area_ += Geo::area_compute(_pts[tri[0]], _pts[tri[1]], _pts[tri[2]]); } namespace { // return 0 - outside, 1 - on boundary, 2 - inside size_t inside_triangle( const Geo::Vector3 _vert[2], const Geo::Vector3& _test_pt) { double A[2][2], B[2], X[2]; for (int i = 0; i < 2; ++i) { for (int j = i; j < 2; ++j) A[i][j] = A[j][i] = _vert[i] * _vert[j]; B[i] = _vert[i] * _test_pt; } if (!Geo::solve_2x2(A, X, B)) return 0; size_t result = 0; if (X[0] >= 0 && X[1] >= 0 && (X[0] + X[1]) <= 1) { ++result; if (X[0] > 0 && X[1] > 0 && (X[0] + X[1]) < 1) ++result; } return result; } size_t inside_triangle(const Geo::Vector3& _pt, const Geo::Vector3& _vrt0, const Geo::Vector3& _vrt1, const Geo::Vector3& _vrt2 ) { const Geo::Vector3 verts[2] = { _vrt1 - _vrt0, _vrt2 - _vrt0 }; return inside_triangle(verts, _pt - _vrt0); } } bool PolygonFilImpl::Solution::find_concave( const std::vector<Geo::Vector3>& _pts, std::vector<bool>& _concav) const { bool achange = false; _concav.resize(_pts.size()); for (size_t i = 0; i < _pts.size(); ++i) { _concav[i] = concave(i); size_t inside = 0; for (const auto& tri : tris_) { if (std::find(tri.begin(), tri.end(), i) != tri.end()) continue; inside += inside_triangle( _pts[i], _pts[tri[0]], _pts[tri[1]], _pts[tri[2]]); if (inside > 1) { _concav[i] = !_concav[i]; achange = true; break; } } } return achange; } bool PolygonFilImpl::Solution::contain_concave( size_t _inds[3], Geo::Vector3 _vects[2], const std::vector<Geo::Vector3>& _pts) const { for (auto i = 0; i < concav_.size(); ++i) { if (i == _inds[0] || i == _inds[2] || !concav_[i]) continue; if (inside_triangle(_vects, _pts[i] - _pts[_inds[1]])) return true; } return false; }
#include "poly_triang.hh" #include "Utils/statistics.hh" #include "circular.hh" #include "Geo/linear_system.hh" #include "Geo/area.hh" #include <numeric> struct PolygonFilImpl : public PolygonFil { void init(const std::vector<Geo::Vector3>& _plgn); virtual const std::vector<std::array<size_t, 3>>& triangles() const { return sol_.tris_; } virtual const std::vector<Geo::Vector3>& positions() const { return pts_; } virtual double area_compute() const { return sol_.area_; } private: struct Solution { void compute(const std::vector<Geo::Vector3>& _pos); bool concave(size_t _i) const { return _i < concav_.size() && concav_[_i]; } bool contain_concave(size_t _inds[3], Geo::Vector3 _vects[2], const std::vector<Geo::Vector3>& _pts) const; bool find_concave(const std::vector<Geo::Vector3>& _pts, std::vector<bool>& _concav) const; std::vector<std::array<size_t, 3>> tris_; double area_ = 0; std::vector<bool> concav_; std::vector<size_t> indcs_; }; std::vector<Geo::Vector3> pts_; Solution sol_; }; std::shared_ptr<PolygonFil> PolygonFil::make() { return std::make_shared<PolygonFilImpl>(); } void PolygonFilImpl::init(const std::vector<Geo::Vector3>& _plgn) { pts_ = _plgn; sol_.compute(_plgn); Solution sol; if (sol_.find_concave(_plgn, sol.concav_)) { sol.compute(_plgn); if (sol.area_ < sol_.area_) sol_ = sol; } } void PolygonFilImpl::Solution::compute( const std::vector<Geo::Vector3>& _pts) { indcs_.resize(_pts.size()); std::iota(indcs_.begin(), indcs_.end(), 0); for (;;) { if (indcs_.size() < 3) break; Geo::Vector3 vects[2]; size_t inds[3] = { *(indcs_.end() - 2), indcs_.back(), 0 }; vects[0] = _pts[inds[0]] - _pts[inds[1]]; Utils::StatisticsT<double> min_ang; for (size_t i = 0; i < indcs_.size(); ++i) { inds[2] = indcs_[i]; if (!concave(inds[1])) { vects[1] = _pts[inds[2]] - _pts[inds[1]]; if (!contain_concave(inds, vects, _pts)) { auto angl = Geo::angle(vects[0], vects[1]); min_ang.add(angl, i); } } inds[0] = inds[1]; inds[1] = inds[2]; vects[0] = -vects[1]; } auto idx = min_ang.min_idx(); auto decrease = [this](size_t& _idx) { if (_idx == 0) _idx = indcs_.size(); return --_idx; }; std::array<size_t, 3> tri; tri[2] = indcs_[idx]; tri[1] = indcs_[Circular::decrease(idx, indcs_.size())]; indcs_.erase(indcs_.begin() + idx); tri[0] = indcs_[Circular::decrease(idx, indcs_.size())]; if (min_ang.min() > 0) tris_.push_back(tri); } area_ = 0.; for (const auto& tri : tris_) area_ += Geo::area_compute(_pts[tri[0]], _pts[tri[1]], _pts[tri[2]]); } namespace { // return 0 - outside, 1 - on boundary, 2 - inside size_t inside_triangle( const Geo::Vector3 _vert[2], const Geo::Vector3& _test_pt) { double A[2][2], B[2], X[2]; for (int i = 0; i < 2; ++i) { for (int j = i; j < 2; ++j) A[i][j] = A[j][i] = _vert[i] * _vert[j]; B[i] = _vert[i] * _test_pt; } if (!Geo::solve_2x2(A, X, B)) return 0; size_t result = 0; if (X[0] >= 0 && X[1] >= 0 && (X[0] + X[1]) <= 1) { ++result; if (X[0] > 0 && X[1] > 0 && (X[0] + X[1]) < 1) ++result; } return result; } size_t inside_triangle(const Geo::Vector3& _pt, const Geo::Vector3& _vrt0, const Geo::Vector3& _vrt1, const Geo::Vector3& _vrt2 ) { const Geo::Vector3 verts[2] = { _vrt1 - _vrt0, _vrt2 - _vrt0 }; return inside_triangle(verts, _pt - _vrt0); } } bool PolygonFilImpl::Solution::find_concave( const std::vector<Geo::Vector3>& _pts, std::vector<bool>& _concav) const { bool achange = false; _concav.resize(_pts.size()); for (size_t i = 0; i < _pts.size(); ++i) { _concav[i] = concave(i); size_t inside = 0; for (const auto& tri : tris_) { if (std::find(tri.begin(), tri.end(), i) != tri.end()) continue; inside += inside_triangle( _pts[i], _pts[tri[0]], _pts[tri[1]], _pts[tri[2]]); if (inside > 1) { _concav[i] = !_concav[i]; achange = true; break; } } } return achange; } bool PolygonFilImpl::Solution::contain_concave( size_t _inds[3], Geo::Vector3 _vects[2], const std::vector<Geo::Vector3>& _pts) const { for (auto i = 0; i < concav_.size(); ++i) { if (i == _inds[0] || i == _inds[2] || !concav_[i]) continue; if (inside_triangle(_vects, _pts[i] - _pts[_inds[1]])) return true; } return false; }
Fix concave cases
Fix concave cases
C++
apache-2.0
marcomanno/polygon_triangulation,marcomanno/polygon_triangulation
30e09c264cf7bba0b30fcbfaf5b9f79a7eb351bc
akonadi/resources/kolabproxy/collectiontreebuilder.cpp
akonadi/resources/kolabproxy/collectiontreebuilder.cpp
/* Copyright (c) 2009 Volker Krause <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "collectiontreebuilder.h" #include <collectionannotationsattribute.h> #include <akonadi/collectionfetchjob.h> using namespace Akonadi; CollectionTreeBuilder::CollectionTreeBuilder(KolabProxyResource* parent) : Job( parent ), m_resource( parent ) { } void CollectionTreeBuilder::doStart() { CollectionFetchJob *job = new CollectionFetchJob( Collection::root(), CollectionFetchJob::Recursive, this ); connect(job, SIGNAL(collectionsReceived(Akonadi::Collection::List)), SLOT(collectionsReceived(Akonadi::Collection::List)) ); connect(job, SIGNAL(result(KJob*)), SLOT(collectionFetchResult(KJob*)) ); } void CollectionTreeBuilder::collectionsReceived(const Akonadi::Collection::List& collections) { foreach( const Collection &collection, collections ) { if ( collection.resource() == resource()->identifier() ) continue; if ( resource()->registerHandlerForCollection( collection ) ) { m_kolabCollections.append( collection ); } m_allCollections.insert( collection.id(), collection ); } } Collection::List CollectionTreeBuilder::allCollections() const { return m_resultCollections; } Collection::List CollectionTreeBuilder::treeToList( const QHash< Entity::Id, Collection::List > &tree, const Akonadi::Collection& current ) { Collection::List rv; foreach ( const Collection &child, tree.value( current.id() ) ) { rv += child; rv += treeToList( tree, child ); } return rv; } void CollectionTreeBuilder::collectionFetchResult(KJob* job) { m_resultCollections.clear(); // step 1: build the minimal sub-tree that contains all Kolab collections QHash<Collection::Id, Collection::List> remainingTree; foreach ( const Collection &kolabCollection, m_kolabCollections ) { Collection child = kolabCollection; Collection::Id parentId = child.parentCollection().id(); while ( child.isValid() && !remainingTree.value( parentId ).contains( child ) ) { remainingTree[ parentId ].append( child ); child = m_allCollections.value( parentId ); parentId = child.parentCollection().id(); } } // step 2: path contraction // TODO // step 3: flatten the tree and adjust root node foreach ( Collection topLevel, remainingTree.value( Collection::root().id() ) ) { //krazy:exclude=foreach topLevel.setParentCollection( resource()->root() ); m_resultCollections.append( topLevel ); m_resultCollections += treeToList( remainingTree, topLevel ); } emitResult(); // error handling already done by Akonadi::Job } #include "collectiontreebuilder.moc"
/* Copyright (c) 2009 Volker Krause <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "collectiontreebuilder.h" #include <collectionannotationsattribute.h> #include <akonadi/collectionfetchjob.h> using namespace Akonadi; CollectionTreeBuilder::CollectionTreeBuilder(KolabProxyResource* parent) : Job( parent ), m_resource( parent ) { } void CollectionTreeBuilder::doStart() { CollectionFetchJob *job = new CollectionFetchJob( Collection::root(), CollectionFetchJob::Recursive, this ); connect(job, SIGNAL(collectionsReceived(Akonadi::Collection::List)), SLOT(collectionsReceived(Akonadi::Collection::List)) ); connect(job, SIGNAL(result(KJob*)), SLOT(collectionFetchResult(KJob*)) ); } void CollectionTreeBuilder::collectionsReceived(const Akonadi::Collection::List& collections) { foreach( const Collection &collection, collections ) { if ( collection.resource() == resource()->identifier() ) continue; if ( resource()->registerHandlerForCollection( collection ) ) { m_kolabCollections.append( collection ); } m_allCollections.insert( collection.id(), collection ); } } Collection::List CollectionTreeBuilder::allCollections() const { return m_resultCollections; } Collection::List CollectionTreeBuilder::treeToList( const QHash< Entity::Id, Collection::List > &tree, const Akonadi::Collection& current ) { Collection::List rv; foreach ( const Collection &child, tree.value( current.id() ) ) { rv += child; rv += treeToList( tree, child ); } return rv; } void CollectionTreeBuilder::collectionFetchResult(KJob* job) { Q_UNUSED( job ); #warnig: what is the need of the unused parameter(s)? //TODO what is the need of the unused parameter(s)? m_resultCollections.clear(); // step 1: build the minimal sub-tree that contains all Kolab collections QHash<Collection::Id, Collection::List> remainingTree; foreach ( const Collection &kolabCollection, m_kolabCollections ) { Collection child = kolabCollection; Collection::Id parentId = child.parentCollection().id(); while ( child.isValid() && !remainingTree.value( parentId ).contains( child ) ) { remainingTree[ parentId ].append( child ); child = m_allCollections.value( parentId ); parentId = child.parentCollection().id(); } } // step 2: path contraction // TODO // step 3: flatten the tree and adjust root node foreach ( Collection topLevel, remainingTree.value( Collection::root().id() ) ) { //krazy:exclude=foreach topLevel.setParentCollection( resource()->root() ); m_resultCollections.append( topLevel ); m_resultCollections += treeToList( remainingTree, topLevel ); } emitResult(); // error handling already done by Akonadi::Job } #include "collectiontreebuilder.moc"
add some Q_UNUSED( )
add some Q_UNUSED( ) svn path=/trunk/KDE/kdepim/; revision=1052051
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
358962c46b854f26d32d254734e65690f2736448
src/player/XInputMTInputDevice.cpp
src/player/XInputMTInputDevice.cpp
// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "XInputMTInputDevice.h" #include "TouchEvent.h" #include "Player.h" #include "AVGNode.h" #include "TouchStatus.h" #include "SDLDisplayEngine.h" #include "../base/Logger.h" #include "../base/ObjectCounter.h" #include "../base/Exception.h" #include "../base/OSHelper.h" #include "../base/StringHelper.h" #include <SDL/SDL_syswm.h> #include <SDL/SDL.h> #include <X11/extensions/XInput.h> #include <X11/extensions/XInput2.h> using namespace std; namespace avg { Display* XInputMTInputDevice::s_pDisplay = 0; const char* cookieTypeToName(int evtype); string xEventTypeToName(int evtype); XInputMTInputDevice::XInputMTInputDevice() : m_LastID(0), m_DeviceID(-1) { } XInputMTInputDevice::~XInputMTInputDevice() { if (m_DeviceID != -1 && m_OldMasterDeviceID != -1) { XIAttachSlaveInfo atInfo; atInfo.type = XIAttachSlave; atInfo.deviceid = m_DeviceID; atInfo.new_master = m_OldMasterDeviceID; XIChangeHierarchy(s_pDisplay, (XIAnyHierarchyChangeInfo *)&atInfo, 1); } } void XInputMTInputDevice::start() { Status status; SDLDisplayEngine * pEngine = Player::get()->getDisplayEngine(); SDL_SysWMinfo info; SDL_VERSION(&info.version); int rc = SDL_GetWMInfo(&info); AVG_ASSERT(rc != -1); s_pDisplay = info.info.x11.display; m_SDLLockFunc = info.info.x11.lock_func; m_SDLUnlockFunc = info.info.x11.unlock_func; m_SDLLockFunc(); // XInput Extension available? int event, error; bool bOk = XQueryExtension(s_pDisplay, "XInputExtension", &m_XIOpcode, &event, &error); if (!bOk) { throw Exception(AVG_ERR_MT_INIT, "XInput multitouch event source: X Input extension not available."); } // Which version of XI2? int major; int minor; status = XIQueryVersion(s_pDisplay, &major, &minor); if (status == BadRequest) { throw Exception(AVG_ERR_MT_INIT, "XInput 2.1 multitouch event source: Server does not support XI2"); } if (major < 2 || minor < 1) { throw Exception(AVG_ERR_MT_INIT, "XInput multitouch event source: Supported version is " +toString(major)+"."+toString(minor)+". At least 2.1 is needed."); } findMTDevice(); // SDL grabs the pointer in full screen mode. This breaks touchscreen usage. // Can't use SDL_WM_GrabInput(SDL_GRAB_OFF) because it doesn't work in full // screen mode. Get the display connection and do it manually. XUngrabPointer(info.info.x11.display, CurrentTime); XIEventMask mask; mask.deviceid = m_DeviceID; mask.mask_len = XIMaskLen(XI_LASTEVENT); mask.mask = (unsigned char *)calloc(mask.mask_len, sizeof(char)); memset(mask.mask, 0, mask.mask_len); XISetMask(mask.mask, XI_TouchBegin); XISetMask(mask.mask, XI_TouchUpdate); XISetMask(mask.mask, XI_TouchEnd); status = XISelectEvents(s_pDisplay, info.info.x11.window, &mask, 1); AVG_ASSERT(status == Success); m_SDLUnlockFunc(); SDL_SetEventFilter(XInputMTInputDevice::filterEvent); XIDetachSlaveInfo detInfo; detInfo.type = XIDetachSlave; detInfo.deviceid = m_DeviceID; XIChangeHierarchy(s_pDisplay, (XIAnyHierarchyChangeInfo *)&detInfo, 1); pEngine->setXIMTInputDevice(this); MultitouchInputDevice::start(); AVG_TRACE(Logger::CONFIG, "XInput Multitouch event source created."); } void XInputMTInputDevice::handleXIEvent(const XEvent& xEvent) { m_SDLLockFunc(); XGenericEventCookie* pCookie = (XGenericEventCookie*)&xEvent.xcookie; if (pCookie->type == GenericEvent && pCookie->extension == m_XIOpcode) { XIDeviceEvent* pDevEvent = (XIDeviceEvent*)(pCookie->data); IntPoint pos(pDevEvent->event_x, pDevEvent->event_y); int xid = pDevEvent->detail; switch (pCookie->evtype) { case XI_TouchBegin: { // cerr << "TouchBegin " << xid << ", " << pos << endl; m_LastID++; TouchEventPtr pEvent = createEvent(m_LastID, Event::CURSOR_DOWN, pos); addTouchStatus(xid, pEvent); } break; case XI_TouchUpdate: { // cerr << "TouchUpdate " << xid << ", " << pos << endl; TouchEventPtr pEvent = createEvent(0, Event::CURSOR_MOTION, pos); TouchStatusPtr pTouchStatus = getTouchStatus(xid); AVG_ASSERT(pTouchStatus); pTouchStatus->pushEvent(pEvent); } break; case XI_TouchEnd: { // cerr << "TouchEnd " << xid << ", " << pos << endl; TouchStatusPtr pTouchStatus = getTouchStatus(xid); AVG_ASSERT(pTouchStatus); TouchEventPtr pEvent = createEvent(0, Event::CURSOR_UP, pos); pTouchStatus->pushEvent(pEvent); } break; default: ; // cerr << "Unhandled XInput event, type: " // << cookieTypeToName(pCookie->evtype) << endl; } } else { // cerr << "Unhandled X11 Event: " << xEvent.type << endl; } XFreeEventData(s_pDisplay, pCookie); m_SDLUnlockFunc(); } std::vector<EventPtr> XInputMTInputDevice::pollEvents() { return MultitouchInputDevice::pollEvents(); } void XInputMTInputDevice::findMTDevice() { int ndevices; XIDeviceInfo* pDevices; XIDeviceInfo* pDevice; pDevices = XIQueryDevice(s_pDisplay, XIAllDevices, &ndevices); XITouchClassInfo* pTouchClass = 0; int maxTouches; for (int i = 0; i < ndevices && !pTouchClass; ++i) { pDevice = &pDevices[i]; // cerr << "Device " << pDevice->name << "(id: " << pDevice->deviceid << ")." // << endl; if (pDevice->use == XISlavePointer || pDevice->use == XIFloatingSlave) { for (int j = 0; j < pDevice->num_classes; ++j) { XIAnyClassInfo * pClass = pDevice->classes[j]; if (pClass->type == XITouchClass) { XITouchClassInfo* pTempTouchClass = (XITouchClassInfo *)pClass; if (pTempTouchClass->mode == XIDirectTouch) { pTouchClass = pTempTouchClass; m_sDeviceName = pDevice->name; m_DeviceID = pDevice->deviceid; if (pDevice->use == XISlavePointer) { m_OldMasterDeviceID = pDevice->attachment; } else { m_OldMasterDeviceID = -1; } maxTouches = pTouchClass->num_touches; break; } } } } } if (pTouchClass) { AVG_TRACE(Logger::CONFIG, "Using multitouch input device " << m_sDeviceName << ", max touches: " << maxTouches); } else { throw Exception(AVG_ERR_MT_INIT, "XInput multitouch event source: No multitouch device found."); } XIFreeDeviceInfo(pDevices); } TouchEventPtr XInputMTInputDevice::createEvent(int id, Event::Type type, IntPoint pos) { return TouchEventPtr(new TouchEvent(id, type, pos, Event::TOUCH)); } int XInputMTInputDevice::filterEvent(const SDL_Event * pEvent) { // This is a hook into libsdl event processing. Since libsdl doesn't know about // XInput 2, it doesn't call XGetEventData either. By the time the event arrives // in handleXIEvent(), other events may have arrived and XGetEventData can't be // called anymore. Hence this function, which calls XGetEventData for each event // that has a cookie. if (pEvent->type == SDL_SYSWMEVENT) { SDL_SysWMmsg* pMsg = pEvent->syswm.msg; AVG_ASSERT(pMsg->subsystem == SDL_SYSWM_X11); XEvent* pXEvent = &pMsg->event.xevent; XGenericEventCookie* pCookie = (XGenericEventCookie*)&(pXEvent->xcookie); // cerr << "---- filter xinput event: " << xEventTypeToName(pXEvent->type) << ", " // << cookieTypeToName(pCookie->evtype) << endl; XGetEventData(s_pDisplay, pCookie); } else { // cerr << "---- filter: " << int(pEvent->type) << endl; } return 1; } // From xinput/test_xi2.c const char* cookieTypeToName(int evtype) { const char *name; switch(evtype) { case XI_DeviceChanged: name = "DeviceChanged"; break; case XI_KeyPress: name = "KeyPress"; break; case XI_KeyRelease: name = "KeyRelease"; break; case XI_ButtonPress: name = "ButtonPress"; break; case XI_ButtonRelease: name = "ButtonRelease"; break; case XI_Motion: name = "Motion"; break; case XI_Enter: name = "Enter"; break; case XI_Leave: name = "Leave"; break; case XI_FocusIn: name = "FocusIn"; break; case XI_FocusOut: name = "FocusOut"; break; case XI_HierarchyChanged: name = "HierarchyChanged"; break; case XI_PropertyEvent: name = "PropertyEvent"; break; case XI_RawKeyPress: name = "RawKeyPress"; break; case XI_RawKeyRelease: name = "RawKeyRelease"; break; case XI_RawButtonPress: name = "RawButtonPress"; break; case XI_RawButtonRelease: name = "RawButtonRelease"; break; case XI_RawMotion: name = "RawMotion"; break; case XI_TouchBegin: name = "TouchBegin"; break; case XI_TouchEnd: name = "TouchEnd"; break; case XI_TouchUpdate: name = "TouchUpdate"; break; #ifdef HAVE_XI2_1 case XI_TouchUpdateUnowned: name = "TouchUpdateUnowned"; break; #endif default: name = "unknown event type"; break; } return name; } string xEventTypeToName(int evtype) { switch(evtype) { case KeyPress: return "KeyPress"; case KeyRelease: return "KeyRelease"; case ButtonPress: return "ButtonPress"; case ButtonRelease: return "ButtonRelease"; case MotionNotify: return "MotionNotify"; case EnterNotify: return "EnterNotify"; case LeaveNotify: return "LeaveNotify"; case FocusIn: return "FocusIn"; case FocusOut: return "FocusOut"; case KeymapNotify: return "KeymapNotify"; case Expose: return "Expose"; case GraphicsExpose: return "GraphicsExpose"; case NoExpose: return "NoExpose"; case VisibilityNotify: return "VisibilityNotify"; case CreateNotify: return "CreateNotify"; case DestroyNotify: return "DestroyNotify"; case UnmapNotify: return "UnmapNotify"; case MapNotify: return "MapNotify"; case MapRequest: return "MapRequest"; case ReparentNotify: return "ReparentNotify"; case ConfigureNotify: return "ConfigureNotify"; case ConfigureRequest: return "ConfigureRequest"; case GravityNotify: return "GravityNotify"; case ResizeRequest: return "ResizeRequest"; case CirculateNotify: return "CirculateNotify"; case CirculateRequest: return "CirculateRequest"; case PropertyNotify: return "PropertyNotify"; case SelectionClear: return "SelectionClear"; case SelectionRequest: return "SelectionRequest"; case SelectionNotify: return "SelectionNotify"; case ColormapNotify: return "ColormapNotify"; case ClientMessage: return "ClientMessage"; case MappingNotify: return "MappingNotify"; case GenericEvent: return "GenericEvent"; default: return "Unknown event type"; } } }
// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "XInputMTInputDevice.h" #include "TouchEvent.h" #include "Player.h" #include "AVGNode.h" #include "TouchStatus.h" #include "SDLDisplayEngine.h" #include "../base/Logger.h" #include "../base/ObjectCounter.h" #include "../base/Exception.h" #include "../base/OSHelper.h" #include "../base/StringHelper.h" #include <SDL/SDL_syswm.h> #include <SDL/SDL.h> #include <X11/extensions/XInput.h> #include <X11/extensions/XInput2.h> using namespace std; namespace avg { Display* XInputMTInputDevice::s_pDisplay = 0; const char* cookieTypeToName(int evtype); string xEventTypeToName(int evtype); XInputMTInputDevice::XInputMTInputDevice() : m_LastID(0), m_DeviceID(-1) { } XInputMTInputDevice::~XInputMTInputDevice() { if (m_DeviceID != -1 && m_OldMasterDeviceID != -1) { XIAttachSlaveInfo atInfo; atInfo.type = XIAttachSlave; atInfo.deviceid = m_DeviceID; atInfo.new_master = m_OldMasterDeviceID; XIChangeHierarchy(s_pDisplay, (XIAnyHierarchyChangeInfo *)&atInfo, 1); } } void XInputMTInputDevice::start() { Status status; SDLDisplayEngine * pEngine = Player::get()->getDisplayEngine(); SDL_SysWMinfo info; SDL_VERSION(&info.version); int rc = SDL_GetWMInfo(&info); AVG_ASSERT(rc != -1); s_pDisplay = info.info.x11.display; m_SDLLockFunc = info.info.x11.lock_func; m_SDLUnlockFunc = info.info.x11.unlock_func; m_SDLLockFunc(); // XInput Extension available? int event, error; bool bOk = XQueryExtension(s_pDisplay, "XInputExtension", &m_XIOpcode, &event, &error); if (!bOk) { throw Exception(AVG_ERR_MT_INIT, "XInput multitouch event source: X Input extension not available."); } // Which version of XI2? int major; int minor; status = XIQueryVersion(s_pDisplay, &major, &minor); if (status == BadRequest) { throw Exception(AVG_ERR_MT_INIT, "XInput 2.1 multitouch event source: Server does not support XI2"); } if (major < 2 || minor < 1) { throw Exception(AVG_ERR_MT_INIT, "XInput multitouch event source: Supported version is " +toString(major)+"."+toString(minor)+". At least 2.1 is needed."); } findMTDevice(); // SDL grabs the pointer in full screen mode. This breaks touchscreen usage. // Can't use SDL_WM_GrabInput(SDL_GRAB_OFF) because it doesn't work in full // screen mode. Get the display connection and do it manually. XUngrabPointer(info.info.x11.display, CurrentTime); XIEventMask mask; mask.deviceid = m_DeviceID; mask.mask_len = XIMaskLen(XI_LASTEVENT); mask.mask = (unsigned char *)calloc(mask.mask_len, sizeof(char)); memset(mask.mask, 0, mask.mask_len); XISetMask(mask.mask, XI_TouchBegin); XISetMask(mask.mask, XI_TouchUpdate); XISetMask(mask.mask, XI_TouchEnd); status = XISelectEvents(s_pDisplay, info.info.x11.window, &mask, 1); AVG_ASSERT(status == Success); m_SDLUnlockFunc(); SDL_SetEventFilter(XInputMTInputDevice::filterEvent); XIDetachSlaveInfo detInfo; detInfo.type = XIDetachSlave; detInfo.deviceid = m_DeviceID; XIChangeHierarchy(s_pDisplay, (XIAnyHierarchyChangeInfo *)&detInfo, 1); pEngine->setXIMTInputDevice(this); MultitouchInputDevice::start(); AVG_TRACE(Logger::CONFIG, "XInput Multitouch event source created."); } void XInputMTInputDevice::handleXIEvent(const XEvent& xEvent) { m_SDLLockFunc(); XGenericEventCookie* pCookie = (XGenericEventCookie*)&xEvent.xcookie; if (pCookie->type == GenericEvent && pCookie->extension == m_XIOpcode) { XIDeviceEvent* pDevEvent = (XIDeviceEvent*)(pCookie->data); IntPoint pos(pDevEvent->event_x, pDevEvent->event_y); int xid = pDevEvent->detail; switch (pCookie->evtype) { case XI_TouchBegin: { // cerr << "TouchBegin " << xid << ", " << pos << endl; m_LastID++; TouchEventPtr pEvent = createEvent(m_LastID, Event::CURSOR_DOWN, pos); addTouchStatus(xid, pEvent); } break; case XI_TouchUpdate: { // cerr << "TouchUpdate " << xid << ", " << pos << endl; TouchEventPtr pEvent = createEvent(0, Event::CURSOR_MOTION, pos); TouchStatusPtr pTouchStatus = getTouchStatus(xid); AVG_ASSERT(pTouchStatus); pTouchStatus->pushEvent(pEvent); } break; case XI_TouchEnd: { // cerr << "TouchEnd " << xid << ", " << pos << endl; TouchStatusPtr pTouchStatus = getTouchStatus(xid); AVG_ASSERT(pTouchStatus); TouchEventPtr pEvent = createEvent(0, Event::CURSOR_UP, pos); pTouchStatus->pushEvent(pEvent); } break; default: ; // cerr << "Unhandled XInput event, type: " // << cookieTypeToName(pCookie->evtype) << endl; } } else { // cerr << "Unhandled X11 Event: " << xEvent.type << endl; } XFreeEventData(s_pDisplay, pCookie); m_SDLUnlockFunc(); } std::vector<EventPtr> XInputMTInputDevice::pollEvents() { return MultitouchInputDevice::pollEvents(); } void XInputMTInputDevice::findMTDevice() { int ndevices; XIDeviceInfo* pDevices; XIDeviceInfo* pDevice; pDevices = XIQueryDevice(s_pDisplay, XIAllDevices, &ndevices); XITouchClassInfo* pTouchClass = 0; for (int i = 0; i < ndevices && !pTouchClass; ++i) { pDevice = &pDevices[i]; // cerr << "Device " << pDevice->name << "(id: " << pDevice->deviceid << ")." // << endl; if (pDevice->use == XISlavePointer || pDevice->use == XIFloatingSlave) { for (int j = 0; j < pDevice->num_classes; ++j) { XIAnyClassInfo * pClass = pDevice->classes[j]; if (pClass->type == XITouchClass) { XITouchClassInfo* pTempTouchClass = (XITouchClassInfo *)pClass; if (pTempTouchClass->mode == XIDirectTouch) { pTouchClass = pTempTouchClass; m_sDeviceName = pDevice->name; m_DeviceID = pDevice->deviceid; if (pDevice->use == XISlavePointer) { m_OldMasterDeviceID = pDevice->attachment; } else { m_OldMasterDeviceID = -1; } break; } } } } } if (pTouchClass) { AVG_TRACE(Logger::CONFIG, "Using multitouch input device " << m_sDeviceName << ", max touches: " << pTouchClass->num_touches); } else { throw Exception(AVG_ERR_MT_INIT, "XInput multitouch event source: No multitouch device found."); } XIFreeDeviceInfo(pDevices); } TouchEventPtr XInputMTInputDevice::createEvent(int id, Event::Type type, IntPoint pos) { return TouchEventPtr(new TouchEvent(id, type, pos, Event::TOUCH)); } int XInputMTInputDevice::filterEvent(const SDL_Event * pEvent) { // This is a hook into libsdl event processing. Since libsdl doesn't know about // XInput 2, it doesn't call XGetEventData either. By the time the event arrives // in handleXIEvent(), other events may have arrived and XGetEventData can't be // called anymore. Hence this function, which calls XGetEventData for each event // that has a cookie. if (pEvent->type == SDL_SYSWMEVENT) { SDL_SysWMmsg* pMsg = pEvent->syswm.msg; AVG_ASSERT(pMsg->subsystem == SDL_SYSWM_X11); XEvent* pXEvent = &pMsg->event.xevent; XGenericEventCookie* pCookie = (XGenericEventCookie*)&(pXEvent->xcookie); // cerr << "---- filter xinput event: " << xEventTypeToName(pXEvent->type) << ", " // << cookieTypeToName(pCookie->evtype) << endl; XGetEventData(s_pDisplay, pCookie); } else { // cerr << "---- filter: " << int(pEvent->type) << endl; } return 1; } // From xinput/test_xi2.c const char* cookieTypeToName(int evtype) { const char *name; switch(evtype) { case XI_DeviceChanged: name = "DeviceChanged"; break; case XI_KeyPress: name = "KeyPress"; break; case XI_KeyRelease: name = "KeyRelease"; break; case XI_ButtonPress: name = "ButtonPress"; break; case XI_ButtonRelease: name = "ButtonRelease"; break; case XI_Motion: name = "Motion"; break; case XI_Enter: name = "Enter"; break; case XI_Leave: name = "Leave"; break; case XI_FocusIn: name = "FocusIn"; break; case XI_FocusOut: name = "FocusOut"; break; case XI_HierarchyChanged: name = "HierarchyChanged"; break; case XI_PropertyEvent: name = "PropertyEvent"; break; case XI_RawKeyPress: name = "RawKeyPress"; break; case XI_RawKeyRelease: name = "RawKeyRelease"; break; case XI_RawButtonPress: name = "RawButtonPress"; break; case XI_RawButtonRelease: name = "RawButtonRelease"; break; case XI_RawMotion: name = "RawMotion"; break; case XI_TouchBegin: name = "TouchBegin"; break; case XI_TouchEnd: name = "TouchEnd"; break; case XI_TouchUpdate: name = "TouchUpdate"; break; #ifdef HAVE_XI2_1 case XI_TouchUpdateUnowned: name = "TouchUpdateUnowned"; break; #endif default: name = "unknown event type"; break; } return name; } string xEventTypeToName(int evtype) { switch(evtype) { case KeyPress: return "KeyPress"; case KeyRelease: return "KeyRelease"; case ButtonPress: return "ButtonPress"; case ButtonRelease: return "ButtonRelease"; case MotionNotify: return "MotionNotify"; case EnterNotify: return "EnterNotify"; case LeaveNotify: return "LeaveNotify"; case FocusIn: return "FocusIn"; case FocusOut: return "FocusOut"; case KeymapNotify: return "KeymapNotify"; case Expose: return "Expose"; case GraphicsExpose: return "GraphicsExpose"; case NoExpose: return "NoExpose"; case VisibilityNotify: return "VisibilityNotify"; case CreateNotify: return "CreateNotify"; case DestroyNotify: return "DestroyNotify"; case UnmapNotify: return "UnmapNotify"; case MapNotify: return "MapNotify"; case MapRequest: return "MapRequest"; case ReparentNotify: return "ReparentNotify"; case ConfigureNotify: return "ConfigureNotify"; case ConfigureRequest: return "ConfigureRequest"; case GravityNotify: return "GravityNotify"; case ResizeRequest: return "ResizeRequest"; case CirculateNotify: return "CirculateNotify"; case CirculateRequest: return "CirculateRequest"; case PropertyNotify: return "PropertyNotify"; case SelectionClear: return "SelectionClear"; case SelectionRequest: return "SelectionRequest"; case SelectionNotify: return "SelectionNotify"; case ColormapNotify: return "ColormapNotify"; case ClientMessage: return "ClientMessage"; case MappingNotify: return "MappingNotify"; case GenericEvent: return "GenericEvent"; default: return "Unknown event type"; } } }
Remove unnecessary local variable 'maxTouches'
Remove unnecessary local variable 'maxTouches' git-svn-id: f4e1a40f847802203273bde8e26df4d11611876a@8187 44470bb9-56e9-0310-a0f8-c586564d3dc6
C++
lgpl-2.1
lynxis/libavg,pararthshah/libavg-vaapi,lynxis/libavg,pararthshah/libavg-vaapi,pararthshah/libavg-vaapi,pararthshah/libavg-vaapi,lynxis/libavg,lynxis/libavg
4ea2e9ed066a8790f6777a906009028a727676f7
vm/generic_arrays.hpp
vm/generic_arrays.hpp
namespace factor { template<typename Array> cell array_capacity(const Array *array) { #ifdef FACTOR_DEBUG FACTOR_ASSERT(array->type() == Array::type_number); #endif return array->capacity >> TAG_BITS; } template<typename Array> cell array_size(cell capacity) { return sizeof(Array) + capacity * Array::element_size; } template<typename Array> cell array_size(Array *array) { return array_size<Array>(array_capacity(array)); } /* Allocates memory */ template<typename Array> Array *factor_vm::allot_uninitialized_array(cell capacity) { Array *array = allot<Array>(array_size<Array>(capacity)); array->capacity = tag_fixnum(capacity); return array; } template<typename Array> bool factor_vm::reallot_array_in_place_p(Array *array, cell capacity) { return nursery.contains_p(array) && capacity <= array_capacity(array); } /* Allocates memory (sometimes) */ template<typename Array> Array *factor_vm::reallot_array(Array *array_, cell capacity) { data_root<Array> array(array_,this); if (array_capacity(array.untagged()) == capacity) return array.untagged(); if(reallot_array_in_place_p(array.untagged(),capacity)) { array->capacity = tag_fixnum(capacity); return array.untagged(); } else { cell to_copy = array_capacity(array.untagged()); if(capacity < to_copy) to_copy = capacity; Array *new_array = allot_uninitialized_array<Array>(capacity); memcpy(new_array + 1,array.untagged() + 1,to_copy * Array::element_size); memset((char *)(new_array + 1) + to_copy * Array::element_size, 0,(capacity - to_copy) * Array::element_size); return new_array; } } }
namespace factor { template <typename Array> cell array_capacity(const Array* array) { #ifdef FACTOR_DEBUG FACTOR_ASSERT(array->type() == Array::type_number); #endif return array->capacity >> TAG_BITS; } template <typename Array> cell array_size(cell capacity) { return sizeof(Array) + capacity * Array::element_size; } template <typename Array> cell array_size(Array* array) { return array_size<Array>(array_capacity(array)); } /* Allocates memory */ template <typename Array> Array* factor_vm::allot_uninitialized_array(cell capacity) { Array* array = allot<Array>(array_size<Array>(capacity)); array->capacity = tag_fixnum(capacity); return array; } template <typename Array> bool factor_vm::reallot_array_in_place_p(Array* array, cell capacity) { return nursery.contains_p(array) && capacity <= array_capacity(array); } /* Allocates memory (sometimes) */ template <typename Array> Array* factor_vm::reallot_array(Array* array_, cell capacity) { data_root<Array> array(array_, this); if (array_capacity(array.untagged()) == capacity) return array.untagged(); if (reallot_array_in_place_p(array.untagged(), capacity)) { array->capacity = tag_fixnum(capacity); return array.untagged(); } else { cell to_copy = array_capacity(array.untagged()); if (capacity < to_copy) to_copy = capacity; Array* new_array = allot_uninitialized_array<Array>(capacity); memcpy(new_array + 1, array.untagged() + 1, to_copy * Array::element_size); memset((char*)(new_array + 1) + to_copy * Array::element_size, 0, (capacity - to_copy) * Array::element_size); return new_array; } } }
Refactor generic_arrays.hpp to Factor style
VM: Refactor generic_arrays.hpp to Factor style
C++
bsd-2-clause
dch/factor,nicolas-p/factor,bjourne/factor,bpollack/factor,factor/factor,sarvex/factor-lang,AlexIljin/factor,slavapestov/factor,mrjbq7/factor,bjourne/factor,bpollack/factor,factor/factor,nicolas-p/factor,bpollack/factor,sarvex/factor-lang,mrjbq7/factor,mrjbq7/factor,bjourne/factor,AlexIljin/factor,AlexIljin/factor,sarvex/factor-lang,nicolas-p/factor,factor/factor,dch/factor,bpollack/factor,tgunr/factor,sarvex/factor-lang,tgunr/factor,bpollack/factor,tgunr/factor,AlexIljin/factor,sarvex/factor-lang,sarvex/factor-lang,nicolas-p/factor,bpollack/factor,slavapestov/factor,factor/factor,mrjbq7/factor,factor/factor,dch/factor,bpollack/factor,dch/factor,AlexIljin/factor,slavapestov/factor,tgunr/factor,dch/factor,bjourne/factor,slavapestov/factor,bjourne/factor,bjourne/factor,nicolas-p/factor,nicolas-p/factor,slavapestov/factor,sarvex/factor-lang,dch/factor,nicolas-p/factor,tgunr/factor,factor/factor,slavapestov/factor,bjourne/factor,mrjbq7/factor,AlexIljin/factor,tgunr/factor,AlexIljin/factor,mrjbq7/factor,slavapestov/factor
21e9da5c8a65c14fdab666be35e1ace9465a8d0e
src/openMVG/keyframe/KeyframeSelector.cpp
src/openMVG/keyframe/KeyframeSelector.cpp
#include "KeyframeSelector.hpp" #include "openMVG/image/image.hpp" #include "openMVG/features/sift/SIFT_describer.hpp" #include "openMVG/exif/sensor_width_database/ParseDatabase.hpp" #include "openMVG/logger.hpp" #include <tuple> #include <cassert> namespace openMVG { namespace keyframe { KeyframeSelector::KeyframeSelector(const std::vector<std::string>& mediaPaths, const std::string& sensorDbPath, const std::string& voctreeFilePath, const std::string& outputDirectory) : _mediaPaths(mediaPaths) , _sensorDbPath(sensorDbPath) , _voctreeFilePath(voctreeFilePath) , _outputDirectory(outputDirectory) { // load vocabulary tree _voctree.reset(new openMVG::voctree::VocabularyTree<DescriptorFloat>(voctreeFilePath)); { OPENMVG_COUT("vocabulary tree loaded with :"); OPENMVG_COUT(" - " << _voctree->levels() << " levels"); OPENMVG_COUT(" - " << _voctree->splits() << " branching factor"); } // check number of input media filePaths if(mediaPaths.empty()) { OPENMVG_CERR("ERROR : can't create KeyframeSelector without a media file path !"); throw std::invalid_argument("ERROR : can't create KeyframeSelector without a media file path !"); } // resize mediasInfo container _mediasInfo.resize(mediaPaths.size()); // create feeds and count minimum number of frames std::size_t nbFrames = std::numeric_limits<std::size_t>::max(); for(const auto& path : _mediaPaths) { // create a feed provider per mediaPaths _feeds.emplace_back(new dataio::FeedProvider(path)); const auto& feed = *_feeds.back(); // check if feed is initialized if(!feed.isInit()) { OPENMVG_CERR("ERROR : while initializing the FeedProvider with " << path); throw std::invalid_argument("ERROR : while initializing the FeedProvider with " + path); } // update minimum number of frames nbFrames = std::min(nbFrames, feed.nbFrames()); } // check if minimum number of frame is zero if(nbFrames == 0) { OPENMVG_CERR("ERROR : one or multiple medias are empty (no frames) !"); throw std::invalid_argument("ERROR : one or multiple medias are empty (no frames) !"); } // resize selection data vector _framesData.resize(nbFrames); // create SIFT image describer _imageDescriber.reset(new features::SIFT_ImageDescriber()); } void KeyframeSelector::process() { // feed provider variables image::Image< image::RGBColor> image; // original image cameras::Pinhole_Intrinsic_Radial_K3 queryIntrinsics; // image associated camera intrinsics bool hasIntrinsics = false; // true if queryIntrinsics is valid std::string currentImgName; // current image name // process variables const unsigned int frameStep = _maxFrameStep - _minFrameStep; const unsigned int tileSharpSubset = (_nbTileSide * _nbTileSide) / _sharpSubset; for(std::size_t mediaIndex = 0 ; mediaIndex < _feeds.size(); ++mediaIndex) { // first frame if(!_feeds.at(mediaIndex)->readImage(image, queryIntrinsics, currentImgName, hasIntrinsics)) { OPENMVG_CERR("ERROR : can't read media first frame " << _mediaPaths[mediaIndex]); throw std::invalid_argument("ERROR : can't read media first frame " + _mediaPaths[mediaIndex]); } // define output image metadata if(!_cameraInfos.at(mediaIndex).focalIsMM) { convertFocalLengthInMM(_cameraInfos.at(mediaIndex), image.Width()); } // define media informations variables auto& mediaInfo = _mediasInfo.at(mediaIndex); mediaInfo.halfHeight = image.Height() / 2; mediaInfo.halfWidth = image.Width() / 2; mediaInfo.tileHeight = mediaInfo.halfHeight / _nbTileSide; mediaInfo.tileWidth = mediaInfo.halfWidth / _nbTileSide; mediaInfo.spec = oiio::ImageSpec(image.Width(), image.Height(), 3, oiio::TypeDesc::UINT8); // always jpeg mediaInfo.spec.attribute("CompressionQuality", 100); // always best compression quality mediaInfo.spec.attribute("jpeg:subsampling", "4:4:4"); // always subsampling 4:4:4 mediaInfo.spec.attribute("oiio:ColorSpace", "sRGB"); // always sRGB mediaInfo.spec.attribute("Make", _cameraInfos[mediaIndex].brand); mediaInfo.spec.attribute("Model", _cameraInfos[mediaIndex].model); mediaInfo.spec.attribute("Exif:FocalLength", _cameraInfos[mediaIndex].focalLength); } // iteration process _keyframeIndexes.clear(); std::size_t currentFrameStep = _minFrameStep; // start directly (dont skip minFrameStep first frames) for(std::size_t frameIndex = 0; frameIndex < _framesData.size(); ++frameIndex) { OPENMVG_COUT("frame : " << frameIndex << std::endl); bool frameSelected = true; auto& frameData = _framesData.at(frameIndex); frameData.mediasData.resize(_feeds.size()); for(std::size_t mediaIndex = 0; mediaIndex < _feeds.size(); ++mediaIndex) { OPENMVG_COUT("media : " << _mediaPaths.at(mediaIndex) << std::endl); auto& feed = *_feeds.at(mediaIndex); if(frameSelected) // false if a camera of a rig is not selected { if(!feed.readImage(image, queryIntrinsics, currentImgName, hasIntrinsics)) { OPENMVG_CERR("ERROR : can't read frame '" << currentImgName << "' !"); throw std::invalid_argument("ERROR : can't read frame '" + currentImgName + "' !"); } // compute sharpness and sparse distance if(!computeFrameData(image, frameIndex, mediaIndex, tileSharpSubset)) { frameSelected = false; } } feed.goToNextFrame(); } { if(frameSelected) { OPENMVG_COUT(" > selected " << std::endl); frameData.selected = true; frameData.computeAvgSharpness(); } else { OPENMVG_COUT(" > skipped " << std::endl); frameData.mediasData.clear(); // remove unselected mediasData } } // selection process if(currentFrameStep >= _maxFrameStep) { currentFrameStep = _minFrameStep; std::size_t keyframeIndex = 0; float maxSharpness = 0; // find the sharpest selected frame for(std::size_t index = frameIndex - (frameStep - 1); index <= frameIndex; ++index) { if(_framesData[index].selected && (_framesData[index].avgSharpness > maxSharpness)) { keyframeIndex = index; maxSharpness = _framesData[index].avgSharpness; } } OPENMVG_COUT("--> keyframe choice : " << keyframeIndex << std::endl); // save keyframe if(keyframeIndex != 0) { if(_maxOutFrame == 0) // no limit of keyframes (direct evaluation) { // write keyframe for(std::size_t mediaIndex = 0; mediaIndex < _feeds.size(); ++mediaIndex) { auto& feed = *_feeds.at(mediaIndex); feed.goToFrame(keyframeIndex); feed.readImage(image, queryIntrinsics, currentImgName, hasIntrinsics); writeKeyframe(image, keyframeIndex, mediaIndex); } } _framesData[keyframeIndex].keyframe = true; _keyframeIndexes.push_back(keyframeIndex); frameIndex = keyframeIndex + _minFrameStep - 1; } } ++currentFrameStep; } if(_maxOutFrame == 0) // no limit of keyframes (evaluation and write already done) { return; } // if limited number of keyframe select smallest sparse distance { std::vector< std::tuple<float, float, std::size_t> > keyframes; for(std::size_t i = 0; i < _framesData.size(); ++i) { if(_framesData[i].keyframe) { keyframes.emplace_back(_framesData[i].maxDistScore, 1 / _framesData[i].avgSharpness, i); } } std::sort(keyframes.begin(), keyframes.end()); for(std::size_t i = 0; i < _maxOutFrame; ++i) { const std::size_t frameIndex = std::get<2>(keyframes.at(i)); for(std::size_t mediaIndex = 0; mediaIndex < _feeds.size(); ++mediaIndex) { auto& feed = *_feeds.at(mediaIndex); feed.goToFrame(frameIndex); feed.readImage(image, queryIntrinsics, currentImgName, hasIntrinsics); writeKeyframe(image, frameIndex, mediaIndex); } } } } float KeyframeSelector::computeSharpness(const image::Image<unsigned char>& imageGray, const unsigned int tileHeight, const unsigned int tileWidth, const unsigned int tileSharpSubset) const { image::Image<float> image; image::Image<float> scharrXDer; image::Image<float> scharrYDer; image::ConvertPixelType(imageGray, &image); image::ImageScharrXDerivative(image, scharrXDer); // normalized image::ImageScharrYDerivative(image, scharrYDer); // normalized scharrXDer = scharrXDer.cwiseAbs(); // absolute value scharrYDer = scharrYDer.cwiseAbs(); // absolute value // image tiles std::vector<float> averageTileIntensity; const float tileSizeInv = 1 / static_cast<float>(tileHeight * tileWidth); for(std::size_t y = 0; y < (_nbTileSide * tileHeight); y += tileHeight) { for(std::size_t x = 0; x < (_nbTileSide * tileWidth); x += tileWidth) { const auto sum = scharrXDer.block(y, x, tileHeight, tileWidth).sum() + scharrYDer.block(y, x, tileHeight, tileWidth).sum(); averageTileIntensity.push_back(sum * tileSizeInv); } } // sort tiles average pixel intensity std::sort(averageTileIntensity.begin(), averageTileIntensity.end()); // return the sum of the subset average pixel intensity return std::accumulate(averageTileIntensity.end() - tileSharpSubset, averageTileIntensity.end(), 0.0f) / tileSharpSubset; } bool KeyframeSelector::computeFrameData(const image::Image<image::RGBColor>& image, std::size_t frameIndex, std::size_t mediaIndex, unsigned int tileSharpSubset) { image::Image<unsigned char> imageGray; // grayscale image image::Image<unsigned char> imageGrayHalfSample; // half resolution grayscale image const auto& currMediaInfo = _mediasInfo.at(mediaIndex); auto& currframeData = _framesData.at(frameIndex); auto& currMediaData = currframeData.mediasData.at(mediaIndex); // get grayscale image and resize image::ConvertPixelType(image, &imageGray); image::ImageHalfSample(imageGray, imageGrayHalfSample); // compute sharpness currMediaData.sharpness = computeSharpness(imageGrayHalfSample, currMediaInfo.tileHeight, currMediaInfo.tileWidth, tileSharpSubset); OPENMVG_COUT( " - sharpness : " << currMediaData.sharpness << std::endl); if(currMediaData.sharpness > _sharpnessThreshold) { bool noKeyframe = (_keyframeIndexes.empty()); // compute current frame sparse histogram std::unique_ptr<features::Regions> regions; _imageDescriber->Describe(imageGrayHalfSample, regions); currMediaData.histogram = voctree::SparseHistogram(_voctree->quantizeToSparse(dynamic_cast<features::SIFT_Regions*>(regions.get())->Descriptors())); // compute sparseDistance if(!noKeyframe) { unsigned int nbKeyframetoCompare = (_keyframeIndexes.size() < _nbKeyFrameDist)? _keyframeIndexes.size() : _nbKeyFrameDist; for(std::size_t i = _keyframeIndexes.size() - nbKeyframetoCompare; i < _keyframeIndexes.size(); ++i) { for(auto& media : _framesData.at(_keyframeIndexes.at(i)).mediasData) { currMediaData.distScore = std::max(currMediaData.distScore, std::abs(voctree::sparseDistance(media.histogram, currMediaData.histogram, "strongCommonPoints"))); } } currframeData.maxDistScore = std::max(currframeData.maxDistScore, currMediaData.distScore); OPENMVG_COUT(" - distScore : " << currMediaData.distScore << std::endl); } if(noKeyframe || (currMediaData.distScore < _distScoreMax)) { return true; } } return false; } void KeyframeSelector::writeKeyframe(const image::Image<image::RGBColor>& image, std::size_t frameIndex, std::size_t mediaIndex) { const auto& mediaInfo = _mediasInfo.at(mediaIndex); const auto filepath = _outputDirectory + "/frame_" + to_string(frameIndex) + "_media_" + to_string(mediaIndex) + ".jpg"; std::unique_ptr<oiio::ImageOutput> out(oiio::ImageOutput::create(filepath)); if(out.get() == nullptr) { throw std::invalid_argument("ERROR : can't create image file : " + filepath); } if(!out->open(filepath, mediaInfo.spec)) { throw std::invalid_argument("ERROR : can't open image file : " + filepath); } out->write_image(oiio::TypeDesc::UINT8, image.data()); // always jpeg out->close(); } void KeyframeSelector::convertFocalLengthInMM(CameraInfo& cameraInfo, int imageWidth) { assert(imageWidth > 0); exif::sensordb::Datasheet find; std::vector<exif::sensordb::Datasheet> vecDatabase; exif::sensordb::parseDatabase(_sensorDbPath, vecDatabase); if(exif::sensordb::getInfo(cameraInfo.brand, cameraInfo.model, vecDatabase, find)) { cameraInfo.focalLength = (cameraInfo.focalLength * find._sensorSize) / imageWidth; cameraInfo.focalIsMM = true; OPENMVG_COUT("INFO : Focal length converted in mm : " << cameraInfo.focalLength << std::endl); } else { OPENMVG_COUT("WARNING : can't convert focal length in mm : " << cameraInfo.brand << " / " << cameraInfo.model << std::endl); } } } // namespace keyframe } // namespace openMVG
#include "KeyframeSelector.hpp" #include "openMVG/image/image.hpp" #include "openMVG/features/sift/SIFT_describer.hpp" #include "openMVG/exif/sensor_width_database/ParseDatabase.hpp" #include "openMVG/logger.hpp" #include <tuple> #include <cassert> namespace openMVG { namespace keyframe { KeyframeSelector::KeyframeSelector(const std::vector<std::string>& mediaPaths, const std::string& sensorDbPath, const std::string& voctreeFilePath, const std::string& outputDirectory) : _mediaPaths(mediaPaths) , _sensorDbPath(sensorDbPath) , _voctreeFilePath(voctreeFilePath) , _outputDirectory(outputDirectory) { // load vocabulary tree _voctree.reset(new openMVG::voctree::VocabularyTree<DescriptorFloat>(voctreeFilePath)); { OPENMVG_COUT("vocabulary tree loaded with :"); OPENMVG_COUT(" - " << _voctree->levels() << " levels"); OPENMVG_COUT(" - " << _voctree->splits() << " branching factor"); } // check number of input media filePaths if(mediaPaths.empty()) { OPENMVG_CERR("ERROR : can't create KeyframeSelector without a media file path !"); throw std::invalid_argument("ERROR : can't create KeyframeSelector without a media file path !"); } // resize mediasInfo container _mediasInfo.resize(mediaPaths.size()); // create feeds and count minimum number of frames std::size_t nbFrames = std::numeric_limits<std::size_t>::max(); for(const auto& path : _mediaPaths) { // create a feed provider per mediaPaths _feeds.emplace_back(new dataio::FeedProvider(path)); const auto& feed = *_feeds.back(); // check if feed is initialized if(!feed.isInit()) { OPENMVG_CERR("ERROR : while initializing the FeedProvider with " << path); throw std::invalid_argument("ERROR : while initializing the FeedProvider with " + path); } // update minimum number of frames nbFrames = std::min(nbFrames, feed.nbFrames()); } // check if minimum number of frame is zero if(nbFrames == 0) { OPENMVG_CERR("ERROR : one or multiple medias are empty (no frames) !"); throw std::invalid_argument("ERROR : one or multiple medias are empty (no frames) !"); } // resize selection data vector _framesData.resize(nbFrames); // create SIFT image describer _imageDescriber.reset(new features::SIFT_ImageDescriber()); } void KeyframeSelector::process() { // feed provider variables image::Image< image::RGBColor> image; // original image cameras::Pinhole_Intrinsic_Radial_K3 queryIntrinsics; // image associated camera intrinsics bool hasIntrinsics = false; // true if queryIntrinsics is valid std::string currentImgName; // current image name // process variables const unsigned int frameStep = _maxFrameStep - _minFrameStep; const unsigned int tileSharpSubset = (_nbTileSide * _nbTileSide) / _sharpSubset; for(std::size_t mediaIndex = 0 ; mediaIndex < _feeds.size(); ++mediaIndex) { // first frame if(!_feeds.at(mediaIndex)->readImage(image, queryIntrinsics, currentImgName, hasIntrinsics)) { OPENMVG_CERR("ERROR : can't read media first frame " << _mediaPaths[mediaIndex]); throw std::invalid_argument("ERROR : can't read media first frame " + _mediaPaths[mediaIndex]); } // define output image metadata if(!_cameraInfos.at(mediaIndex).focalIsMM) { convertFocalLengthInMM(_cameraInfos.at(mediaIndex), image.Width()); } // define media informations variables auto& mediaInfo = _mediasInfo.at(mediaIndex); mediaInfo.halfHeight = image.Height() / 2; mediaInfo.halfWidth = image.Width() / 2; mediaInfo.tileHeight = mediaInfo.halfHeight / _nbTileSide; mediaInfo.tileWidth = mediaInfo.halfWidth / _nbTileSide; mediaInfo.spec = oiio::ImageSpec(image.Width(), image.Height(), 3, oiio::TypeDesc::UINT8); // always jpeg mediaInfo.spec.attribute("CompressionQuality", 100); // always best compression quality mediaInfo.spec.attribute("jpeg:subsampling", "4:4:4"); // always subsampling 4:4:4 mediaInfo.spec.attribute("oiio:ColorSpace", "sRGB"); // always sRGB mediaInfo.spec.attribute("Make", _cameraInfos[mediaIndex].brand); mediaInfo.spec.attribute("Model", _cameraInfos[mediaIndex].model); mediaInfo.spec.attribute("Exif:FocalLength", _cameraInfos[mediaIndex].focalLength); } // iteration process _keyframeIndexes.clear(); std::size_t currentFrameStep = _minFrameStep; // start directly (dont skip minFrameStep first frames) for(std::size_t frameIndex = 0; frameIndex < _framesData.size(); ++frameIndex) { OPENMVG_COUT("frame : " << frameIndex << std::endl); bool frameSelected = true; auto& frameData = _framesData.at(frameIndex); frameData.mediasData.resize(_feeds.size()); for(std::size_t mediaIndex = 0; mediaIndex < _feeds.size(); ++mediaIndex) { OPENMVG_COUT("media : " << _mediaPaths.at(mediaIndex) << std::endl); auto& feed = *_feeds.at(mediaIndex); if(frameSelected) // false if a camera of a rig is not selected { if(!feed.readImage(image, queryIntrinsics, currentImgName, hasIntrinsics)) { OPENMVG_CERR("ERROR : can't read frame '" << currentImgName << "' !"); throw std::invalid_argument("ERROR : can't read frame '" + currentImgName + "' !"); } // compute sharpness and sparse distance if(!computeFrameData(image, frameIndex, mediaIndex, tileSharpSubset)) { frameSelected = false; } } feed.goToNextFrame(); } { if(frameSelected) { OPENMVG_COUT(" > selected " << std::endl); frameData.selected = true; frameData.computeAvgSharpness(); } else { OPENMVG_COUT(" > skipped " << std::endl); frameData.mediasData.clear(); // remove unselected mediasData } } // selection process if(currentFrameStep >= _maxFrameStep) { currentFrameStep = _minFrameStep; bool hasKeyframe = false; std::size_t keyframeIndex = 0; float maxSharpness = 0; // find the sharpest selected frame for(std::size_t index = frameIndex - (frameStep - 1); index <= frameIndex; ++index) { if(_framesData[index].selected && (_framesData[index].avgSharpness > maxSharpness)) { hasKeyframe = true; keyframeIndex = index; maxSharpness = _framesData[index].avgSharpness; } } // save keyframe if(hasKeyframe) { OPENMVG_COUT("--> keyframe choice : " << keyframeIndex << std::endl); if(_maxOutFrame == 0) // no limit of keyframes (direct evaluation) { // write keyframe for(std::size_t mediaIndex = 0; mediaIndex < _feeds.size(); ++mediaIndex) { auto& feed = *_feeds.at(mediaIndex); feed.goToFrame(keyframeIndex); feed.readImage(image, queryIntrinsics, currentImgName, hasIntrinsics); writeKeyframe(image, keyframeIndex, mediaIndex); } } _framesData[keyframeIndex].keyframe = true; _keyframeIndexes.push_back(keyframeIndex); frameIndex = keyframeIndex + _minFrameStep - 1; } else { OPENMVG_COUT("--> keyframe choice : none"); } } ++currentFrameStep; } if(_maxOutFrame == 0) // no limit of keyframes (evaluation and write already done) { return; } // if limited number of keyframe select smallest sparse distance { std::vector< std::tuple<float, float, std::size_t> > keyframes; for(std::size_t i = 0; i < _framesData.size(); ++i) { if(_framesData[i].keyframe) { keyframes.emplace_back(_framesData[i].maxDistScore, 1 / _framesData[i].avgSharpness, i); } } std::sort(keyframes.begin(), keyframes.end()); for(std::size_t i = 0; i < _maxOutFrame; ++i) { const std::size_t frameIndex = std::get<2>(keyframes.at(i)); for(std::size_t mediaIndex = 0; mediaIndex < _feeds.size(); ++mediaIndex) { auto& feed = *_feeds.at(mediaIndex); feed.goToFrame(frameIndex); feed.readImage(image, queryIntrinsics, currentImgName, hasIntrinsics); writeKeyframe(image, frameIndex, mediaIndex); } } } } float KeyframeSelector::computeSharpness(const image::Image<unsigned char>& imageGray, const unsigned int tileHeight, const unsigned int tileWidth, const unsigned int tileSharpSubset) const { image::Image<float> image; image::Image<float> scharrXDer; image::Image<float> scharrYDer; image::ConvertPixelType(imageGray, &image); image::ImageScharrXDerivative(image, scharrXDer); // normalized image::ImageScharrYDerivative(image, scharrYDer); // normalized scharrXDer = scharrXDer.cwiseAbs(); // absolute value scharrYDer = scharrYDer.cwiseAbs(); // absolute value // image tiles std::vector<float> averageTileIntensity; const float tileSizeInv = 1 / static_cast<float>(tileHeight * tileWidth); for(std::size_t y = 0; y < (_nbTileSide * tileHeight); y += tileHeight) { for(std::size_t x = 0; x < (_nbTileSide * tileWidth); x += tileWidth) { const auto sum = scharrXDer.block(y, x, tileHeight, tileWidth).sum() + scharrYDer.block(y, x, tileHeight, tileWidth).sum(); averageTileIntensity.push_back(sum * tileSizeInv); } } // sort tiles average pixel intensity std::sort(averageTileIntensity.begin(), averageTileIntensity.end()); // return the sum of the subset average pixel intensity return std::accumulate(averageTileIntensity.end() - tileSharpSubset, averageTileIntensity.end(), 0.0f) / tileSharpSubset; } bool KeyframeSelector::computeFrameData(const image::Image<image::RGBColor>& image, std::size_t frameIndex, std::size_t mediaIndex, unsigned int tileSharpSubset) { image::Image<unsigned char> imageGray; // grayscale image image::Image<unsigned char> imageGrayHalfSample; // half resolution grayscale image const auto& currMediaInfo = _mediasInfo.at(mediaIndex); auto& currframeData = _framesData.at(frameIndex); auto& currMediaData = currframeData.mediasData.at(mediaIndex); // get grayscale image and resize image::ConvertPixelType(image, &imageGray); image::ImageHalfSample(imageGray, imageGrayHalfSample); // compute sharpness currMediaData.sharpness = computeSharpness(imageGrayHalfSample, currMediaInfo.tileHeight, currMediaInfo.tileWidth, tileSharpSubset); OPENMVG_COUT( " - sharpness : " << currMediaData.sharpness << std::endl); if(currMediaData.sharpness > _sharpnessThreshold) { bool noKeyframe = (_keyframeIndexes.empty()); // compute current frame sparse histogram std::unique_ptr<features::Regions> regions; _imageDescriber->Describe(imageGrayHalfSample, regions); currMediaData.histogram = voctree::SparseHistogram(_voctree->quantizeToSparse(dynamic_cast<features::SIFT_Regions*>(regions.get())->Descriptors())); // compute sparseDistance if(!noKeyframe) { unsigned int nbKeyframetoCompare = (_keyframeIndexes.size() < _nbKeyFrameDist)? _keyframeIndexes.size() : _nbKeyFrameDist; for(std::size_t i = _keyframeIndexes.size() - nbKeyframetoCompare; i < _keyframeIndexes.size(); ++i) { for(auto& media : _framesData.at(_keyframeIndexes.at(i)).mediasData) { currMediaData.distScore = std::max(currMediaData.distScore, std::abs(voctree::sparseDistance(media.histogram, currMediaData.histogram, "strongCommonPoints"))); } } currframeData.maxDistScore = std::max(currframeData.maxDistScore, currMediaData.distScore); OPENMVG_COUT(" - distScore : " << currMediaData.distScore << std::endl); } if(noKeyframe || (currMediaData.distScore < _distScoreMax)) { return true; } } return false; } void KeyframeSelector::writeKeyframe(const image::Image<image::RGBColor>& image, std::size_t frameIndex, std::size_t mediaIndex) { const auto& mediaInfo = _mediasInfo.at(mediaIndex); const auto filepath = _outputDirectory + "/frame_" + to_string(frameIndex) + "_media_" + to_string(mediaIndex) + ".jpg"; std::unique_ptr<oiio::ImageOutput> out(oiio::ImageOutput::create(filepath)); if(out.get() == nullptr) { throw std::invalid_argument("ERROR : can't create image file : " + filepath); } if(!out->open(filepath, mediaInfo.spec)) { throw std::invalid_argument("ERROR : can't open image file : " + filepath); } out->write_image(oiio::TypeDesc::UINT8, image.data()); // always jpeg out->close(); } void KeyframeSelector::convertFocalLengthInMM(CameraInfo& cameraInfo, int imageWidth) { assert(imageWidth > 0); exif::sensordb::Datasheet find; std::vector<exif::sensordb::Datasheet> vecDatabase; exif::sensordb::parseDatabase(_sensorDbPath, vecDatabase); if(exif::sensordb::getInfo(cameraInfo.brand, cameraInfo.model, vecDatabase, find)) { cameraInfo.focalLength = (cameraInfo.focalLength * find._sensorSize) / imageWidth; cameraInfo.focalIsMM = true; OPENMVG_COUT("INFO : Focal length converted in mm : " << cameraInfo.focalLength << std::endl); } else { OPENMVG_COUT("WARNING : can't convert focal length in mm : " << cameraInfo.brand << " / " << cameraInfo.model << std::endl); } } } // namespace keyframe } // namespace openMVG
fix : first frame can be selected
[keyframe] fix : first frame can be selected
C++
mit
poparteu/openMVG,poparteu/openMVG,poparteu/openMVG,poparteu/openMVG
017af8702c731b47b1ae014c81b159b997191628
src/base_controller/src/serial_controller/serial_controller_node.cpp
src/base_controller/src/serial_controller/serial_controller_node.cpp
#include <iostream> /* allows to perform standard input and output operations */ #include <fstream> #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <ctype.h> /* isxxx() */ const char* serialport="/dev/ttyAMA0"; /* defines used serialport */ int serialport_bps=B38400; /* defines baudrate od serialport */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ int filedesc; // File descriptor of serial port we will talk to int fd; /* serial port file descriptor */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ struct termios orig; // Port options using namespace std; int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void read_MD49_Data (void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); char* itoa(int value, char* result, int base); unsigned char md49_data[18]; int main( int argc, char* argv[] ){ // Open serial port // **************** filedesc = openSerialPort("/dev/ttyAMA0", serialport_bps); if (filedesc == -1) exit(1); usleep(10000); // Sleep for UART to power up and set options while( 1 ) { // Read encoder and other data from MD49 // and put into sqlite db // ************************************* read_MD49_Data(); usleep(200000); // Read commands from sqlite db and // set speed and other commands to MD49 // ************************************ string line; ifstream myfile ("md49_commands.txt"); if (myfile.is_open()) { int i=0; while ( getline (myfile,line) ) { //cout << line << '\n'; char data[10]; std::copy(line.begin(), line.end(), data); md49_data[i]=atoi(data); i =i++; } myfile.close(); speed_l=md49_data[0]; speed_r=md49_data[1]; } else cout << "Unable to open file"; set_MD49_speed(speed_l, speed_r); usleep(200000); }// end.mainloop return 1; } // end.main int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); //fprintf(stderr, "speed=%d\n", bps); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void read_MD49_Data (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); ofstream myfile; myfile.open ("md49_data.txt"); //myfile << "Writing this to a file.\n"; char buffer[33]; EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("====================================================== \n"); printf("Encoder1 Byte1: %i ",serialBuffer[0]); if (serialBuffer[0]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[0],buffer,10); } myfile << "\n"; printf("Byte2: %i ",serialBuffer[1]); myfile << itoa(serialBuffer[1],buffer,10); myfile << "\n"; printf("Byte3: % i ",serialBuffer[2]); myfile << itoa(serialBuffer[2],buffer,10); myfile << "\n"; printf("Byte4: %i \n",serialBuffer[3]); myfile << itoa(serialBuffer[3],buffer,10); myfile << "\n"; printf("Encoder2 Byte1: %i ",serialBuffer[4]); myfile << itoa(serialBuffer[4],buffer,10); myfile << "\n"; printf("Byte2: %i ",serialBuffer[5]); myfile << itoa(serialBuffer[5],buffer,10); myfile << "\n"; printf("Byte3: %i ",serialBuffer[6]); myfile << itoa(serialBuffer[6],buffer,10); myfile << "\n"; printf("Byte4: %i \n",serialBuffer[7]); myfile << itoa(serialBuffer[7],buffer,10); myfile << "\n"; printf("EncoderL: %i ",EncoderL); // myfile << itoa(EncoderL,buffer,10); //myfile << "\n"; printf("EncoderR: %i \n",EncoderR); //myfile << itoa(EncoderR,buffer,10); //myfile << "\n"; printf("====================================================== \n"); printf("Speed1: %i ",serialBuffer[8]); myfile << itoa(serialBuffer[8],buffer,10); myfile << "\n"; printf("Speed2: %i \n",serialBuffer[9]); myfile << itoa(serialBuffer[9],buffer,10); myfile << "\n"; printf("Volts: %i \n",serialBuffer[10]); myfile << itoa(serialBuffer[10],buffer,10); myfile << "\n"; printf("Current1: %i ",serialBuffer[11]); myfile << itoa(serialBuffer[11],buffer,10); myfile << "\n"; printf("Current2: %i \n",serialBuffer[12]); myfile << itoa(serialBuffer[12],buffer,10); myfile << "\n"; printf("Error: %i \n",serialBuffer[13]); myfile << itoa(serialBuffer[13],buffer,10); myfile << "\n"; printf("Acceleration: %i \n",serialBuffer[14]); myfile << itoa(serialBuffer[14],buffer,10); myfile << "\n"; printf("Mode: %i \n",serialBuffer[15]); myfile << itoa(serialBuffer[15],buffer,10); myfile << "\n"; printf("Regulator: %i \n",serialBuffer[16]); myfile << itoa(serialBuffer[16],buffer,10); myfile << "\n"; printf("Timeout: %i \n",serialBuffer[17]); myfile << itoa(serialBuffer[17],buffer,10); myfile << "\n"; printf("speed_l = %i \n",speed_l); printf("speed_r = %i \n",speed_r); myfile.close(); } void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = speed_l; // speed1 serialBuffer[3] = speed_r; // speed2 writeBytes(fd, 4); } char* itoa(int value, char* result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; }
#include <iostream> /* allows to perform standard input and output operations */ #include <fstream> #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <ctype.h> /* isxxx() */ const char* serialport="/dev/ttyAMA0"; /* defines used serialport */ int serialport_bps=B38400; /* defines baudrate od serialport */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ int filedesc; // File descriptor of serial port we will talk to int fd; /* serial port file descriptor */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ struct termios orig; // Port options using namespace std; int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void read_MD49_Data (void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); char* itoa(int value, char* result, int base); unsigned char md49_data[18]; int main( int argc, char* argv[] ){ // Open serial port // **************** filedesc = openSerialPort("/dev/ttyAMA0", serialport_bps); if (filedesc == -1) exit(1); usleep(10000); // Sleep for UART to power up and set options while( 1 ) { // Read encoder and other data from MD49 // and put into sqlite db // ************************************* read_MD49_Data(); usleep(200000); // Read commands from sqlite db and // set speed and other commands to MD49 // ************************************ string line; ifstream myfile ("md49_commands.txt"); if (myfile.is_open()) { int i=0; while ( getline (myfile,line) ) { //cout << line << '\n'; char data[10]; std::copy(line.begin(), line.end(), data); md49_data[i]=atoi(data); i =i++; } myfile.close(); speed_l=md49_data[0]; speed_r=md49_data[1]; } else cout << "Unable to open file"; set_MD49_speed(speed_l, speed_r); usleep(200000); }// end.mainloop return 1; } // end.main int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); //fprintf(stderr, "speed=%d\n", bps); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void read_MD49_Data (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); ofstream myfile; myfile.open ("md49_data.txt"); //myfile << "Writing this to a file.\n"; char buffer[33]; EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("====================================================== \n"); printf("Encoder1 Byte1: %i ",serialBuffer[0]); if (serialBuffer[0]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[0],buffer,10); } myfile << "\n"; printf("Byte2: %i ",serialBuffer[1]); if (serialBuffer[1]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[1],buffer,10); } myfile << "\n"; printf("Byte3: % i ",serialBuffer[2]); if (serialBuffer[2]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[2],buffer,10); } myfile << "\n"; printf("Byte4: %i \n",serialBuffer[3]); if (serialBuffer[3]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[3],buffer,10); } myfile << "\n"; printf("Encoder2 Byte1: %i ",serialBuffer[4]); if (serialBuffer[4]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[4],buffer,10); } myfile << "\n"; printf("Byte2: %i ",serialBuffer[5]); if (serialBuffer[5]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[5],buffer,10); } myfile << "\n"; printf("Byte3: %i ",serialBuffer[6]); if (serialBuffer[6]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[6],buffer,10); } myfile << "\n"; printf("Byte4: %i \n",serialBuffer[7]); if (serialBuffer[7]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[7],buffer,10); } myfile << "\n"; printf("EncoderL: %i ",EncoderL); // myfile << itoa(EncoderL,buffer,10); //myfile << "\n"; printf("EncoderR: %i \n",EncoderR); //myfile << itoa(EncoderR,buffer,10); //myfile << "\n"; printf("====================================================== \n"); printf("Speed1: %i ",serialBuffer[8]); if (serialBuffer[8]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[8],buffer,10); } myfile << "\n"; printf("Speed2: %i \n",serialBuffer[9]); if (serialBuffer[9]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[9],buffer,10); } myfile << "\n"; printf("Volts: %i \n",serialBuffer[10]); if (serialBuffer[10]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[10],buffer,10); } myfile << "\n"; printf("Current1: %i ",serialBuffer[11]); if (serialBuffer[11]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[11],buffer,10); } myfile << "\n"; printf("Current2: %i \n",serialBuffer[12]); if (serialBuffer[12]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[12],buffer,10); } myfile << "\n"; printf("Error: %i \n",serialBuffer[13]); if (serialBuffer[13]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[13],buffer,10); } myfile << "\n"; printf("Acceleration: %i \n",serialBuffer[14]); if (serialBuffer[14]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[14],buffer,10); } myfile << "\n"; printf("Mode: %i \n",serialBuffer[15]); if (serialBuffer[15]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[15],buffer,10); } myfile << "\n"; printf("Regulator: %i \n",serialBuffer[16]); if (serialBuffer[16]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[16],buffer,10); } myfile << "\n"; printf("Timeout: %i \n",serialBuffer[17]); if (serialBuffer[17]==0){ myfile << "000"; } else{ myfile << itoa(serialBuffer[17],buffer,10); } myfile << "\n"; printf("speed_l = %i \n",speed_l); printf("speed_r = %i \n",speed_r); myfile.close(); } void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = speed_l; // speed1 serialBuffer[3] = speed_r; // speed2 writeBytes(fd, 4); } char* itoa(int value, char* result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; }
Update code
Update code
C++
bsd-3-clause
Scheik/ROS-Groovy-Workspace,Scheik/ROS-Workspace,Scheik/ROS-Groovy-Workspace,Scheik/ROS-Workspace
bdbb31a1c760906d43037db3579fa906eea71f33
src/providers/verbs/connection.hpp
src/providers/verbs/connection.hpp
// Copyright 2016 Peter Georg // // 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 pMR_PROVIDERS_VERBS_CONNECTION_H #define pMR_PROVIDERS_VERBS_CONNECTION_H #include <cstdint> extern "C" { #include <infiniband/verbs.h> } #include "context.hpp" #include "protectiondomain.hpp" #include "completionqueue.hpp" #include "queuepair.hpp" #include "connectionaddress.hpp" #include "memoryaddress.hpp" #include "memoryregion.hpp" namespace pMR { namespace verbs { class ScatterGatherList; class Connection { public: Connection(Target const &target, Device const &device, std::uint8_t const portNumber = 1); Connection(const Connection&) = delete; Connection(Connection&&) = delete; Connection& operator=(const Connection&) = delete; Connection& operator=(Connection&&) = delete; ~Connection() = default; Context& getContext(); Context const& getContext() const; ProtectionDomain& getProtectionDomain(); ProtectionDomain const& getProtectionDomain() const; void setLocalMemoryAddress(MemoryRegion const&); MemoryAddress const& getRemoteMemoryAddress() const; void postSendAddrRequestToPassive(); void postRecvAddrRequestToActive(); void postSendRequestToActive(MemoryRegion const &memoryRegion); void postSendRequestToActive(MemoryRegion const &memoryRegion, std::uint32_t const sizeByte); void postSendRequestToPassive(MemoryRegion const &memoryRegion); void postSendRequestToPassive(MemoryRegion const &memoryRegion, std::uint32_t const sizeByte); void postRecvRequestToActive(MemoryRegion const &memoryRegion); void postRecvRequestToPassive(MemoryRegion const &memoryRegion); void postRDMAWriteRequestToActive(MemoryRegion const &memoryRegion, MemoryAddress const &remoteMemoryAddress); void postRDMAWriteRequestToActive(MemoryRegion const &memoryRegion, std::uint32_t const sizeByte, MemoryAddress const &remoteMemoryAddress); void postRDMAWriteRequestToPassive(MemoryRegion const &memoryRegion, MemoryAddress const &remoteMemoryAddress); void postRDMAWriteRequestToPassive(MemoryRegion const &memoryRegion, std::uint32_t const sizeByte, MemoryAddress const &remoteMemoryAddress); void postRecvRequestToActive(); void postRecvRequestToPassive(); void pollActiveCompletionQueue(); void pollPassiveCompletionQueue(); private: Context mContext; ProtectionDomain mProtectionDomain; CompletionQueue mActiveCompletionQueue; CompletionQueue mPassiveCompletionQueue; QueuePair mActiveQueuePair; QueuePair mPassiveQueuePair; MemoryAddress mLocalMemoryAddress; MemoryAddress mRemoteMemoryAddress; MemoryRegion mSendMemoryRegion; MemoryRegion mRecvMemoryRegion; std::uint32_t mMaxInlineDataSize = 0; void postSendRequest(QueuePair &queuePair, MemoryRegion const &memoryRegion); void postSendRequest(QueuePair &queuePair, MemoryRegion const &memoryRegion, std::uint32_t const sizeByte); void postSendRequest(QueuePair &queuePair, ibv_sge *scatterGatherList, int const numEntries); void postRecvRequest(QueuePair &queuePair); void postRecvRequest(QueuePair &queuePair, MemoryRegion const &memoryRegion); void postRecvRequest(QueuePair &queuePair, ibv_sge *scatterGatherList, int const numEntries); void postRDMAWriteRequest(QueuePair &queuePair, MemoryRegion const &memoryRegion, MemoryAddress const &remoteMemoryAddress); void postRDMAWriteRequest(QueuePair &queuePair, MemoryRegion const &memoryRegion, std::uint32_t const sizeByte, MemoryAddress const &remoteMemoryAddress); void postRDMAWriteRequest(QueuePair &queuePair, ScatterGatherList &scatterGatherList, MemoryAddress const &remoteMemoryAddress); }; class ScatterGatherList { public: ScatterGatherList(MemoryRegion const&); ScatterGatherList(MemoryRegion const&, std::uint32_t const sizeByte); ibv_sge* get(); ibv_sge const* get() const; std::uint32_t getLength() const; int getNumEntries() const; private: ibv_sge mScatterGatherList; }; }} #endif // pMR_PROVIDERS_VERBS_CONNECTION_H
// Copyright 2016 Peter Georg // // 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 pMR_PROVIDERS_VERBS_CONNECTION_H #define pMR_PROVIDERS_VERBS_CONNECTION_H #include <cstdint> extern "C" { #include <infiniband/verbs.h> } #include "context.hpp" #include "protectiondomain.hpp" #include "completionqueue.hpp" #include "queuepair.hpp" #include "connectionaddress.hpp" #include "memoryaddress.hpp" #include "memoryregion.hpp" #include "config.hpp" namespace pMR { namespace verbs { class ScatterGatherList; class Connection { public: Connection(Target const &target, Device const &device, std::uint8_t const portNumber = 1); Connection(const Connection&) = delete; Connection(Connection&&) = delete; Connection& operator=(const Connection&) = delete; Connection& operator=(Connection&&) = delete; ~Connection() = default; Context& getContext(); Context const& getContext() const; ProtectionDomain& getProtectionDomain(); ProtectionDomain const& getProtectionDomain() const; void setLocalMemoryAddress(MemoryRegion const&); MemoryAddress const& getRemoteMemoryAddress() const; void postSendAddrRequestToPassive(); void postRecvAddrRequestToActive(); void postSendRequestToActive(MemoryRegion const &memoryRegion); void postSendRequestToActive(MemoryRegion const &memoryRegion, std::uint32_t const sizeByte); void postSendRequestToPassive(MemoryRegion const &memoryRegion); void postSendRequestToPassive(MemoryRegion const &memoryRegion, std::uint32_t const sizeByte); void postRecvRequestToActive(MemoryRegion const &memoryRegion); void postRecvRequestToPassive(MemoryRegion const &memoryRegion); void postRDMAWriteRequestToActive(MemoryRegion const &memoryRegion, MemoryAddress const &remoteMemoryAddress); void postRDMAWriteRequestToActive(MemoryRegion const &memoryRegion, std::uint32_t const sizeByte, MemoryAddress const &remoteMemoryAddress); void postRDMAWriteRequestToPassive(MemoryRegion const &memoryRegion, MemoryAddress const &remoteMemoryAddress); void postRDMAWriteRequestToPassive(MemoryRegion const &memoryRegion, std::uint32_t const sizeByte, MemoryAddress const &remoteMemoryAddress); void postRecvRequestToActive(); void postRecvRequestToPassive(); void pollActiveCompletionQueue(); void pollPassiveCompletionQueue(); private: Context mContext; ProtectionDomain mProtectionDomain; CompletionQueue mActiveCompletionQueue; CompletionQueue mPassiveCompletionQueue; QueuePair mActiveQueuePair; QueuePair mPassiveQueuePair; MemoryAddress mLocalMemoryAddress; MemoryAddress mRemoteMemoryAddress; alignas(alignment) MemoryRegion mSendMemoryRegion; alignas(alignment) MemoryRegion mRecvMemoryRegion; std::uint32_t mMaxInlineDataSize = 0; void postSendRequest(QueuePair &queuePair, MemoryRegion const &memoryRegion); void postSendRequest(QueuePair &queuePair, MemoryRegion const &memoryRegion, std::uint32_t const sizeByte); void postSendRequest(QueuePair &queuePair, ibv_sge *scatterGatherList, int const numEntries); void postRecvRequest(QueuePair &queuePair); void postRecvRequest(QueuePair &queuePair, MemoryRegion const &memoryRegion); void postRecvRequest(QueuePair &queuePair, ibv_sge *scatterGatherList, int const numEntries); void postRDMAWriteRequest(QueuePair &queuePair, MemoryRegion const &memoryRegion, MemoryAddress const &remoteMemoryAddress); void postRDMAWriteRequest(QueuePair &queuePair, MemoryRegion const &memoryRegion, std::uint32_t const sizeByte, MemoryAddress const &remoteMemoryAddress); void postRDMAWriteRequest(QueuePair &queuePair, ScatterGatherList &scatterGatherList, MemoryAddress const &remoteMemoryAddress); }; class ScatterGatherList { public: ScatterGatherList(MemoryRegion const&); ScatterGatherList(MemoryRegion const&, std::uint32_t const sizeByte); ibv_sge* get(); ibv_sge const* get() const; std::uint32_t getLength() const; int getNumEntries() const; private: ibv_sge mScatterGatherList; }; }} #endif // pMR_PROVIDERS_VERBS_CONNECTION_H
Align MemoryRegions exchanged with remote
Align MemoryRegions exchanged with remote
C++
apache-2.0
pjgeorg/pMR,pjgeorg/pMR,pjgeorg/pMR
13e0430948b9b5f4d92c556ec1e88e3f651883ac
src/qt/bitcoinaddressvalidator.cpp
src/qt/bitcoinaddressvalidator.cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoinaddressvalidator.h" #include "base58.h" /* Base58 characters are: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" This is: - All numbers except for '0' - All upper-case letters except for 'I' and 'O' - All lower-case letters except for 'l' */ BitcoinAddressEntryValidator::BitcoinAddressEntryValidator(QObject* parent) : QValidator(parent) { } QValidator::State BitcoinAddressEntryValidator::validate(QString& input, int& pos) const { Q_UNUSED(pos); // Empty address is "intermediate" input if (input.isEmpty()) return QValidator::Intermediate; // Correction for (int idx = 0; idx < input.size();) { bool removeChar = false; QChar ch = input.at(idx); // Corrections made are very conservative on purpose, to avoid // users unexpectedly getting away with typos that would normally // be detected, and thus sending to the wrong address. switch (ch.unicode()) { // Qt categorizes these as "Other_Format" not "Separator_Space" case 0x200B: // ZERO WIDTH SPACE case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE removeChar = true; break; default: break; } // Remove whitespace if (ch.isSpace()) removeChar = true; // To next character if (removeChar) input.remove(idx, 1); else ++idx; } // Validation QValidator::State state = QValidator::Acceptable; for (int idx = 0; idx < input.size(); ++idx) { int ch = input.at(idx).unicode(); if (((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) && ch != 'l' && ch != 'I' && ch != '0' && ch != 'O') { // Alphanumeric and not a 'forbidden' character } else { state = QValidator::Invalid; } } return state; } BitcoinAddressCheckValidator::BitcoinAddressCheckValidator(QObject* parent) : QValidator(parent) { } QValidator::State BitcoinAddressCheckValidator::validate(QString& input, int& pos) const { Q_UNUSED(pos); // Validate the passed PIVX address CBitcoinAddress addr(input.toStdString()); if (addr.IsValid()) return QValidator::Acceptable; return QValidator::Invalid; }
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017 The Phore developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoinaddressvalidator.h" #include "base58.h" /* Base58 characters are: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" This is: - All numbers except for '0' - All upper-case letters except for 'I' and 'O' - All lower-case letters except for 'l' */ BitcoinAddressEntryValidator::BitcoinAddressEntryValidator(QObject* parent) : QValidator(parent) { } QValidator::State BitcoinAddressEntryValidator::validate(QString& input, int& pos) const { Q_UNUSED(pos); // Empty address is "intermediate" input if (input.isEmpty()) return QValidator::Intermediate; // Correction for (int idx = 0; idx < input.size();) { bool removeChar = false; QChar ch = input.at(idx); // Corrections made are very conservative on purpose, to avoid // users unexpectedly getting away with typos that would normally // be detected, and thus sending to the wrong address. switch (ch.unicode()) { // Qt categorizes these as "Other_Format" not "Separator_Space" case 0x200B: // ZERO WIDTH SPACE case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE removeChar = true; break; default: break; } // Remove whitespace if (ch.isSpace()) removeChar = true; // To next character if (removeChar) input.remove(idx, 1); else ++idx; } // Validation QValidator::State state = QValidator::Acceptable; for (int idx = 0; idx < input.size(); ++idx) { int ch = input.at(idx).unicode(); if (((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) && ch != 'l' && ch != 'I' && ch != '0' && ch != 'O') { // Alphanumeric and not a 'forbidden' character } else { state = QValidator::Invalid; } } return state; } BitcoinAddressCheckValidator::BitcoinAddressCheckValidator(QObject* parent) : QValidator(parent) { } QValidator::State BitcoinAddressCheckValidator::validate(QString& input, int& pos) const { Q_UNUSED(pos); // Validate the passed Phore address CBitcoinAddress addr(input.toStdString()); if (addr.IsValid()) return QValidator::Acceptable; return QValidator::Invalid; }
Update bitcoinaddressvalidator.cpp
Update bitcoinaddressvalidator.cpp
C++
mit
48thct2jtnf/P,48thct2jtnf/P,48thct2jtnf/P,48thct2jtnf/P,48thct2jtnf/P,48thct2jtnf/P
85db232d366504c0577c8b3063d5b201d0a439bc
src/components/media_manager/src/audio/audio_stream_sender_thread.cc
src/components/media_manager/src/audio/audio_stream_sender_thread.cc
// // Copyright (c) 2014, Ford Motor Company // 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 Ford Motor Company nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. // #if defined(OS_POSIX) && defined(OS_LINUX) #include <pthread.h> // TODO(DK): Need to remove #include <unistd.h> #endif #include <string> #include <string.h> #include "application_manager/application_manager.h" #include "application_manager/mobile_command_factory.h" #include "application_manager/application_impl.h" #include "smart_objects/smart_object.h" #include "interfaces/MOBILE_API.h" #include "utils/file_system.h" #include "utils/logger.h" #include "media_manager/media_manager_settings.h" #include "media_manager/audio/audio_stream_sender_thread.h" #include "application_manager/smart_object_keys.h" #include "application_manager/message.h" namespace media_manager { using sync_primitives::AutoLock; #ifdef EXTENDED_MEDIA_MODE const int32_t AudioStreamSenderThread::kAudioPassThruTimeout = 50; #else const int32_t AudioStreamSenderThread::kAudioPassThruTimeout = 1000; #endif const uint32_t kMqueueMessageSize = 4095; CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManager") AudioStreamSenderThread::AudioStreamSenderThread( const std::string& fileName, uint32_t session_key, application_manager::ApplicationManager& app_mngr) : session_key_(session_key) , fileName_(fileName) , offset_(0) , shouldBeStoped_(false) , shouldBeStoped_lock_() , shouldBeStoped_cv_() , application_manager_(app_mngr) { LOG4CXX_AUTO_TRACE(logger_); } AudioStreamSenderThread::~AudioStreamSenderThread() {} void AudioStreamSenderThread::threadMain() { LOG4CXX_AUTO_TRACE(logger_); offset_ = 0; while (false == getShouldBeStopped()) { AutoLock auto_lock(shouldBeStoped_lock_); shouldBeStoped_cv_.WaitFor(auto_lock, kAudioPassThruTimeout); sendAudioChunkToMobile(); } } void AudioStreamSenderThread::sendAudioChunkToMobile() { LOG4CXX_AUTO_TRACE(logger_); std::vector<uint8_t> binaryData; std::vector<uint8_t>::iterator from; std::vector<uint8_t>::iterator to; if (!file_system::ReadBinaryFile(fileName_, binaryData)) { LOG4CXX_ERROR(logger_, "Unable to read file." << fileName_); return; } if (binaryData.empty()) { LOG4CXX_ERROR(logger_, "Binary data is empty."); return; } LOG4CXX_INFO(logger_, "offset = " << offset_); from = binaryData.begin() + offset_; to = binaryData.end(); if (from < binaryData.end() /*from != binaryData.end()*/) { LOG4CXX_INFO(logger_, "from != binaryData.end()"); offset_ = offset_ + to - from; std::vector<uint8_t> data(from, to); application_manager_.SendAudioPassThroughNotification(session_key_, data); binaryData.clear(); } #if !defined(EXTENDED_MEDIA_MODE) // without recording stream restart reading 1-sec file offset_ = 0; #endif } bool AudioStreamSenderThread::getShouldBeStopped() { AutoLock auto_lock(shouldBeStoped_lock_); return shouldBeStoped_; } void AudioStreamSenderThread::setShouldBeStopped(bool should_stop) { AutoLock auto_lock(shouldBeStoped_lock_); shouldBeStoped_ = should_stop; shouldBeStoped_cv_.NotifyOne(); } void AudioStreamSenderThread::exitThreadMain() { LOG4CXX_AUTO_TRACE(logger_); setShouldBeStopped(true); } uint32_t AudioStreamSenderThread::session_key() const { return session_key_; } } // namespace media_manager
// // Copyright (c) 2014, Ford Motor Company // 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 Ford Motor Company nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. // #if defined(OS_POSIX) && defined(OS_LINUX) #include <pthread.h> // TODO(DK): Need to remove #include <unistd.h> #endif #include <string> #include <string.h> #include "application_manager/application_manager.h" #include "application_manager/mobile_command_factory.h" #include "application_manager/application_impl.h" #include "smart_objects/smart_object.h" #include "interfaces/MOBILE_API.h" #include "utils/file_system.h" #include "utils/logger.h" #include "media_manager/media_manager_settings.h" #include "media_manager/audio/audio_stream_sender_thread.h" #include "application_manager/smart_object_keys.h" #include "application_manager/message.h" namespace media_manager { using sync_primitives::AutoLock; #ifdef EXTENDED_MEDIA_MODE const int32_t AudioStreamSenderThread::kAudioPassThruTimeout = 50; #else const int32_t AudioStreamSenderThread::kAudioPassThruTimeout = 1000; #endif const uint32_t kMqueueMessageSize = 4095; // Size of RIFF header contained in a .wav file: 12 bytes for 'RIFF' chunk // descriptor, 24 bytes for 'fmt ' sub-chunk and 8 bytes for 'data' sub-chunk // header. // The correct format of audio stream for AudioPassThru feature is to include // only audio sample data. Since both pre-recorded file (audio.8bit.wav) and // GStreamer-generated file contain RIFF header, we will skip it when reading // the files. static const uint32_t kRIFFHeaderSize = 44; CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManager") AudioStreamSenderThread::AudioStreamSenderThread( const std::string& fileName, uint32_t session_key, application_manager::ApplicationManager& app_mngr) : session_key_(session_key) , fileName_(fileName) , offset_(kRIFFHeaderSize) , shouldBeStoped_(false) , shouldBeStoped_lock_() , shouldBeStoped_cv_() , application_manager_(app_mngr) { LOG4CXX_AUTO_TRACE(logger_); } AudioStreamSenderThread::~AudioStreamSenderThread() {} void AudioStreamSenderThread::threadMain() { LOG4CXX_AUTO_TRACE(logger_); offset_ = kRIFFHeaderSize; while (false == getShouldBeStopped()) { AutoLock auto_lock(shouldBeStoped_lock_); shouldBeStoped_cv_.WaitFor(auto_lock, kAudioPassThruTimeout); sendAudioChunkToMobile(); } } void AudioStreamSenderThread::sendAudioChunkToMobile() { LOG4CXX_AUTO_TRACE(logger_); std::vector<uint8_t> binaryData; std::vector<uint8_t>::iterator from; std::vector<uint8_t>::iterator to; if (!file_system::ReadBinaryFile(fileName_, binaryData)) { LOG4CXX_ERROR(logger_, "Unable to read file." << fileName_); return; } if (binaryData.empty()) { LOG4CXX_ERROR(logger_, "Binary data is empty."); return; } LOG4CXX_INFO(logger_, "offset = " << offset_); from = binaryData.begin() + offset_; to = binaryData.end(); if (from < binaryData.end() /*from != binaryData.end()*/) { LOG4CXX_INFO(logger_, "from != binaryData.end()"); offset_ = offset_ + to - from; std::vector<uint8_t> data(from, to); application_manager_.SendAudioPassThroughNotification(session_key_, data); binaryData.clear(); } #if !defined(EXTENDED_MEDIA_MODE) // without recording stream restart reading 1-sec file offset_ = kRIFFHeaderSize; #endif } bool AudioStreamSenderThread::getShouldBeStopped() { AutoLock auto_lock(shouldBeStoped_lock_); return shouldBeStoped_; } void AudioStreamSenderThread::setShouldBeStopped(bool should_stop) { AutoLock auto_lock(shouldBeStoped_lock_); shouldBeStoped_ = should_stop; shouldBeStoped_cv_.NotifyOne(); } void AudioStreamSenderThread::exitThreadMain() { LOG4CXX_AUTO_TRACE(logger_); setShouldBeStopped(true); } uint32_t AudioStreamSenderThread::session_key() const { return session_key_; } } // namespace media_manager
remove RIFF header from audio stream for AudioPassThru
fix: remove RIFF header from audio stream for AudioPassThru Please refer to the proposal on https://github.com/smartdevicelink/sdl_evolution/issues/394. The correct format is NOT to include any header.
C++
bsd-3-clause
smartdevicelink/sdl_core,smartdevicelink/sdl_core,smartdevicelink/sdl_core,smartdevicelink/sdl_core
13e598345943ae1cbe458f2b5cf56618928001c2
chrome/browser/chromeos/login/screen_locker_browsertest.cc
chrome/browser/chromeos/login/screen_locker_browsertest.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h" #include "chrome/browser/chromeos/cros/mock_network_library.h" #include "chrome/browser/chromeos/login/mock_authenticator.h" #include "chrome/browser/chromeos/login/screen_locker.h" #include "chrome/browser/chromeos/login/screen_locker_tester.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/fullscreen/fullscreen_controller.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "chromeos/dbus/mock_dbus_thread_manager.h" #include "chromeos/dbus/mock_power_manager_client.h" #include "content/public/browser/notification_service.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/ui_controls/ui_controls.h" #include "ui/views/widget/widget.h" namespace { // An object that wait for lock state and fullscreen state. class Waiter : public content::NotificationObserver { public: explicit Waiter(Browser* browser) : browser_(browser), running_(false) { registrar_.Add(this, chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_FULLSCREEN_CHANGED, content::NotificationService::AllSources()); } virtual ~Waiter() { } virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK(type == chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED || type == chrome::NOTIFICATION_FULLSCREEN_CHANGED); if (running_) MessageLoop::current()->Quit(); } // Wait until the two conditions are met. void Wait(bool locker_state, bool fullscreen) { running_ = true; scoped_ptr<chromeos::test::ScreenLockerTester> tester(chromeos::ScreenLocker::GetTester()); while (tester->IsLocked() != locker_state || browser_->window()->IsFullscreen() != fullscreen) { ui_test_utils::RunMessageLoop(); } // Make sure all pending tasks are executed. ui_test_utils::RunAllPendingInMessageLoop(); running_ = false; } private: Browser* browser_; content::NotificationRegistrar registrar_; // Are we currently running the message loop? bool running_; DISALLOW_COPY_AND_ASSIGN(Waiter); }; } // namespace namespace chromeos { class ScreenLockerTest : public CrosInProcessBrowserTest { public: ScreenLockerTest() : mock_power_manager_client_(NULL) { } protected: MockPowerManagerClient* mock_power_manager_client_; // Test the no password mode with different unlock scheme given by // |unlock| function. void TestNoPassword(void (unlock)(views::Widget*)) { EXPECT_CALL(*mock_power_manager_client_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); UserManager::Get()->GuestUserLoggedIn(); ScreenLocker::Show(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); tester->EmulateWindowManagerReady(); ui_test_utils::WindowedNotificationObserver lock_state_observer( chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED, content::NotificationService::AllSources()); if (!chromeos::ScreenLocker::GetTester()->IsLocked()) lock_state_observer.Wait(); EXPECT_TRUE(tester->IsLocked()); tester->InjectMockAuthenticator("", ""); unlock(tester->GetWidget()); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(tester->IsLocked()); // Emulate UnlockScreen request from SessionManager. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } void LockScreenWithUser(test::ScreenLockerTester* tester, const std::string& user) { UserManager::Get()->UserLoggedIn(user, true); ScreenLocker::Show(); tester->EmulateWindowManagerReady(); ui_test_utils::WindowedNotificationObserver lock_state_observer( chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED, content::NotificationService::AllSources()); if (!tester->IsLocked()) lock_state_observer.Wait(); EXPECT_TRUE(tester->IsLocked()); } private: virtual void SetUpInProcessBrowserTestFixture() { MockDBusThreadManager* mock_dbus_thread_manager = new MockDBusThreadManager; DBusThreadManager::InitializeForTesting(mock_dbus_thread_manager); CrosInProcessBrowserTest::SetUpInProcessBrowserTestFixture(); mock_power_manager_client_ = static_cast<MockPowerManagerClient*>( DBusThreadManager::Get()->GetPowerManagerClient()); cros_mock_->InitStatusAreaMocks(); EXPECT_CALL(*mock_power_manager_client_, AddObserver(testing::_)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*mock_power_manager_client_, NotifyScreenUnlockCompleted()) .Times(1) .RetiresOnSaturation(); // Expectations for the status are on the screen lock window. cros_mock_->SetStatusAreaMocksExpectations(); MockNetworkLibrary* mock_network_library = cros_mock_->mock_network_library(); EXPECT_CALL(*mock_network_library, AddUserActionObserver(testing::_)) .Times(testing::AnyNumber()); } virtual void SetUpCommandLine(CommandLine* command_line) { command_line->AppendSwitchASCII(switches::kLoginProfile, "user"); command_line->AppendSwitch(switches::kNoFirstRun); } DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest); }; IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) { EXPECT_CALL(*mock_power_manager_client_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); ScreenLocker::Show(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); tester->EmulateWindowManagerReady(); ui_test_utils::WindowedNotificationObserver lock_state_observer( chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED, content::NotificationService::AllSources()); if (!chromeos::ScreenLocker::GetTester()->IsLocked()) lock_state_observer.Wait(); // Test to make sure that the widget is actually appearing and is of // reasonable size, preventing a regression of // http://code.google.com/p/chromium-os/issues/detail?id=5987 gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds(); EXPECT_GT(lock_bounds.width(), 10); EXPECT_GT(lock_bounds.height(), 10); tester->InjectMockAuthenticator(UserManager::kStubUser, "pass"); EXPECT_TRUE(tester->IsLocked()); tester->EnterPassword("fail"); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(tester->IsLocked()); tester->EnterPassword("pass"); ui_test_utils::RunAllPendingInMessageLoop(); // Successful authentication simply send a unlock request to PowerManager. EXPECT_TRUE(tester->IsLocked()); // Emulate LockScreen request from SessionManager. // TODO(oshima): Find out better way to handle this in mock. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) { EXPECT_CALL(*mock_power_manager_client_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); { Waiter waiter(browser()); browser()->fullscreen_controller()->ToggleFullscreenMode(); waiter.Wait(false /* not locked */, true /* full screen */); EXPECT_TRUE(browser()->window()->IsFullscreen()); EXPECT_FALSE(tester->IsLocked()); } { Waiter waiter(browser()); ScreenLocker::Show(); tester->EmulateWindowManagerReady(); waiter.Wait(true /* locked */, false /* full screen */); EXPECT_FALSE(browser()->window()->IsFullscreen()); EXPECT_TRUE(tester->IsLocked()); } tester->InjectMockAuthenticator(UserManager::kStubUser, "pass"); tester->EnterPassword("pass"); ui_test_utils::RunAllPendingInMessageLoop(); ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } void SimulateKeyPress(views::Widget* widget, ui::KeyboardCode key_code) { ui_controls::SendKeyPress(widget->GetNativeWindow(), key_code, false, false, false, false); } void UnlockKeyPress(views::Widget* widget) { SimulateKeyPress(widget, ui::VKEY_SPACE); } IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestShowTwice) { EXPECT_CALL(*mock_power_manager_client_, NotifyScreenLockCompleted()) .Times(2) .RetiresOnSaturation(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); LockScreenWithUser(tester.get(), UserManager::kStubUser); // Ensure there's a profile or this test crashes. ProfileManager::GetDefaultProfile(); // Calling Show again simply send LockCompleted signal. ScreenLocker::Show(); EXPECT_TRUE(tester->IsLocked()); // Close the locker to match expectations. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestEscape) { EXPECT_CALL(*mock_power_manager_client_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); LockScreenWithUser(tester.get(), UserManager::kStubUser); // Ensure there's a profile or this test crashes. ProfileManager::GetDefaultProfile(); tester->SetPassword("password"); EXPECT_EQ("password", tester->GetPassword()); // Escape clears the password. SimulateKeyPress(tester->GetWidget(), ui::VKEY_ESCAPE); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_EQ("", tester->GetPassword()); // Close the locker to match expectations. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } } // namespace chromeos
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h" #include "chrome/browser/chromeos/cros/mock_network_library.h" #include "chrome/browser/chromeos/login/mock_authenticator.h" #include "chrome/browser/chromeos/login/screen_locker.h" #include "chrome/browser/chromeos/login/screen_locker_tester.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/fullscreen/fullscreen_controller.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "chromeos/dbus/mock_dbus_thread_manager.h" #include "chromeos/dbus/mock_power_manager_client.h" #include "content/public/browser/notification_service.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/ui_controls/ui_controls.h" #include "ui/views/widget/widget.h" namespace { // An object that wait for lock state and fullscreen state. class Waiter : public content::NotificationObserver { public: explicit Waiter(Browser* browser) : browser_(browser), running_(false) { registrar_.Add(this, chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_FULLSCREEN_CHANGED, content::NotificationService::AllSources()); } virtual ~Waiter() { } virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK(type == chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED || type == chrome::NOTIFICATION_FULLSCREEN_CHANGED); if (running_) MessageLoop::current()->Quit(); } // Wait until the two conditions are met. void Wait(bool locker_state, bool fullscreen) { running_ = true; scoped_ptr<chromeos::test::ScreenLockerTester> tester(chromeos::ScreenLocker::GetTester()); while (tester->IsLocked() != locker_state || browser_->window()->IsFullscreen() != fullscreen) { ui_test_utils::RunMessageLoop(); } // Make sure all pending tasks are executed. ui_test_utils::RunAllPendingInMessageLoop(); running_ = false; } private: Browser* browser_; content::NotificationRegistrar registrar_; // Are we currently running the message loop? bool running_; DISALLOW_COPY_AND_ASSIGN(Waiter); }; } // namespace namespace chromeos { class ScreenLockerTest : public CrosInProcessBrowserTest { public: ScreenLockerTest() : mock_power_manager_client_(NULL) { } protected: MockPowerManagerClient* mock_power_manager_client_; // Test the no password mode with different unlock scheme given by // |unlock| function. void TestNoPassword(void (unlock)(views::Widget*)) { EXPECT_CALL(*mock_power_manager_client_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); UserManager::Get()->GuestUserLoggedIn(); ScreenLocker::Show(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); tester->EmulateWindowManagerReady(); ui_test_utils::WindowedNotificationObserver lock_state_observer( chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED, content::NotificationService::AllSources()); if (!chromeos::ScreenLocker::GetTester()->IsLocked()) lock_state_observer.Wait(); EXPECT_TRUE(tester->IsLocked()); tester->InjectMockAuthenticator("", ""); unlock(tester->GetWidget()); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(tester->IsLocked()); // Emulate UnlockScreen request from SessionManager. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } void LockScreenWithUser(test::ScreenLockerTester* tester, const std::string& user) { UserManager::Get()->UserLoggedIn(user, true); ScreenLocker::Show(); tester->EmulateWindowManagerReady(); ui_test_utils::WindowedNotificationObserver lock_state_observer( chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED, content::NotificationService::AllSources()); if (!tester->IsLocked()) lock_state_observer.Wait(); EXPECT_TRUE(tester->IsLocked()); } private: virtual void SetUpInProcessBrowserTestFixture() { MockDBusThreadManager* mock_dbus_thread_manager = new MockDBusThreadManager; DBusThreadManager::InitializeForTesting(mock_dbus_thread_manager); CrosInProcessBrowserTest::SetUpInProcessBrowserTestFixture(); mock_power_manager_client_ = static_cast<MockPowerManagerClient*>( DBusThreadManager::Get()->GetPowerManagerClient()); cros_mock_->InitStatusAreaMocks(); EXPECT_CALL(*mock_power_manager_client_, AddObserver(testing::_)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*mock_power_manager_client_, NotifyScreenUnlockCompleted()) .Times(1) .RetiresOnSaturation(); // Expectations for the status are on the screen lock window. cros_mock_->SetStatusAreaMocksExpectations(); MockNetworkLibrary* mock_network_library = cros_mock_->mock_network_library(); EXPECT_CALL(*mock_network_library, AddUserActionObserver(testing::_)) .Times(testing::AnyNumber()); } virtual void SetUpCommandLine(CommandLine* command_line) { command_line->AppendSwitchASCII(switches::kLoginProfile, "user"); command_line->AppendSwitch(switches::kNoFirstRun); } DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest); }; IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) { EXPECT_CALL(*mock_power_manager_client_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); ScreenLocker::Show(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); tester->EmulateWindowManagerReady(); ui_test_utils::WindowedNotificationObserver lock_state_observer( chrome::NOTIFICATION_SCREEN_LOCK_STATE_CHANGED, content::NotificationService::AllSources()); if (!chromeos::ScreenLocker::GetTester()->IsLocked()) lock_state_observer.Wait(); // Test to make sure that the widget is actually appearing and is of // reasonable size, preventing a regression of // http://code.google.com/p/chromium-os/issues/detail?id=5987 gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds(); EXPECT_GT(lock_bounds.width(), 10); EXPECT_GT(lock_bounds.height(), 10); tester->InjectMockAuthenticator(UserManager::kStubUser, "pass"); EXPECT_TRUE(tester->IsLocked()); tester->EnterPassword("fail"); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(tester->IsLocked()); tester->EnterPassword("pass"); ui_test_utils::RunAllPendingInMessageLoop(); // Successful authentication simply send a unlock request to PowerManager. EXPECT_TRUE(tester->IsLocked()); // Emulate LockScreen request from SessionManager. // TODO(oshima): Find out better way to handle this in mock. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) { EXPECT_CALL(*mock_power_manager_client_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); { Waiter waiter(browser()); browser()->fullscreen_controller()->ToggleFullscreenMode(); waiter.Wait(false /* not locked */, true /* full screen */); EXPECT_TRUE(browser()->window()->IsFullscreen()); EXPECT_FALSE(tester->IsLocked()); } { Waiter waiter(browser()); ScreenLocker::Show(); tester->EmulateWindowManagerReady(); waiter.Wait(true /* locked */, false /* full screen */); EXPECT_FALSE(browser()->window()->IsFullscreen()); EXPECT_TRUE(tester->IsLocked()); } tester->InjectMockAuthenticator(UserManager::kStubUser, "pass"); tester->EnterPassword("pass"); ui_test_utils::RunAllPendingInMessageLoop(); ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } void SimulateKeyPress(views::Widget* widget, ui::KeyboardCode key_code) { ui_controls::SendKeyPress(widget->GetNativeWindow(), key_code, false, false, false, false); } void UnlockKeyPress(views::Widget* widget) { SimulateKeyPress(widget, ui::VKEY_SPACE); } IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestShowTwice) { EXPECT_CALL(*mock_power_manager_client_, NotifyScreenLockCompleted()) .Times(2) .RetiresOnSaturation(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); LockScreenWithUser(tester.get(), UserManager::kStubUser); // Ensure there's a profile or this test crashes. ProfileManager::GetDefaultProfile(); // Calling Show again simply send LockCompleted signal. ScreenLocker::Show(); EXPECT_TRUE(tester->IsLocked()); // Close the locker to match expectations. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } // TODO(flackr): Find out why the RenderView isn't getting the escape press // and re-enable this test (currently this test is flaky). IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) { EXPECT_CALL(*mock_power_manager_client_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); LockScreenWithUser(tester.get(), UserManager::kStubUser); // Ensure there's a profile or this test crashes. ProfileManager::GetDefaultProfile(); tester->SetPassword("password"); EXPECT_EQ("password", tester->GetPassword()); // Escape clears the password. SimulateKeyPress(tester->GetWidget(), ui::VKEY_ESCAPE); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_EQ("", tester->GetPassword()); // Close the locker to match expectations. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } } // namespace chromeos
Disable flaky ScreenLockerTest.TestEscape.
Disable flaky ScreenLockerTest.TestEscape. BUG=137488 TEST=ScreenLockerTest.* TBR=flackr Review URL: https://chromiumcodereview.appspot.com/10790051 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@147233 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
anirudhSK/chromium,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,hujiajie/pa-chromium,anirudhSK/chromium,mogoweb/chromium-crosswalk,patrickm/chromium.src,ltilve/chromium,axinging/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,hujiajie/pa-chromium,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,M4sse/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,keishi/chromium,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,ondra-novak/chromium.src,hujiajie/pa-chromium,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,nacl-webkit/chrome_deps,M4sse/chromium.src,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,Chilledheart/chromium,Just-D/chromium-1,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,patrickm/chromium.src,ltilve/chromium,hujiajie/pa-chromium,keishi/chromium,ltilve/chromium,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,keishi/chromium,ltilve/chromium,fujunwei/chromium-crosswalk,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,anirudhSK/chromium,timopulkkinen/BubbleFish,Jonekee/chromium.src,axinging/chromium-crosswalk,patrickm/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,Just-D/chromium-1,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,dednal/chromium.src,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,hgl888/chromium-crosswalk,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,dushu1203/chromium.src,patrickm/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,keishi/chromium,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,ChromiumWebApps/chromium,zcbenz/cefode-chromium,keishi/chromium,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,littlstar/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,ltilve/chromium,jaruba/chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,M4sse/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,Jonekee/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,nacl-webkit/chrome_deps,markYoungH/chromium.src,hgl888/chromium-crosswalk,keishi/chromium,dushu1203/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,jaruba/chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,markYoungH/chromium.src,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,keishi/chromium,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,Chilledheart/chromium,zcbenz/cefode-chromium,ChromiumWebApps/chromium,keishi/chromium,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,ltilve/chromium,axinging/chromium-crosswalk,jaruba/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,ondra-novak/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,dednal/chromium.src,keishi/chromium,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,dednal/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,zcbenz/cefode-chromium,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,keishi/chromium,hgl888/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,anirudhSK/chromium,dednal/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,M4sse/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,dushu1203/chromium.src,patrickm/chromium.src,anirudhSK/chromium,dednal/chromium.src,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,dushu1203/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,keishi/chromium,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,hujiajie/pa-chromium,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,zcbenz/cefode-chromium,ondra-novak/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,littlstar/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,nacl-webkit/chrome_deps,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,nacl-webkit/chrome_deps,M4sse/chromium.src,hujiajie/pa-chromium,littlstar/chromium.src
3a9f39c6cdb098011f8fc225ade77f87ef548c3d
modules/globebrowsing/globes/renderableglobe.cpp
modules/globebrowsing/globes/renderableglobe.cpp
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2016 * * * * 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 <modules/globebrowsing/globes/renderableglobe.h> #include <modules/globebrowsing/globes/globemesh.h> #include <modules/globebrowsing/other/threadpool.h> // open space includes #include <openspace/engine/openspaceengine.h> #include <openspace/rendering/renderengine.h> #include <openspace/util/spicemanager.h> #include <openspace/scene/scenegraphnode.h> // ghoul includes #include <ghoul/misc/assert.h> namespace { const std::string _loggerCat = "RenderableGlobe"; // Keys for the dictionary const std::string keyRadii = "Radii"; const std::string keySegmentsPerPatch = "SegmentsPerPatch"; const std::string keyTextures = "Textures"; const std::string keyColorTextures = "ColorTextures"; const std::string keyHeightMaps = "HeightMaps"; } namespace openspace { RenderableGlobe::RenderableGlobe(const ghoul::Dictionary& dictionary) : _tileProviderManager(std::shared_ptr<TileProviderManager>(new TileProviderManager)) , _saveOrThrowCamera(properties::BoolProperty("saveOrThrowCamera", "saveOrThrowCamera")) , doFrustumCulling(properties::BoolProperty("doFrustumCulling", "doFrustumCulling")) , doHorizonCulling(properties::BoolProperty("doHorizonCulling", "doHorizonCulling")) , mergeInvisible(properties::BoolProperty("mergeInvisible", "mergeInvisible", true)) , lodScaleFactor(properties::FloatProperty("lodScaleFactor", "lodScaleFactor", 5.0f, 0.0f, 20.0f)) , initChunkVisible(properties::BoolProperty("initChunkVisible", "initChunkVisible", true)) , renderSmallChunksFirst(properties::BoolProperty("renderSmallChunksFirst", "renderSmallChunksFirst", true)) { setName("RenderableGlobe"); addProperty(_saveOrThrowCamera); addProperty(doFrustumCulling); addProperty(doHorizonCulling); addProperty(mergeInvisible); addProperty(lodScaleFactor); addProperty(initChunkVisible); addProperty(renderSmallChunksFirst); doFrustumCulling.setValue(true); doHorizonCulling.setValue(true); renderSmallChunksFirst.setValue(true); // Read the radii in to its own dictionary Vec3 radii; double patchSegmentsd; dictionary.getValue(keyRadii, radii); // Ghoul can't read ints from lua dictionaries dictionary.getValue(keySegmentsPerPatch, patchSegmentsd); int patchSegments = patchSegmentsd; _ellipsoid = Ellipsoid(radii); setBoundingSphere(pss(_ellipsoid.averageRadius(), 0.0)); ghoul::Dictionary texturesDictionary; dictionary.getValue(keyTextures, texturesDictionary); ghoul::Dictionary colorTexturesDictionary; texturesDictionary.getValue(keyColorTextures, colorTexturesDictionary); int minimumTextureSide = 1024; int minimumHeightmapSize = 64; int frameUntilFlushRequestQueue = 60; int cacheSize = 5000; // Create TileProviders for all color textures for (size_t i = 1; i < colorTexturesDictionary.size() + 1; i++) { std::string name, path; ghoul::Dictionary colorTextureDictionary = colorTexturesDictionary.value<ghoul::Dictionary>(std::to_string(i)); colorTextureDictionary.getValue("Name", name); colorTextureDictionary.getValue("FilePath", path); std::shared_ptr<TileDataset> tileDataset = std::shared_ptr<TileDataset>( new TileDataset(path, minimumTextureSide)); std::shared_ptr<ThreadPool> threadPool = std::shared_ptr<ThreadPool>( new ThreadPool(1)); std::shared_ptr<AsyncTileDataProvider> tileReader = std::shared_ptr<AsyncTileDataProvider>( new AsyncTileDataProvider(tileDataset, threadPool)); std::shared_ptr<TileProvider> colorTextureProvider = std::shared_ptr<TileProvider>( new TileProvider(tileReader, cacheSize, frameUntilFlushRequestQueue)); _tileProviderManager->addColorTexture(name, colorTextureProvider, true); // Create property for this tile provider _activeColorLayers.push_back(properties::BoolProperty(name, name, true)); } ghoul::Dictionary heightMapsDictionary; texturesDictionary.getValue(keyHeightMaps, heightMapsDictionary); // Create TileProviders for all height maps for (size_t i = 1; i < heightMapsDictionary.size() + 1; i++) { std::string name, path; ghoul::Dictionary heightMapDictionary = heightMapsDictionary.value<ghoul::Dictionary>(std::to_string(i)); heightMapDictionary.getValue("Name", name); heightMapDictionary.getValue("FilePath", path); std::shared_ptr<TileDataset> tileDataset = std::shared_ptr<TileDataset>( new TileDataset(path, minimumHeightmapSize)); std::shared_ptr<ThreadPool> threadPool = std::shared_ptr<ThreadPool>( new ThreadPool(1)); std::shared_ptr<AsyncTileDataProvider> tileReader = std::shared_ptr<AsyncTileDataProvider>( new AsyncTileDataProvider(tileDataset, threadPool)); std::shared_ptr<TileProvider> heightMapProvider = std::shared_ptr<TileProvider>( new TileProvider(tileReader, cacheSize, frameUntilFlushRequestQueue)); _tileProviderManager->addHeightMap(name, heightMapProvider, true); // Create property for this tile provider _activeHeightMapLayers.push_back(properties::BoolProperty(name, name, true)); } // Add properties for the tile providers for (auto it = _activeColorLayers.begin(); it != _activeColorLayers.end(); it++) { addProperty(*it); } for (auto it = _activeHeightMapLayers.begin(); it != _activeHeightMapLayers.end(); it++) { addProperty(*it); } _chunkedLodGlobe = std::shared_ptr<ChunkedLodGlobe>( new ChunkedLodGlobe(_ellipsoid, patchSegments, _tileProviderManager)); _distanceSwitch.addSwitchValue(_chunkedLodGlobe, 1e12); } RenderableGlobe::~RenderableGlobe() { } bool RenderableGlobe::initialize() { return _distanceSwitch.initialize(); } bool RenderableGlobe::deinitialize() { return _distanceSwitch.deinitialize(); } bool RenderableGlobe::isReady() const { return _distanceSwitch.isReady(); } void RenderableGlobe::render(const RenderData& data) { if (_saveOrThrowCamera.value()) { _saveOrThrowCamera.setValue(false); if (_chunkedLodGlobe->getSavedCamera() == nullptr) { // save camera LDEBUG("Saving snapshot of camera!"); _chunkedLodGlobe->setSaveCamera(new Camera(data.camera)); } else { // throw camera LDEBUG("Throwing away saved camera!"); _chunkedLodGlobe->setSaveCamera(nullptr); } } _distanceSwitch.render(data); } void RenderableGlobe::update(const UpdateData& data) { _time = data.time; _distanceSwitch.update(data); _chunkedLodGlobe->doFrustumCulling = doFrustumCulling.value(); _chunkedLodGlobe->doHorizonCulling = doHorizonCulling.value(); _chunkedLodGlobe->mergeInvisible = mergeInvisible.value(); _chunkedLodGlobe->lodScaleFactor = lodScaleFactor.value(); _chunkedLodGlobe->initChunkVisible = initChunkVisible.value(); std::vector<TileProviderManager::TileProviderWithName>& colorTextureProviders = _tileProviderManager->colorTextureProviders(); std::vector<TileProviderManager::TileProviderWithName>& heightMapProviders = _tileProviderManager->heightMapProviders(); for (size_t i = 0; i < colorTextureProviders.size(); i++) { colorTextureProviders[i].isActive = _activeColorLayers[i].value(); } for (size_t i = 0; i < heightMapProviders.size(); i++) { heightMapProviders[i].isActive = _activeHeightMapLayers[i].value(); } } glm::dvec3 RenderableGlobe::geodeticSurfaceProjection(glm::dvec3 position) { return _ellipsoid.geodeticSurfaceProjection(position); } } // namespace openspace
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2016 * * * * 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 <modules/globebrowsing/globes/renderableglobe.h> #include <modules/globebrowsing/globes/globemesh.h> #include <modules/globebrowsing/other/threadpool.h> // open space includes #include <openspace/engine/openspaceengine.h> #include <openspace/rendering/renderengine.h> #include <openspace/util/spicemanager.h> #include <openspace/scene/scenegraphnode.h> // ghoul includes #include <ghoul/misc/assert.h> namespace { const std::string _loggerCat = "RenderableGlobe"; // Keys for the dictionary const std::string keyRadii = "Radii"; const std::string keySegmentsPerPatch = "SegmentsPerPatch"; const std::string keyTextures = "Textures"; const std::string keyColorTextures = "ColorTextures"; const std::string keyHeightMaps = "HeightMaps"; } namespace openspace { RenderableGlobe::RenderableGlobe(const ghoul::Dictionary& dictionary) : _tileProviderManager(std::shared_ptr<TileProviderManager>(new TileProviderManager)) , _saveOrThrowCamera(properties::BoolProperty("saveOrThrowCamera", "saveOrThrowCamera")) , doFrustumCulling(properties::BoolProperty("doFrustumCulling", "doFrustumCulling")) , doHorizonCulling(properties::BoolProperty("doHorizonCulling", "doHorizonCulling")) , mergeInvisible(properties::BoolProperty("mergeInvisible", "mergeInvisible", true)) , lodScaleFactor(properties::FloatProperty("lodScaleFactor", "lodScaleFactor", 5.0f, 0.0f, 20.0f)) , initChunkVisible(properties::BoolProperty("initChunkVisible", "initChunkVisible", true)) , renderSmallChunksFirst(properties::BoolProperty("renderSmallChunksFirst", "renderSmallChunksFirst", true)) { setName("RenderableGlobe"); addProperty(_saveOrThrowCamera); addProperty(doFrustumCulling); addProperty(doHorizonCulling); addProperty(mergeInvisible); addProperty(lodScaleFactor); addProperty(initChunkVisible); addProperty(renderSmallChunksFirst); doFrustumCulling.setValue(true); doHorizonCulling.setValue(true); renderSmallChunksFirst.setValue(true); // Read the radii in to its own dictionary Vec3 radii; double patchSegmentsd; dictionary.getValue(keyRadii, radii); // Ghoul can't read ints from lua dictionaries dictionary.getValue(keySegmentsPerPatch, patchSegmentsd); int patchSegments = patchSegmentsd; _ellipsoid = Ellipsoid(radii); setBoundingSphere(pss(_ellipsoid.averageRadius(), 0.0)); ghoul::Dictionary texturesDictionary; dictionary.getValue(keyTextures, texturesDictionary); ghoul::Dictionary colorTexturesDictionary; texturesDictionary.getValue(keyColorTextures, colorTexturesDictionary); int minimumTextureSide = 1024; int minimumHeightmapSize = 64; int frameUntilFlushRequestQueue = 60; int cacheSize = 5000; // Create TileProviders for all color textures for (size_t i = 0; i < colorTexturesDictionary.size(); i++) { std::string name, path; std::string dictionaryKey = std::to_string(i + 1); ghoul::Dictionary colorTextureDictionary = colorTexturesDictionary.value<ghoul::Dictionary>(dictionaryKey); colorTextureDictionary.getValue("Name", name); colorTextureDictionary.getValue("FilePath", path); std::shared_ptr<TileDataset> tileDataset = std::shared_ptr<TileDataset>( new TileDataset(path, minimumTextureSide)); std::shared_ptr<ThreadPool> threadPool = std::shared_ptr<ThreadPool>( new ThreadPool(1)); std::shared_ptr<AsyncTileDataProvider> tileReader = std::shared_ptr<AsyncTileDataProvider>( new AsyncTileDataProvider(tileDataset, threadPool)); std::shared_ptr<TileProvider> colorTextureProvider = std::shared_ptr<TileProvider>( new TileProvider(tileReader, cacheSize, frameUntilFlushRequestQueue)); _tileProviderManager->addColorTexture(name, colorTextureProvider, true); // Create property for this tile provider bool enabled = i == 0; // Only enable first layer _activeColorLayers.push_back(properties::BoolProperty(name, name, enabled)); } ghoul::Dictionary heightMapsDictionary; texturesDictionary.getValue(keyHeightMaps, heightMapsDictionary); // Create TileProviders for all height maps for (size_t i = 0; i < heightMapsDictionary.size(); i++) { std::string name, path; std::string dictionaryKey = std::to_string(i + 1); ghoul::Dictionary heightMapDictionary = heightMapsDictionary.value<ghoul::Dictionary>(dictionaryKey); heightMapDictionary.getValue("Name", name); heightMapDictionary.getValue("FilePath", path); std::shared_ptr<TileDataset> tileDataset = std::shared_ptr<TileDataset>( new TileDataset(path, minimumHeightmapSize)); std::shared_ptr<ThreadPool> threadPool = std::shared_ptr<ThreadPool>( new ThreadPool(1)); std::shared_ptr<AsyncTileDataProvider> tileReader = std::shared_ptr<AsyncTileDataProvider>( new AsyncTileDataProvider(tileDataset, threadPool)); std::shared_ptr<TileProvider> heightMapProvider = std::shared_ptr<TileProvider>( new TileProvider(tileReader, cacheSize, frameUntilFlushRequestQueue)); _tileProviderManager->addHeightMap(name, heightMapProvider, true); // Create property for this tile provider bool enabled = i == 0; // Only enable first layer _activeHeightMapLayers.push_back(properties::BoolProperty(name, name, enabled)); } // Add properties for the tile providers for (auto it = _activeColorLayers.begin(); it != _activeColorLayers.end(); it++) { addProperty(*it); } for (auto it = _activeHeightMapLayers.begin(); it != _activeHeightMapLayers.end(); it++) { addProperty(*it); } _chunkedLodGlobe = std::shared_ptr<ChunkedLodGlobe>( new ChunkedLodGlobe(_ellipsoid, patchSegments, _tileProviderManager)); _distanceSwitch.addSwitchValue(_chunkedLodGlobe, 1e12); } RenderableGlobe::~RenderableGlobe() { } bool RenderableGlobe::initialize() { return _distanceSwitch.initialize(); } bool RenderableGlobe::deinitialize() { return _distanceSwitch.deinitialize(); } bool RenderableGlobe::isReady() const { return _distanceSwitch.isReady(); } void RenderableGlobe::render(const RenderData& data) { if (_saveOrThrowCamera.value()) { _saveOrThrowCamera.setValue(false); if (_chunkedLodGlobe->getSavedCamera() == nullptr) { // save camera LDEBUG("Saving snapshot of camera!"); _chunkedLodGlobe->setSaveCamera(new Camera(data.camera)); } else { // throw camera LDEBUG("Throwing away saved camera!"); _chunkedLodGlobe->setSaveCamera(nullptr); } } _distanceSwitch.render(data); } void RenderableGlobe::update(const UpdateData& data) { _time = data.time; _distanceSwitch.update(data); _chunkedLodGlobe->doFrustumCulling = doFrustumCulling.value(); _chunkedLodGlobe->doHorizonCulling = doHorizonCulling.value(); _chunkedLodGlobe->mergeInvisible = mergeInvisible.value(); _chunkedLodGlobe->lodScaleFactor = lodScaleFactor.value(); _chunkedLodGlobe->initChunkVisible = initChunkVisible.value(); std::vector<TileProviderManager::TileProviderWithName>& colorTextureProviders = _tileProviderManager->colorTextureProviders(); std::vector<TileProviderManager::TileProviderWithName>& heightMapProviders = _tileProviderManager->heightMapProviders(); for (size_t i = 0; i < colorTextureProviders.size(); i++) { colorTextureProviders[i].isActive = _activeColorLayers[i].value(); } for (size_t i = 0; i < heightMapProviders.size(); i++) { heightMapProviders[i].isActive = _activeHeightMapLayers[i].value(); } } glm::dvec3 RenderableGlobe::geodeticSurfaceProjection(glm::dvec3 position) { return _ellipsoid.geodeticSurfaceProjection(position); } } // namespace openspace
Initialize only the first color texture and heightmap as active
Initialize only the first color texture and heightmap as active
C++
mit
OpenSpace/OpenSpace,OpenSpace/OpenSpace,OpenSpace/OpenSpace,OpenSpace/OpenSpace
787398871efe29b6c156c412309d042e89ad8697
src/pub14_core/terrain/terrain_service.cc
src/pub14_core/terrain/terrain_service.cc
#include "terrain_service.h" #include <map> #include "pub14_core/simulation/scene_events.h" #include <anh/event_dispatcher.h> #include <anh/logger.h> #include "swganh/tre/resource_manager.h" //#include "swganh/tre/visitors/terrain/layer_visitor.h" #include "swganh/tre/visitors/terrain/terrain_visitor.h" #include "swganh/tre/visitors/terrain/detail/container_layer.h" #include "swganh/tre/visitors/terrain/detail/boundary_layer.h" #include "swganh/tre/visitors/terrain/detail/height_layer.h" #include "swganh/tre/visitors/terrain/detail/filter_layer.h" #include "swganh/tre/visitors/terrain/detail/boundary_polygon.h" #include "swganh/tre/visitors/terrain/detail/header.h" using namespace swganh_core::terrain; using namespace swganh::tre; TerrainService::TerrainService(swganh::app::SwganhKernel* kernel) : kernel_(kernel) { kernel_->GetEventDispatcher()->Subscribe("SceneManager:NewScene", [&] (const std::shared_ptr<anh::EventInterface>& newEvent) { auto real_event = std::static_pointer_cast<swganh_core::simulation::NewSceneEvent>(newEvent); try { auto visitor = kernel_->GetResourceManager()->getResourceByName(real_event->terrain_filename, TRN_VISITOR); SceneEntry entry; entry.terrain_visitor_ = std::static_pointer_cast<TerrainVisitor>(visitor); scenes_.insert(SceneMap::value_type(real_event->scene_id, std::move(entry))); } catch(...) { LOG(error) << "Failed to load trn file: " << real_event->terrain_filename; } }); kernel_->GetEventDispatcher()->Subscribe("SceneManager:DestroyScene", [&] (const std::shared_ptr<anh::EventInterface>& newEvent) { auto real_event = std::static_pointer_cast<swganh_core::simulation::DestroySceneEvent>(newEvent); this->scenes_.erase(real_event->scene_id); }); } anh::service::ServiceDescription TerrainService::GetServiceDescription() { anh::service::ServiceDescription service_description( "Terrain Service", "terrain", "0.1", "127.0.0.1", 0, 0, 0); return service_description; } bool TerrainService::waterHeightHelper(swganh::tre::ContainerLayer* layer, float x, float z, float& result) { //Check our boundaries for(auto& boundary : layer->boundaries) { if(boundary->GetType() == LAYER_TYPE_BOUNDARY_POLYGON) { BoundaryPolygon* bpol = (BoundaryPolygon*)boundary; if(bpol->use_water_height && bpol->IsContained(x, z)) { result = bpol->water_height; return true; } } } //Check our children recursively for(auto& child : layer->children) { if(waterHeightHelper(child, x, z, result)) { return true; } } return false; } float TerrainService::GetWaterHeight(uint32_t scene_id, float x, float z, float raw) { auto itr = scenes_.find(scene_id); if(itr != scenes_.end()) { for(auto& child : itr->second.terrain_visitor_->GetLayers()) { float result; if(waterHeightHelper(child, x, z, result)) { return result; } } if(!raw) { //Todo:Apply any necessary layer modifications } auto header = itr->second.terrain_visitor_->GetHeader(); if(header->use_global_water_height) { return header->global_water_height; } } return FLT_MIN; } float TerrainService::GetHeight(uint32_t scene_id, float x, float z, bool raw) { auto itr = scenes_.find(scene_id); if(itr != scenes_.end()) { //Read in height at this point auto& layers = itr->second.terrain_visitor_->GetLayers(); auto& fractals = itr->second.terrain_visitor_->GetFractals(); float affector_transform = 1.0f; float transform_value = 0.0f; float height_result = 0.0f; for(auto& layer : layers) { if(layer->enabled) { transform_value = processLayerHeight(layer, x, z, height_result, affector_transform, fractals); } } if(!raw) { //Todo:Apply any necessary layer modifications } return (float) height_result; } return FLT_MIN; } bool TerrainService::IsWater(uint32_t scene_id, float x, float z, bool raw) { float water_height = GetWaterHeight(scene_id, x, z, raw); if (water_height != FLT_MIN) { float height = GetHeight(scene_id, x, z); if (height <= water_height) return true; } return false; } float TerrainService::processLayerHeight(ContainerLayer* layer, float x, float z, float& base_value, float affector_transform, std::map<uint32_t,Fractal*>& fractals) { //std::cout << "PROCESS_LAYER_HEIGHT("<< x << "," << z << "," << base_value << "," << affector_transform << ")" << std::endl; std::vector<BoundaryLayer*> boundaries = layer->boundaries; std::vector<HeightLayer*> heights = layer->heights; std::vector<FilterLayer*> filters = layer->filters; float transform_value = 0.0f; bool has_boundaries = false; float result = 0.0f; for (unsigned int i = 0; i < boundaries.size(); i++) { BoundaryLayer* boundary = (BoundaryLayer*)boundaries.at(i); if (!boundary->enabled) continue; else has_boundaries = true; float result = (float) boundary->Process(x, z); result = calculateFeathering(result, boundary->feather_type); if (result > transform_value) transform_value = result; if (transform_value >= 1) break; } if (has_boundaries == false) transform_value = 1.0f; if (layer->invert_boundaries) transform_value = 1.0f - transform_value; if (transform_value != 0) { for (unsigned int i = 0; i < filters.size(); ++i) { FilterLayer* filter = (FilterLayer*)filters.at(i); if (!filter->enabled) continue; float result = (float) filter->Process(x, z, transform_value, base_value, fractals); result = calculateFeathering(result, filter->feather_type); if (transform_value > result) transform_value = result; if (transform_value == 0) break; } if (layer->invert_filters) transform_value = 1.0f - transform_value; if (transform_value != 0) { for (unsigned int i = 0; i < heights.size(); i++) { HeightLayer* affector = (HeightLayer*)heights.at(i); if (affector->enabled) { affector->GetBaseHeight(x, z, transform_value, base_value, fractals); } } std::vector<ContainerLayer*> children = layer->children; for (unsigned int i = 0; i < children.size(); i++) { ContainerLayer* child = children.at(i); if (child->enabled) processLayerHeight(child, x, z, base_value, affector_transform * transform_value, fractals); } } } return transform_value; } float TerrainService::calculateFeathering(float value, int featheringType) { float result = value; switch (featheringType) { case 1: result = result * result; break; case 2: result = sqrt(result); break; case 3: result = result * result * (3 - 2 * result); break; case 0: result = result; break; default: result = 0; break; } return result; }
#include "terrain_service.h" #include <map> #include "pub14_core/simulation/scene_events.h" #include <anh/event_dispatcher.h> #include <anh/logger.h> #include "swganh/tre/resource_manager.h" //#include "swganh/tre/visitors/terrain/layer_visitor.h" #include "swganh/tre/visitors/terrain/terrain_visitor.h" #include "swganh/tre/visitors/terrain/detail/container_layer.h" #include "swganh/tre/visitors/terrain/detail/boundary_layer.h" #include "swganh/tre/visitors/terrain/detail/height_layer.h" #include "swganh/tre/visitors/terrain/detail/filter_layer.h" #include "swganh/tre/visitors/terrain/detail/boundary_polygon.h" #include "swganh/tre/visitors/terrain/detail/header.h" using namespace swganh_core::terrain; using namespace swganh::tre; TerrainService::TerrainService(swganh::app::SwganhKernel* kernel) : kernel_(kernel) { kernel_->GetEventDispatcher()->Subscribe("SceneManager:NewScene", [&] (const std::shared_ptr<anh::EventInterface>& newEvent) { auto real_event = std::static_pointer_cast<swganh_core::simulation::NewSceneEvent>(newEvent); try { auto visitor = kernel_->GetResourceManager()->getResourceByName(real_event->terrain_filename, TRN_VISITOR); SceneEntry entry; entry.terrain_visitor_ = std::static_pointer_cast<TerrainVisitor>(visitor); scenes_.insert(SceneMap::value_type(real_event->scene_id, std::move(entry))); } catch(...) { LOG(error) << "Failed to load trn file: " << real_event->terrain_filename; } }); kernel_->GetEventDispatcher()->Subscribe("SceneManager:DestroyScene", [&] (const std::shared_ptr<anh::EventInterface>& newEvent) { auto real_event = std::static_pointer_cast<swganh_core::simulation::DestroySceneEvent>(newEvent); this->scenes_.erase(real_event->scene_id); }); } anh::service::ServiceDescription TerrainService::GetServiceDescription() { anh::service::ServiceDescription service_description( "Terrain Service", "terrain", "0.1", "127.0.0.1", 0, 0, 0); return service_description; } bool TerrainService::waterHeightHelper(swganh::tre::ContainerLayer* layer, float x, float z, float& result) { //Check our boundaries for(auto& boundary : layer->boundaries) { if(boundary->GetType() == LAYER_TYPE_BOUNDARY_POLYGON) { BoundaryPolygon* bpol = (BoundaryPolygon*)boundary; if(bpol->use_water_height && bpol->IsContained(x, z)) { result = bpol->water_height; return true; } } } //Check our children recursively for(auto& child : layer->children) { if(waterHeightHelper(child, x, z, result)) { return true; } } return false; } float TerrainService::GetWaterHeight(uint32_t scene_id, float x, float z, float raw) { auto itr = scenes_.find(scene_id); if(itr != scenes_.end()) { for(auto& child : itr->second.terrain_visitor_->GetLayers()) { float result; if(waterHeightHelper(child, x, z, result)) { return result; } } if(!raw) { //Todo:Apply any necessary layer modifications } auto header = itr->second.terrain_visitor_->GetHeader(); if(header->use_global_water_height) { return header->global_water_height; } } return FLT_MIN; } float TerrainService::GetHeight(uint32_t scene_id, float x, float z, bool raw) { auto itr = scenes_.find(scene_id); if(itr != scenes_.end()) { //Read in height at this point auto& layers = itr->second.terrain_visitor_->GetLayers(); auto& fractals = itr->second.terrain_visitor_->GetFractals(); float affector_transform = 1.0f; float transform_value = 0.0f; float height_result = 0.0f; for(auto& layer : layers) { if(layer->enabled) { transform_value = processLayerHeight(layer, x, z, height_result, affector_transform, fractals); } } if(!raw) { //Todo:Apply any necessary layer modifications } return (float) height_result; } return FLT_MIN; } bool TerrainService::IsWater(uint32_t scene_id, float x, float z, bool raw) { float water_height = GetWaterHeight(scene_id, x, z, raw); if (water_height != FLT_MIN) { float height = GetHeight(scene_id, x, z); if (height <= water_height) return true; } return false; } float TerrainService::processLayerHeight(ContainerLayer* layer, float x, float z, float& base_value, float affector_transform, std::map<uint32_t,Fractal*>& fractals) { //std::cout << "PROCESS_LAYER_HEIGHT("<< x << "," << z << "," << base_value << "," << affector_transform << ")" << std::endl; std::vector<BoundaryLayer*> boundaries = layer->boundaries; std::vector<HeightLayer*> heights = layer->heights; std::vector<FilterLayer*> filters = layer->filters; float transform_value = 0.0f; bool has_boundaries = false; for (unsigned int i = 0; i < boundaries.size(); i++) { BoundaryLayer* boundary = (BoundaryLayer*)boundaries.at(i); if (!boundary->enabled) continue; else has_boundaries = true; float result = (float) boundary->Process(x, z); result = calculateFeathering(result, boundary->feather_type); if (result > transform_value) transform_value = result; if (transform_value >= 1) break; } if (has_boundaries == false) transform_value = 1.0f; if (layer->invert_boundaries) transform_value = 1.0f - transform_value; if (transform_value != 0) { for (unsigned int i = 0; i < filters.size(); ++i) { FilterLayer* filter = (FilterLayer*)filters.at(i); if (!filter->enabled) continue; float result = (float) filter->Process(x, z, transform_value, base_value, fractals); result = calculateFeathering(result, filter->feather_type); if (transform_value > result) transform_value = result; if (transform_value == 0) break; } if (layer->invert_filters) transform_value = 1.0f - transform_value; if (transform_value != 0) { for (unsigned int i = 0; i < heights.size(); i++) { HeightLayer* affector = (HeightLayer*)heights.at(i); if (affector->enabled) { affector->GetBaseHeight(x, z, transform_value, base_value, fractals); } } std::vector<ContainerLayer*> children = layer->children; for (unsigned int i = 0; i < children.size(); i++) { ContainerLayer* child = children.at(i); if (child->enabled) processLayerHeight(child, x, z, base_value, affector_transform * transform_value, fractals); } } } return transform_value; } float TerrainService::calculateFeathering(float value, int featheringType) { float result = value; switch (featheringType) { case 1: result = result * result; break; case 2: result = sqrt(result); break; case 3: result = result * result * (3 - 2 * result); break; case 0: result = result; break; default: result = 0; break; } return result; }
Update src/pub14_core/terrain/terrain_service.cc
Update src/pub14_core/terrain/terrain_service.cc lolz
C++
mit
anhstudios/swganh,anhstudios/swganh,anhstudios/swganh
f217b3bc01f81c5f00fcf5581976a0552c277ddf
src/import/chips/p9/procedures/hwp/memory/lib/spd/common/raw_cards.C
src/import/chips/p9/procedures/hwp/memory/lib/spd/common/raw_cards.C
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/spd/common/raw_cards.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file raw_cards.C /// @brief Raw card data structure /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Brian Silver <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB // std lib #include <vector> // fapi2 #include <fapi2.H> // mss lib #include <lib/spd/common/raw_cards.H> namespace mss { namespace rcd01 { enum raw_card_rev : uint8_t { // TODO RTC:160116 Fill in valid RCD data for LRDIMM B0 = 0x01, // RDIMM power-on C1 = 0x22, // TK - Change to 0xFF - AAM // In the spec hex XF (where X - don't care) // means no JEDEC reference raw card design used. // We will want to redefine it to be VBU reference raw card // since it is unlikely we will use a DIMM w/o a // reference caw card design. VBU = 0x23, }; /// /// @brief raw card B0 settings /// // TODO RTC:160116 Fill in valid RCD data for LRDIMM raw_card_t raw_card_b0( 0x00, 0x00, 0x00, 0x0F, 0x03, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07); /// /// @brief raw card C1 settings /// raw_card_t raw_card_c1( 0x00, 0x0B, 0x00, 0x0F, 0x03, 0x0F, 0x0E, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07); /// /// @brief raw card VBU settings /// raw_card_t raw_card_vbu( 0x00, 0x00, 0x00, 0x0F, 0x03, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07); // TODO - RTC:160121 Catch all for adding raw card data for DIMMs // Not sure if we can have the same raw card revision for rcd01 and rcd02, // if not, then we can move this vector outside of the rcd01 namespace. const std::vector< std::pair< uint8_t , rcd01::raw_card_t> > RAW_CARDS = { {raw_card_rev::B0, rcd01::raw_card_b0}, {raw_card_rev::C1, rcd01::raw_card_c1}, {raw_card_rev::VBU, rcd01::raw_card_vbu}, }; }// rcd01 }// mss
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/spd/common/raw_cards.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file raw_cards.C /// @brief Raw card data structure /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Brian Silver <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB // std lib #include <vector> // fapi2 #include <fapi2.H> // mss lib #include <lib/spd/common/raw_cards.H> namespace mss { namespace rcd01 { enum raw_card_rev : uint8_t { // TODO RTC:160116 Fill in valid RCD data for LRDIMM B0 = 0x01, // RDIMM power-on C1 = 0x22, // TK - Change to 0xFF - AAM // In the spec hex XF (where X - don't care) // means no JEDEC reference raw card design used. // We will want to redefine it to be VBU reference raw card // since it is unlikely we will use a DIMM w/o a // reference caw card design. VBU = 0x23, }; /// /// @brief raw card B0 settings /// // TODO RTC:160116 Fill in valid RCD data for LRDIMM raw_card_t raw_card_b0( 0x00, 0x00, 0x00, 0x0F, 0x03, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07); /// /// @brief raw card C1 settings /// raw_card_t raw_card_c1( 0x00, 0x0B, 0x00, 0x0F, 0x03, 0x0F, 0x0E, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07); /// /// @brief raw card VBU settings /// raw_card_t raw_card_vbu( 0x00, 0x00, 0x00, 0x0F, 0x03, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07); // TODO - RTC:160121 Catch all for adding raw card data for DIMMs // Not sure if we can have the same raw card revision for rcd01 and rcd02, // if not, then we can move this vector outside of the rcd01 namespace. const std::vector< std::pair< uint8_t , rcd01::raw_card_t> > RAW_CARDS = { {raw_card_rev::B0, rcd01::raw_card_b0}, {raw_card_rev::C1, rcd01::raw_card_c1}, {raw_card_rev::VBU, rcd01::raw_card_vbu}, }; }// rcd01 }// mss
Fix incorrect RCWs settings for power-on DIMM
Fix incorrect RCWs settings for power-on DIMM Change-Id: Ib673667d7c7531d8ab135541b174e136c71367bb Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/30640 Tested-by: Jenkins Server <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: Brian R. Silver <[email protected]> Reviewed-by: Louis Stermole <[email protected]> Reviewed-by: STEPHEN GLANCY <[email protected]> Reviewed-by: Jennifer A. Stofer <[email protected]> Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/30641 Tested-by: FSP CI Jenkins <[email protected]> Reviewed-by: Daniel M. Crowell <[email protected]>
C++
apache-2.0
Over-enthusiastic/hostboot,Over-enthusiastic/hostboot,Over-enthusiastic/hostboot,Over-enthusiastic/hostboot,Over-enthusiastic/hostboot
b2a1d07a53611d0797f576726bc7cf51b023b7b6
kernel/cairo_display.cpp
kernel/cairo_display.cpp
#include "config.h" #include <stdarg.h> #include <stdio.h> #include <assert.h> #include "ntstatus.h" #define WIN32_NO_STATUS #include "windef.h" #include "winternl.h" #include "ntcall.h" #include "debug.h" #include "win32mgr.h" #include "ntwin32.h" #include "cairo_display.h" #include <stdlib.h> #include <X11/Xutil.h> #include <X11/Xlib.h> #include <cairo.h> #include <cairo-xlib.h> #include <math.h> Display* disp; int screenNumber; unsigned long white, black; int width, height; class cairo_device_context_t : public device_context_t { public: window_tt *win; public: cairo_device_context_t(); virtual BOOL set_pixel( INT x, INT y, COLORREF color ); virtual BOOL rectangle( INT x, INT y, INT width, INT height ); virtual BOOL exttextout( INT x, INT y, UINT options, LPRECT rect, UNICODE_STRING& text ); virtual COLORREF get_pixel( INT x, INT y ); virtual BOOL polypatblt( ULONG Rop, PRECT rect ); virtual int getcaps( int index ); }; class win32k_cairo_t : public win32k_manager_t, public sleeper_t { public: virtual BOOL init(); virtual void fini(); win32k_cairo_t(); virtual BOOL set_pixel( INT x, INT y, COLORREF color ); virtual BOOL rectangle( INT left, INT top, INT right, INT bottom, brush_t* brush ); virtual BOOL exttextout( INT x, INT y, UINT options, LPRECT rect, UNICODE_STRING& text ); virtual BOOL bitblt( INT xDest, INT yDest, INT cx, INT cy, device_context_t *src, INT xSrc, INT ySrc, ULONG rop ); virtual BOOL polypatblt( ULONG Rop, PRECT rect ); virtual device_context_t* alloc_screen_dc_ptr(); protected: virtual bool check_events( bool wait ); virtual int getcaps( int index ); void handle_events(); Window win; Display* disp; cairo_surface_t *cs, *buffer; cairo_t *cr; int screenNumber; }; template<typename T> void swap( T& A, T& B ) { T x = A; A = B; B = x; } win32k_cairo_t::win32k_cairo_t() : disp(NULL) { } BOOL win32k_cairo_t::init() { if (disp) return TRUE; disp = XOpenDisplay(NULL); if (disp == NULL) return FALSE; screenNumber = DefaultScreen(disp); white = WhitePixel(disp,screenNumber); width = 300; height = 300; win = XCreateSimpleWindow(disp, RootWindow(disp, screenNumber), 0, 0, // origin width, height, // size 0, black, // border white ); // backgd XMapWindow(disp, win); XStoreName(disp, win, "Hello World!"); XSelectInput(disp, win, ExposureMask | ButtonReleaseMask | ButtonPressMask); cs = cairo_xlib_surface_create(disp, win, DefaultVisual(disp, 0), 200, 200); cr = cairo_create(cs); buffer = cairo_image_surface_create(CAIRO_FORMAT_RGB24, 200, 200); cairo_t *c = cairo_create(buffer); cairo_set_source_rgb(c, 0.231372549, 0.447058824, 0.662745098); cairo_rectangle(c, 0, 0, 200, 200); cairo_fill(c); cairo_destroy(c); sleeper = this; return TRUE; } void win32k_cairo_t::fini() { cairo_destroy(cr); cairo_surface_destroy(cs); XDestroyWindow(disp, win); XCloseDisplay(disp); } void win32k_cairo_t::handle_events() { XEvent evt; XNextEvent(disp, &evt); if (evt.type == ButtonPress) { INPUT input; input.type = INPUT_MOUSE; input.mi.dx = evt.xbutton.x; input.mi.dy = evt.xbutton.y; input.mi.mouseData = 0; input.mi.dwFlags = evt.xbutton.button == 1 ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_RIGHTDOWN; input.mi.time = timeout_t::get_tick_count(); input.mi.dwExtraInfo = 0; send_input( &input ); } if (evt.type == ButtonRelease) { INPUT input; input.type = INPUT_MOUSE; input.mi.dx = evt.xbutton.x; input.mi.dy = evt.xbutton.y; input.mi.mouseData = 0; input.mi.dwFlags = evt.xbutton.button == 1 ? MOUSEEVENTF_LEFTUP : MOUSEEVENTF_RIGHTUP; input.mi.time = timeout_t::get_tick_count(); input.mi.dwExtraInfo = 0; send_input( &input ); } if (evt.type == Expose && evt.xexpose.count < 1) { cairo_save(cr); cairo_set_source_surface(cr, buffer, 0, 0); cairo_paint(cr); cairo_restore(cr); } } bool win32k_cairo_t::check_events( bool wait ) { LARGE_INTEGER timeout; bool timers_left = timeout_t::check_timers(timeout); while (XPending(disp) != 0) { handle_events(); } if (!timers_left && !active_window && wait && fiber_t::last_fiber()) return true; if (!wait) return false; handle_events(); return FALSE; } BOOL win32k_cairo_t::set_pixel( INT x, INT y, COLORREF color ) { printf("######## pixel ######## \n"); /* cairo_t *c = cairo_create(buffer); cairo_set_source_rgb(c, ((float) GetRValue(color)) / 255.0, ((float) GetGValue(color)) / 255.0, ((float) GetBValue(color)) / 255.0); cairo_move_to(c, x, y); cairo_line_to(c, x, y); cairo_destroy(c); */ unsigned int *buf = (unsigned int *) cairo_image_surface_get_data(buffer); buf[y * 200 + x] = color; cairo_save(cr); cairo_set_source_surface(cr, buffer, 0, 0); cairo_paint(cr); cairo_restore(cr); return TRUE; } BOOL win32k_cairo_t::rectangle(INT left, INT top, INT right, INT bottom, brush_t* brush ) { printf("######## rectangle ########\n"); cairo_t *c = cairo_create(buffer); cairo_set_source_rgb(c, 0.0, 0.0, 0.0); if (left > right) swap(left, right); if (top > bottom) swap(top, bottom); cairo_rectangle(c, (float) left, (float) top, (float) (right - left), (float) (bottom - top)); cairo_destroy(c); cairo_save(cr); cairo_set_source_surface(cr, buffer, 0, 0); cairo_paint(cr); cairo_restore(cr); return TRUE; } BOOL win32k_cairo_t::exttextout( INT x, INT y, UINT options, LPRECT rect, UNICODE_STRING& text ) { #if 0 char utf8[4]; printf("######## exttextout ########\n"); int dx = 0, dy = 0; cairo_t *c = cairo_create(buffer); for (int i=0; i<text.Length/2; i++) { WCHAR ch = text.Buffer[i]; utf8[0] = ch; utf8[1] = 0; cairo_move_to(c, x + dx, x + dy); dx += 10; cairo_show_text(c, utf8); printf("C : %c\n", ch); } cairo_paint(c); cairo_destroy(c); cairo_save(cr); cairo_set_source_surface(cr, buffer, 0, 0); cairo_paint(cr); cairo_restore(cr); #endif return TRUE; } BOOL win32k_cairo_t::bitblt(INT xDest, INT yDest, INT cx, INT cy, device_context_t *src, INT xSrc, INT ySrc, ULONG rop ) { unsigned int *buf = (unsigned int *) cairo_image_surface_get_data(buffer); bitmap_t *bitmap = src->get_selected_bitmap(); if (!bitmap) return FALSE; COLORREF pixel; for (int i = 0; i < cy; i++) { for (int j = 0; j < cx; j++) { unsigned char c1, c2; pixel = src->get_pixel( xSrc + j, ySrc + i ); c1 = pixel & 0x00FF; c2 = (pixel >> 16) & 0x00FF; pixel = (pixel & 0x0000FF00) | c2 | ( c1 << 16 ); buf[200 * (yDest + i) + (xDest + j)] = pixel; } } cairo_save(cr); cairo_set_source_surface(cr, buffer, 0, 0); cairo_paint(cr); cairo_restore(cr); return TRUE; } BOOL win32k_cairo_t::polypatblt( ULONG Rop, PRECT rect ) { printf("######## polypatblt ########\n"); rect->left = max( rect->left, 0 ); rect->top = max( rect->top, 0 ); rect->right = min( 200, rect->right ); rect->bottom = min( 200, rect->bottom ); cairo_t *c = cairo_create(buffer); cairo_set_source_rgb(c, 0.0, 0.0, 0.0); cairo_rectangle(c, (float) rect->left, (float) rect->top, (float) (rect->right - rect->left), (float) (rect->bottom - rect->top)); cairo_fill(c); cairo_destroy(c); cairo_save(cr); cairo_set_source_surface(cr, buffer, 0, 0); cairo_paint(cr); cairo_restore(cr); return TRUE; } int win32k_cairo_t::getcaps( int index ) { switch (index) { case NUMCOLORS: // return 1 << screen->format->BitsPerPixel; return 1 << 16; case BITSPIXEL: // return screen->format->BitsPerPixel; return 16; default: dprintf("%d\n", index ); return 0; } } win32k_cairo_t win32k_manager_cairo; win32k_manager_t* init_cairo_win32k_manager() { return &win32k_manager_cairo; } BOOL cairo_device_context_t::rectangle(INT left, INT top, INT right, INT bottom ) { brush_t *brush = get_selected_brush(); if (!brush) return FALSE; dprintf("drawing with brush %p with color %08lx\n", brush->get_handle(), brush->get_color() ); return win32k_manager->rectangle( left, top, right, bottom, brush ); } BOOL cairo_device_context_t::polypatblt( ULONG Rop, PRECT rect ) { return win32k_manager->polypatblt( Rop, rect ); } cairo_device_context_t::cairo_device_context_t() : win( 0 ) { } BOOL cairo_device_context_t::set_pixel( INT x, INT y, COLORREF color ) { return win32k_manager->set_pixel( x, y, color ); } BOOL cairo_device_context_t::exttextout( INT x, INT y, UINT options, LPRECT rect, UNICODE_STRING& text ) { return win32k_manager->exttextout( x, y, options, rect, text ); } COLORREF cairo_device_context_t::get_pixel( INT x, INT y ) { return 0; } int cairo_device_context_t::getcaps( int index ) { return win32k_manager->getcaps( index ); } device_context_t* win32k_cairo_t::alloc_screen_dc_ptr() { return new cairo_device_context_t; }
/* * Cairo backend * * Copyright 2009 Hilary Cheng * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #include "config.h" #include <stdarg.h> #include <stdio.h> #include <assert.h> #include "ntstatus.h" #define WIN32_NO_STATUS #include "windef.h" #include "winternl.h" #include "ntcall.h" #include "debug.h" #include "win32mgr.h" #include "ntwin32.h" #include "cairo_display.h" #ifdef HAVE_CAIRO #include <stdlib.h> #include <X11/Xutil.h> #include <X11/Xlib.h> #include <cairo.h> #include <cairo-xlib.h> #include <math.h> Display* disp; int screenNumber; unsigned long white, black; int width, height; class cairo_device_context_t : public device_context_t { public: window_tt *win; public: cairo_device_context_t(); virtual BOOL set_pixel( INT x, INT y, COLORREF color ); virtual BOOL rectangle( INT x, INT y, INT width, INT height ); virtual BOOL exttextout( INT x, INT y, UINT options, LPRECT rect, UNICODE_STRING& text ); virtual COLORREF get_pixel( INT x, INT y ); virtual BOOL polypatblt( ULONG Rop, PRECT rect ); virtual int getcaps( int index ); }; class win32k_cairo_t : public win32k_manager_t, public sleeper_t { public: virtual BOOL init(); virtual void fini(); win32k_cairo_t(); virtual BOOL set_pixel( INT x, INT y, COLORREF color ); virtual BOOL rectangle( INT left, INT top, INT right, INT bottom, brush_t* brush ); virtual BOOL exttextout( INT x, INT y, UINT options, LPRECT rect, UNICODE_STRING& text ); virtual BOOL bitblt( INT xDest, INT yDest, INT cx, INT cy, device_context_t *src, INT xSrc, INT ySrc, ULONG rop ); virtual BOOL polypatblt( ULONG Rop, PRECT rect ); virtual device_context_t* alloc_screen_dc_ptr(); protected: virtual bool check_events( bool wait ); virtual int getcaps( int index ); void handle_events(); Window win; Display* disp; cairo_surface_t *cs, *buffer; cairo_t *cr; int screenNumber; }; template<typename T> void swap( T& A, T& B ) { T x = A; A = B; B = x; } win32k_cairo_t::win32k_cairo_t() : disp(NULL) { } BOOL win32k_cairo_t::init() { if (disp) return TRUE; disp = XOpenDisplay(NULL); if (disp == NULL) return FALSE; screenNumber = DefaultScreen(disp); white = WhitePixel(disp,screenNumber); width = 300; height = 300; win = XCreateSimpleWindow(disp, RootWindow(disp, screenNumber), 0, 0, // origin width, height, // size 0, black, // border white ); // backgd XMapWindow(disp, win); XStoreName(disp, win, "Hello World!"); XSelectInput(disp, win, ExposureMask | ButtonReleaseMask | ButtonPressMask); cs = cairo_xlib_surface_create(disp, win, DefaultVisual(disp, 0), 200, 200); cr = cairo_create(cs); buffer = cairo_image_surface_create(CAIRO_FORMAT_RGB24, 200, 200); cairo_t *c = cairo_create(buffer); cairo_set_source_rgb(c, 0.231372549, 0.447058824, 0.662745098); cairo_rectangle(c, 0, 0, 200, 200); cairo_fill(c); cairo_destroy(c); sleeper = this; return TRUE; } void win32k_cairo_t::fini() { cairo_destroy(cr); cairo_surface_destroy(cs); XDestroyWindow(disp, win); XCloseDisplay(disp); } void win32k_cairo_t::handle_events() { XEvent evt; XNextEvent(disp, &evt); if (evt.type == ButtonPress) { INPUT input; input.type = INPUT_MOUSE; input.mi.dx = evt.xbutton.x; input.mi.dy = evt.xbutton.y; input.mi.mouseData = 0; input.mi.dwFlags = evt.xbutton.button == 1 ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_RIGHTDOWN; input.mi.time = timeout_t::get_tick_count(); input.mi.dwExtraInfo = 0; send_input( &input ); } if (evt.type == ButtonRelease) { INPUT input; input.type = INPUT_MOUSE; input.mi.dx = evt.xbutton.x; input.mi.dy = evt.xbutton.y; input.mi.mouseData = 0; input.mi.dwFlags = evt.xbutton.button == 1 ? MOUSEEVENTF_LEFTUP : MOUSEEVENTF_RIGHTUP; input.mi.time = timeout_t::get_tick_count(); input.mi.dwExtraInfo = 0; send_input( &input ); } if (evt.type == Expose && evt.xexpose.count < 1) { cairo_save(cr); cairo_set_source_surface(cr, buffer, 0, 0); cairo_paint(cr); cairo_restore(cr); } } bool win32k_cairo_t::check_events( bool wait ) { LARGE_INTEGER timeout; bool timers_left = timeout_t::check_timers(timeout); while (XPending(disp) != 0) { handle_events(); } if (!timers_left && !active_window && wait && fiber_t::last_fiber()) return true; if (!wait) return false; handle_events(); return FALSE; } BOOL win32k_cairo_t::set_pixel( INT x, INT y, COLORREF color ) { printf("######## pixel ######## \n"); /* cairo_t *c = cairo_create(buffer); cairo_set_source_rgb(c, ((float) GetRValue(color)) / 255.0, ((float) GetGValue(color)) / 255.0, ((float) GetBValue(color)) / 255.0); cairo_move_to(c, x, y); cairo_line_to(c, x, y); cairo_destroy(c); */ unsigned int *buf = (unsigned int *) cairo_image_surface_get_data(buffer); buf[y * 200 + x] = color; cairo_save(cr); cairo_set_source_surface(cr, buffer, 0, 0); cairo_paint(cr); cairo_restore(cr); return TRUE; } BOOL win32k_cairo_t::rectangle(INT left, INT top, INT right, INT bottom, brush_t* brush ) { printf("######## rectangle ########\n"); cairo_t *c = cairo_create(buffer); cairo_set_source_rgb(c, 0.0, 0.0, 0.0); if (left > right) swap(left, right); if (top > bottom) swap(top, bottom); cairo_rectangle(c, (float) left, (float) top, (float) (right - left), (float) (bottom - top)); cairo_destroy(c); cairo_save(cr); cairo_set_source_surface(cr, buffer, 0, 0); cairo_paint(cr); cairo_restore(cr); return TRUE; } BOOL win32k_cairo_t::exttextout( INT x, INT y, UINT options, LPRECT rect, UNICODE_STRING& text ) { #if 0 char utf8[4]; printf("######## exttextout ########\n"); int dx = 0, dy = 0; cairo_t *c = cairo_create(buffer); for (int i=0; i<text.Length/2; i++) { WCHAR ch = text.Buffer[i]; utf8[0] = ch; utf8[1] = 0; cairo_move_to(c, x + dx, x + dy); dx += 10; cairo_show_text(c, utf8); printf("C : %c\n", ch); } cairo_paint(c); cairo_destroy(c); cairo_save(cr); cairo_set_source_surface(cr, buffer, 0, 0); cairo_paint(cr); cairo_restore(cr); #endif return TRUE; } BOOL win32k_cairo_t::bitblt(INT xDest, INT yDest, INT cx, INT cy, device_context_t *src, INT xSrc, INT ySrc, ULONG rop ) { unsigned int *buf = (unsigned int *) cairo_image_surface_get_data(buffer); bitmap_t *bitmap = src->get_selected_bitmap(); if (!bitmap) return FALSE; COLORREF pixel; for (int i = 0; i < cy; i++) { for (int j = 0; j < cx; j++) { unsigned char c1, c2; pixel = src->get_pixel( xSrc + j, ySrc + i ); c1 = pixel & 0x00FF; c2 = (pixel >> 16) & 0x00FF; pixel = (pixel & 0x0000FF00) | c2 | ( c1 << 16 ); buf[200 * (yDest + i) + (xDest + j)] = pixel; } } cairo_save(cr); cairo_set_source_surface(cr, buffer, 0, 0); cairo_paint(cr); cairo_restore(cr); return TRUE; } BOOL win32k_cairo_t::polypatblt( ULONG Rop, PRECT rect ) { printf("######## polypatblt ########\n"); rect->left = max( rect->left, 0 ); rect->top = max( rect->top, 0 ); rect->right = min( 200, rect->right ); rect->bottom = min( 200, rect->bottom ); cairo_t *c = cairo_create(buffer); cairo_set_source_rgb(c, 0.0, 0.0, 0.0); cairo_rectangle(c, (float) rect->left, (float) rect->top, (float) (rect->right - rect->left), (float) (rect->bottom - rect->top)); cairo_fill(c); cairo_destroy(c); cairo_save(cr); cairo_set_source_surface(cr, buffer, 0, 0); cairo_paint(cr); cairo_restore(cr); return TRUE; } int win32k_cairo_t::getcaps( int index ) { switch (index) { case NUMCOLORS: // return 1 << screen->format->BitsPerPixel; return 1 << 16; case BITSPIXEL: // return screen->format->BitsPerPixel; return 16; default: dprintf("%d\n", index ); return 0; } } win32k_cairo_t win32k_manager_cairo; win32k_manager_t* init_cairo_win32k_manager() { return &win32k_manager_cairo; } BOOL cairo_device_context_t::rectangle(INT left, INT top, INT right, INT bottom ) { brush_t *brush = get_selected_brush(); if (!brush) return FALSE; dprintf("drawing with brush %p with color %08lx\n", brush->get_handle(), brush->get_color() ); return win32k_manager->rectangle( left, top, right, bottom, brush ); } BOOL cairo_device_context_t::polypatblt( ULONG Rop, PRECT rect ) { return win32k_manager->polypatblt( Rop, rect ); } cairo_device_context_t::cairo_device_context_t() : win( 0 ) { } BOOL cairo_device_context_t::set_pixel( INT x, INT y, COLORREF color ) { return win32k_manager->set_pixel( x, y, color ); } BOOL cairo_device_context_t::exttextout( INT x, INT y, UINT options, LPRECT rect, UNICODE_STRING& text ) { return win32k_manager->exttextout( x, y, options, rect, text ); } COLORREF cairo_device_context_t::get_pixel( INT x, INT y ) { return 0; } int cairo_device_context_t::getcaps( int index ) { return win32k_manager->getcaps( index ); } device_context_t* win32k_cairo_t::alloc_screen_dc_ptr() { return new cairo_device_context_t; } #else win32k_manager_t* init_cairo_win32k_manager() { return NULL; } #endif
Add copyright header and fallback
Add copyright header and fallback
C++
lgpl-2.1
bragin/ring3k,mikemccormack/ring3k,bragin/ring3k,mikemccormack/ring3k,bragin/ring3k,mikemccormack/ring3k,bragin/ring3k
064502d830c7e2b2d18677a9802f61674552ac4a
src/plugins/tricon/triconplugin.cpp
src/plugins/tricon/triconplugin.cpp
/* * Copyright (C) 2008-2013 The Communi Project * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include "triconplugin.h" #include "treewidget.h" #include "treeitem.h" #include <IrcConnection> #include <IrcLagTimer> #include <QPainter> #include <QPixmap> #include <qmath.h> inline void initResource() { Q_INIT_RESOURCE(tricon); } TriconPlugin::TriconPlugin(QObject* parent) : QObject(parent) { d.tree = 0; initResource(); d.movie.setFileName(":/ajax-loader.gif"); } void TriconPlugin::initTree(TreeWidget* tree) { d.tree = tree; for (int i = 0; i < tree->topLevelItemCount(); ++i) updateConnection(static_cast<TreeItem*>(tree->topLevelItem(i))->connection()); connect(&d.movie, SIGNAL(frameChanged(int)), this, SLOT(updateLoader())); } void TriconPlugin::initConnection(IrcConnection* connection) { connect(connection, SIGNAL(statusChanged(IrcConnection::Status)), this, SLOT(updateConnection())); if (d.tree) updateConnection(connection); IrcLagTimer* timer = new IrcLagTimer(connection); connect(timer, SIGNAL(lagChanged(qint64)), this, SLOT(updateLag(qint64))); // TODO: connect(connection, SIGNAL(connected()), timer, SLOT(_irc_pingServer())); } void TriconPlugin::cleanupConnection(IrcConnection* connection) { disconnect(connection, SIGNAL(statusChanged(IrcConnection::Status)), this, SLOT(updateConnection())); foreach (TreeItem* item, d.items) { if (!item || item->connection() == connection) d.items.removeOne(item); } } void TriconPlugin::updateLoader() { QPixmap pixmap = d.movie.currentPixmap(); foreach (TreeItem* item, d.items) { if (item) item->setIcon(0, pixmap); } } void TriconPlugin::updateLag(qint64 lag) { IrcLagTimer* timer = qobject_cast<IrcLagTimer*>(sender()); if (timer) updateConnection(timer->connection(), lag); } void TriconPlugin::updateConnection(IrcConnection* connection, qint64 lag) { if (!connection) connection = qobject_cast<IrcConnection*>(sender()); TreeItem* item = d.tree->connectionItem(connection); if (item) { item->setToolTip(0, lag > 0 ? tr("%1ms").arg(lag) : QString()); if (connection->isActive() && !connection->isConnected()) { item->setIcon(0, d.movie.currentPixmap()); if (!d.items.contains(item)) d.items.append(item); } else { QPixmap pixmap(16, 16); pixmap.fill(Qt::transparent); QPainter painter(&pixmap); painter.setPen(QPalette().color(QPalette::Mid)); QColor color(Qt::transparent); if (lag > 0) { qreal f = qMin(100.0, qSqrt(lag)) / 100; color = QColor::fromHsl(120 - f * 120, 96, 152); // TODO } painter.setBrush(color); painter.setRenderHint(QPainter::Antialiasing); painter.drawEllipse(4, 4, 8, 8); item->setIcon(0, pixmap); d.items.removeOne(item); } } if (d.items.isEmpty()) { if (d.movie.state() == QMovie::Running) d.movie.stop(); } else { if (d.movie.state() == QMovie::NotRunning) d.movie.start(); } } #if QT_VERSION < 0x050000 Q_EXPORT_STATIC_PLUGIN(TriconPlugin) #endif
/* * Copyright (C) 2008-2013 The Communi Project * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include "triconplugin.h" #include "treewidget.h" #include "treeitem.h" #include <IrcConnection> #include <IrcLagTimer> #include <QPainter> #include <QPixmap> #include <qmath.h> inline void initResource() { Q_INIT_RESOURCE(tricon); } TriconPlugin::TriconPlugin(QObject* parent) : QObject(parent) { d.tree = 0; initResource(); d.movie.setFileName(":/ajax-loader.gif"); } void TriconPlugin::initTree(TreeWidget* tree) { d.tree = tree; for (int i = 0; i < tree->topLevelItemCount(); ++i) updateConnection(static_cast<TreeItem*>(tree->topLevelItem(i))->connection()); connect(&d.movie, SIGNAL(frameChanged(int)), this, SLOT(updateLoader())); } void TriconPlugin::initConnection(IrcConnection* connection) { connect(connection, SIGNAL(statusChanged(IrcConnection::Status)), this, SLOT(updateConnection())); if (d.tree) updateConnection(connection); IrcLagTimer* timer = new IrcLagTimer(connection); connect(timer, SIGNAL(lagChanged(qint64)), this, SLOT(updateLag(qint64))); // TODO: connect(connection, SIGNAL(connected()), timer, SLOT(_irc_pingServer())); } void TriconPlugin::cleanupConnection(IrcConnection* connection) { disconnect(connection, SIGNAL(statusChanged(IrcConnection::Status)), this, SLOT(updateConnection())); foreach (TreeItem* item, d.items) { if (!item || item->connection() == connection) d.items.removeOne(item); } } void TriconPlugin::updateLoader() { QPixmap pixmap = d.movie.currentPixmap(); foreach (TreeItem* item, d.items) { if (item) item->setIcon(0, pixmap); } } void TriconPlugin::updateLag(qint64 lag) { IrcLagTimer* timer = qobject_cast<IrcLagTimer*>(sender()); if (timer) updateConnection(timer->connection(), lag); } void TriconPlugin::updateConnection(IrcConnection* connection, qint64 lag) { if (!connection) connection = qobject_cast<IrcConnection*>(sender()); TreeItem* item = d.tree->connectionItem(connection); if (item) { item->setToolTip(0, lag > 0 ? tr("%1ms").arg(lag) : QString()); if (connection->isActive() && !connection->isConnected()) { item->setIcon(0, d.movie.currentPixmap()); if (!d.items.contains(item)) d.items.append(item); } else { QPixmap pixmap(16, 16); pixmap.fill(Qt::transparent); QPainter painter(&pixmap); painter.setPen(QPalette().color(QPalette::Mid)); QColor color(Qt::transparent); if (lag > 0) { qreal f = qMin(100.0, qSqrt(lag)) / 100; color = QColor::fromHsl(120 - f * 120, 96, 152); // TODO } painter.setBrush(color); painter.setRenderHint(QPainter::Antialiasing); painter.drawEllipse(4, 5, 8, 8); item->setIcon(0, pixmap); d.items.removeOne(item); } } if (d.items.isEmpty()) { if (d.movie.state() == QMovie::Running) d.movie.stop(); } else { if (d.movie.state() == QMovie::NotRunning) d.movie.start(); } } #if QT_VERSION < 0x050000 Q_EXPORT_STATIC_PLUGIN(TriconPlugin) #endif
Fix tree icon vertical center alignment
Fix tree icon vertical center alignment
C++
bsd-3-clause
communi/communi-desktop,jpnurmi/communi-desktop,gdamjan/communi-desktop,communi/communi-desktop,sevanteri/communi-desktop
5bce0ed87abf6b0012ffbf08860351af4eaf0001
kernel/util/xprintf.cc
kernel/util/xprintf.cc
/*------------------------------------------------------------------------/ / Universal string handler for user console interface /-------------------------------------------------------------------------/ / / Copyright (C) 2011, ChaN, all right reserved. / / * This software is a free software and there is NO WARRANTY. / * No restriction on use. You can use, modify and redistribute it for / personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY. / * Redistributions of source code must retain the above copyright notice. / / ported to BadAppleOS by foreverbell <[email protected]> at 2014/8/5. / /-------------------------------------------------------------------------*/ #include "xprintf.h" #include <console.h> #define va_start(v,l) __builtin_va_start(v,l) #define va_arg(v,l) __builtin_va_arg(v,l) #define va_end(v) __builtin_va_end(v) #define va_copy(d,s) __builtin_va_copy(d,s) typedef __builtin_va_list va_list; static char *outptr; /*----------------------------------------------*/ /* Put a character */ /*----------------------------------------------*/ void putc (char c) { if (outptr) { *outptr++ = (unsigned char)c; return; } console::putch((unsigned char)c); } /*----------------------------------------------*/ /* Put a null-terminated string */ /*----------------------------------------------*/ void puts ( /* Put a string to the default device */ const char* str /* Pointer to the string */ ) { while (*str) putc(*str++); } /*----------------------------------------------*/ /* Formatted string output */ /*----------------------------------------------*/ /* printf("%d", 1234); "1234" printf("%6d,%3d%%", -200, 5); " -200, 5%" printf("%-6u", 100); "100 " printf("%ld", 12345678L); "12345678" printf("%04x", 0xA3); "00a3" printf("%08LX", 0x123ABC); "00123ABC" printf("%016b", 0x550F); "0101010100001111" printf("%s", "String"); "String" printf("%-4s", "abc"); "abc " printf("%4s", "abc"); " abc" printf("%c", 'a'); "a" printf("%f", 10.0); <printf lacks floating point support> */ static void vprintf ( const char* fmt, /* Pointer to the format string */ va_list arp /* Pointer to arguments */ ) { unsigned int r, i, j, w, f; unsigned long v; char s[16], c, d, *p; for (;;) { c = *fmt++; /* Get a char */ if (!c) break; /* End of format? */ if (c != '%') { /* Pass through it if not a % sequense */ putc(c); continue; } f = 0; c = *fmt++; /* Get first char of the sequense */ if (c == '0') { /* Flag: '0' padded */ f = 1; c = *fmt++; } else { if (c == '-') { /* Flag: left justified */ f = 2; c = *fmt++; } } for (w = 0; c >= '0' && c <= '9'; c = *fmt++) /* Minimum width */ w = w * 10 + c - '0'; if (c == 'l' || c == 'L') { /* Prefix: Size is long int */ f |= 4; c = *fmt++; } if (!c) break; /* End of format? */ d = c; if (d >= 'a') d -= 0x20; switch (d) { /* Type is... */ case 'S' : /* String */ p = va_arg(arp, char*); for (j = 0; p[j]; j++) ; while (!(f & 2) && j++ < w) putc(' '); puts(p); while (j++ < w) putc(' '); continue; case 'C' : /* Character */ putc((char)va_arg(arp, int)); continue; case 'B' : /* Binary */ r = 2; break; case 'O' : /* Octal */ r = 8; break; case 'D' : /* Signed decimal */ case 'U' : /* Unsigned decimal */ r = 10; break; case 'X' : /* Hexdecimal */ r = 16; break; default: /* Unknown type (passthrough) */ putc(c); continue; } /* Get an argument and put it in numeral */ v = (f & 4) ? va_arg(arp, long) : ((d == 'D') ? (long)va_arg(arp, int) : (long)va_arg(arp, unsigned int)); if (d == 'D' && (v & 0x80000000)) { v = 0 - v; f |= 8; } i = 0; do { d = (char)(v % r); v /= r; if (d > 9) d += (c == 'x') ? 0x27 : 0x07; s[i++] = d + '0'; } while (v && i < sizeof(s)); if (f & 8) s[i++] = '-'; j = i; d = (f & 1) ? '0' : ' '; while (!(f & 2) && j++ < w) putc(d); do putc(s[--i]); while(i); while (j++ < w) putc(' '); } } void printf ( /* Put a formatted string to the default device */ const char* fmt, /* Pointer to the format string */ ... /* Optional arguments */ ) { va_list arp; va_start(arp, fmt); vprintf(fmt, arp); va_end(arp); } void xsprintf ( /* Put a formatted string to the memory */ char* buff, /* Pointer to the output buffer */ const char* fmt, /* Pointer to the format string */ ... /* Optional arguments */ ) { va_list arp; outptr = buff; /* Switch destination for memory */ va_start(arp, fmt); vprintf(fmt, arp); va_end(arp); *outptr = 0; /* Terminate output string with a \0 */ outptr = 0; /* Switch destination for device */ }
/*------------------------------------------------------------------------/ / Universal string handler for user console interface /-------------------------------------------------------------------------/ / / Copyright (C) 2011, ChaN, all right reserved. / / * This software is a free software and there is NO WARRANTY. / * No restriction on use. You can use, modify and redistribute it for / personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY. / * Redistributions of source code must retain the above copyright notice. / / ported to BadAppleOS by foreverbell <[email protected]> at 2014/8/5. / /-------------------------------------------------------------------------*/ #include "xprintf.h" #include <console.h> #define va_start(v,l) __builtin_va_start(v,l) #define va_arg(v,l) __builtin_va_arg(v,l) #define va_end(v) __builtin_va_end(v) #define va_copy(d,s) __builtin_va_copy(d,s) typedef __builtin_va_list va_list; static char *outptr; /*----------------------------------------------*/ /* Put a character */ /*----------------------------------------------*/ void putc (char c) { if (outptr) { *outptr++ = (unsigned char)c; return; } console::putch((unsigned char)c); } /*----------------------------------------------*/ /* Put a null-terminated string */ /*----------------------------------------------*/ void puts ( /* Put a string to the default device */ const char* str /* Pointer to the string */ ) { while (*str) putc(*str++); putc('\n'); } /*----------------------------------------------*/ /* Formatted string output */ /*----------------------------------------------*/ /* printf("%d", 1234); "1234" printf("%6d,%3d%%", -200, 5); " -200, 5%" printf("%-6u", 100); "100 " printf("%ld", 12345678L); "12345678" printf("%04x", 0xA3); "00a3" printf("%08LX", 0x123ABC); "00123ABC" printf("%016b", 0x550F); "0101010100001111" printf("%s", "String"); "String" printf("%-4s", "abc"); "abc " printf("%4s", "abc"); " abc" printf("%c", 'a'); "a" printf("%f", 10.0); <printf lacks floating point support> */ static void vprintf ( const char* fmt, /* Pointer to the format string */ va_list arp /* Pointer to arguments */ ) { unsigned int r, i, j, w, f; unsigned long v; char s[16], c, d, *p; for (;;) { c = *fmt++; /* Get a char */ if (!c) break; /* End of format? */ if (c != '%') { /* Pass through it if not a % sequense */ putc(c); continue; } f = 0; c = *fmt++; /* Get first char of the sequense */ if (c == '0') { /* Flag: '0' padded */ f = 1; c = *fmt++; } else { if (c == '-') { /* Flag: left justified */ f = 2; c = *fmt++; } } for (w = 0; c >= '0' && c <= '9'; c = *fmt++) /* Minimum width */ w = w * 10 + c - '0'; if (c == 'l' || c == 'L') { /* Prefix: Size is long int */ f |= 4; c = *fmt++; } if (!c) break; /* End of format? */ d = c; if (d >= 'a') d -= 0x20; switch (d) { /* Type is... */ case 'S' : /* String */ p = va_arg(arp, char*); for (j = 0; p[j]; j++) ; while (!(f & 2) && j++ < w) putc(' '); while (*p) putc(*p++); while (j++ < w) putc(' '); continue; case 'C' : /* Character */ putc((char)va_arg(arp, int)); continue; case 'B' : /* Binary */ r = 2; break; case 'O' : /* Octal */ r = 8; break; case 'D' : /* Signed decimal */ case 'U' : /* Unsigned decimal */ r = 10; break; case 'X' : /* Hexdecimal */ r = 16; break; default: /* Unknown type (passthrough) */ putc(c); continue; } /* Get an argument and put it in numeral */ v = (f & 4) ? va_arg(arp, long) : ((d == 'D') ? (long)va_arg(arp, int) : (long)va_arg(arp, unsigned int)); if (d == 'D' && (v & 0x80000000)) { v = 0 - v; f |= 8; } i = 0; do { d = (char)(v % r); v /= r; if (d > 9) d += (c == 'x') ? 0x27 : 0x07; s[i++] = d + '0'; } while (v && i < sizeof(s)); if (f & 8) s[i++] = '-'; j = i; d = (f & 1) ? '0' : ' '; while (!(f & 2) && j++ < w) putc(d); do putc(s[--i]); while(i); while (j++ < w) putc(' '); } } void printf ( /* Put a formatted string to the default device */ const char* fmt, /* Pointer to the format string */ ... /* Optional arguments */ ) { va_list arp; va_start(arp, fmt); vprintf(fmt, arp); va_end(arp); } void xsprintf ( /* Put a formatted string to the memory */ char* buff, /* Pointer to the output buffer */ const char* fmt, /* Pointer to the format string */ ... /* Optional arguments */ ) { va_list arp; outptr = buff; /* Switch destination for memory */ va_start(arp, fmt); vprintf(fmt, arp); va_end(arp); *outptr = 0; /* Terminate output string with a \0 */ outptr = 0; /* Switch destination for device */ }
fix bug in xprintf
fix bug in xprintf
C++
mit
foreverbell/BadAppleOS,foreverbell/BadAppleOS,foreverbell/BadAppleOS
6e5061a12d4be447c67991d4a9338ce4c0196f05
service/migration_manager.hh
service/migration_manager.hh
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2015-present ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <type_traits> #include "service/migration_listener.hh" #include "gms/endpoint_state.hh" #include <seastar/core/distributed.hh> #include <seastar/core/abort_source.hh> #include <seastar/core/gate.hh> #include "gms/inet_address.hh" #include "gms/feature.hh" #include "gms/i_endpoint_state_change_subscriber.hh" #include "message/msg_addr.hh" #include "utils/UUID.hh" #include "utils/serialized_action.hh" #include "service/raft/raft_group_registry.hh" #include <vector> class canonical_mutation; class frozen_mutation; namespace cql3 { namespace functions { class user_function; class user_aggregate; }} namespace netw { class messaging_service; } namespace gms { class gossiper; enum class application_state; class versioned_value; } namespace service { template<typename M> concept MergeableMutation = std::is_same<M, canonical_mutation>::value || std::is_same<M, frozen_mutation>::value; class migration_manager : public seastar::async_sharded_service<migration_manager>, public gms::i_endpoint_state_change_subscriber, public seastar::peering_sharded_service<migration_manager> { private: migration_notifier& _notifier; std::unordered_map<netw::msg_addr, serialized_action, netw::msg_addr::hash> _schema_pulls; std::vector<gms::feature::listener_registration> _feature_listeners; seastar::gate _background_tasks; static const std::chrono::milliseconds migration_delay; gms::feature_service& _feat; netw::messaging_service& _messaging; gms::gossiper& _gossiper; seastar::abort_source _as; service::raft_group_registry& _raft_gr; serialized_action _schema_push; utils::UUID _schema_version_to_publish; public: migration_manager(migration_notifier&, gms::feature_service&, netw::messaging_service& ms, gms::gossiper& gossiper, service::raft_group_registry& raft_gr); migration_notifier& get_notifier() { return _notifier; } const migration_notifier& get_notifier() const { return _notifier; } future<> submit_migration_task(const gms::inet_address& endpoint, bool can_ignore_down_node = true); // Makes sure that this node knows about all schema changes known by "nodes" that were made prior to this call. future<> sync_schema(const database& db, const std::vector<gms::inet_address>& nodes); // Fetches schema from remote node and applies it locally. // Differs from submit_migration_task() in that all errors are propagated. // Coalesces requests. future<> merge_schema_from(netw::msg_addr); future<> do_merge_schema_from(netw::msg_addr); // Merge mutations received from src. // Keep mutations alive around whole async operation. future<> merge_schema_from(netw::msg_addr src, const std::vector<canonical_mutation>& mutations); // Deprecated. The canonical mutation should be used instead. future<> merge_schema_from(netw::msg_addr src, const std::vector<frozen_mutation>& mutations); template<typename M> requires MergeableMutation<M> future<> merge_schema_in_background(netw::msg_addr src, const std::vector<M>& mutations) { return with_gate(_background_tasks, [this, src, &mutations] { return merge_schema_from(src, mutations); }); } bool should_pull_schema_from(const gms::inet_address& endpoint); bool has_compatible_schema_tables_version(const gms::inet_address& endpoint); future<> announce_keyspace_update(lw_shared_ptr<keyspace_metadata> ksm); std::vector<mutation> prepare_keyspace_update_announcement(lw_shared_ptr<keyspace_metadata> ksm); future<> announce_new_keyspace(lw_shared_ptr<keyspace_metadata> ksm); future<> announce_new_keyspace(lw_shared_ptr<keyspace_metadata> ksm, api::timestamp_type timestamp); std::vector<mutation> prepare_new_keyspace_announcement(lw_shared_ptr<keyspace_metadata> ksm, api::timestamp_type timestamp); // The timestamp parameter can be used to ensure that all nodes update their internal tables' schemas // with identical timestamps, which can prevent an undeeded schema exchange future<> announce_column_family_update(schema_ptr cfm, bool from_thrift, std::optional<api::timestamp_type> timestamp); future<std::vector<mutation>> prepare_column_family_update_announcement(schema_ptr cfm, bool from_thrift, std::vector<view_ptr> view_updates, std::optional<api::timestamp_type> ts_opt); future<> announce_new_column_family(schema_ptr cfm); future<std::vector<mutation>> prepare_new_column_family_announcement(schema_ptr cfm); future<> announce_new_column_family(schema_ptr cfm, api::timestamp_type timestamp); future<std::vector<mutation>> prepare_new_column_family_announcement(schema_ptr cfm, api::timestamp_type timestamp); future<std::vector<mutation>> prepare_new_type_announcement(user_type new_type); future<std::vector<mutation>> prepare_new_function_announcement(shared_ptr<cql3::functions::user_function> func); future<std::vector<mutation>> prepare_new_aggregate_announcement(shared_ptr<cql3::functions::user_aggregate> aggregate); future<std::vector<mutation>> prepare_function_drop_announcement(shared_ptr<cql3::functions::user_function> func); future<std::vector<mutation>> prepare_aggregate_drop_announcement(shared_ptr<cql3::functions::user_aggregate> aggregate); future<std::vector<mutation>> prepare_update_type_announcement(user_type updated_type); future<> announce_keyspace_drop(const sstring& ks_name); std::vector<mutation> prepare_keyspace_drop_announcement(const sstring& ks_name); class drop_views_tag; using drop_views = bool_class<drop_views_tag>; future<> announce_column_family_drop(const sstring& ks_name, const sstring& cf_name, drop_views drop_views = drop_views::no); future<std::vector<mutation>> prepare_column_family_drop_announcement(const sstring& ks_name, const sstring& cf_name, drop_views drop_views = drop_views::no); future<std::vector<mutation>> prepare_type_drop_announcement(user_type dropped_type); future<> announce_new_view(view_ptr view); future<std::vector<mutation>> prepare_new_view_announcement(view_ptr view); future<std::vector<mutation>> prepare_view_update_announcement(view_ptr view); future<std::vector<mutation>> prepare_view_drop_announcement(const sstring& ks_name, const sstring& cf_name); // the function need to be called if a user wants to access most up-to-date schema state future<> schema_read_barrier(); /** * actively announce a new version to active hosts via rpc * @param schema The schema mutation to be applied */ // Returns a future on the local application of the schema future<> announce(std::vector<mutation> schema); void passive_announce(utils::UUID version); future<> drain(); future<> stop(); /** * Known peers in the cluster have the same schema version as us. */ bool have_schema_agreement(); void init_messaging_service(); private: future<> uninit_messaging_service(); future<> include_keyspace_and_announce( const keyspace_metadata& keyspace, std::vector<mutation> mutations); future<std::vector<mutation>> include_keyspace(const keyspace_metadata& keyspace, std::vector<mutation> mutations); future<std::vector<mutation>> do_prepare_new_type_announcement(user_type new_type); future<> do_announce_new_type(user_type new_type); future<> push_schema_mutation(const gms::inet_address& endpoint, const std::vector<mutation>& schema); future<> passive_announce(); void schedule_schema_pull(const gms::inet_address& endpoint, const gms::endpoint_state& state); future<> maybe_schedule_schema_pull(const utils::UUID& their_version, const gms::inet_address& endpoint); public: future<> maybe_sync(const schema_ptr& s, netw::msg_addr endpoint); // Returns schema of given version, either from cache or from remote node identified by 'from'. // The returned schema may not be synchronized. See schema::is_synced(). // Intended to be used in the read path. future<schema_ptr> get_schema_for_read(table_schema_version, netw::msg_addr from, netw::messaging_service& ms); // Returns schema of given version, either from cache or from remote node identified by 'from'. // Ensures that this node is synchronized with the returned schema. See schema::is_synced(). // Intended to be used in the write path, which relies on synchronized schema. future<schema_ptr> get_schema_for_write(table_schema_version, netw::msg_addr from, netw::messaging_service& ms); private: virtual void on_join(gms::inet_address endpoint, gms::endpoint_state ep_state) override; virtual void on_change(gms::inet_address endpoint, gms::application_state state, const gms::versioned_value& value) override; virtual void on_alive(gms::inet_address endpoint, gms::endpoint_state state) override; virtual void on_dead(gms::inet_address endpoint, gms::endpoint_state state) override {} virtual void on_remove(gms::inet_address endpoint) override {} virtual void on_restart(gms::inet_address endpoint, gms::endpoint_state state) override {} virtual void before_change(gms::inet_address endpoint, gms::endpoint_state current_state, gms::application_state new_statekey, const gms::versioned_value& newvalue) override {} }; future<column_mapping> get_column_mapping(utils::UUID table_id, table_schema_version v); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2015-present ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <type_traits> #include "service/migration_listener.hh" #include "gms/endpoint_state.hh" #include <seastar/core/distributed.hh> #include <seastar/core/abort_source.hh> #include <seastar/core/gate.hh> #include "gms/inet_address.hh" #include "gms/feature.hh" #include "gms/i_endpoint_state_change_subscriber.hh" #include "message/msg_addr.hh" #include "utils/UUID.hh" #include "utils/serialized_action.hh" #include "service/raft/raft_group_registry.hh" #include <vector> class canonical_mutation; class frozen_mutation; namespace cql3 { namespace functions { class user_function; class user_aggregate; }} namespace netw { class messaging_service; } namespace gms { class gossiper; enum class application_state; class versioned_value; } namespace service { template<typename M> concept MergeableMutation = std::is_same<M, canonical_mutation>::value || std::is_same<M, frozen_mutation>::value; class migration_manager : public seastar::async_sharded_service<migration_manager>, public gms::i_endpoint_state_change_subscriber, public seastar::peering_sharded_service<migration_manager> { private: migration_notifier& _notifier; std::unordered_map<netw::msg_addr, serialized_action, netw::msg_addr::hash> _schema_pulls; std::vector<gms::feature::listener_registration> _feature_listeners; seastar::gate _background_tasks; static const std::chrono::milliseconds migration_delay; gms::feature_service& _feat; netw::messaging_service& _messaging; gms::gossiper& _gossiper; seastar::abort_source _as; service::raft_group_registry& _raft_gr; serialized_action _schema_push; utils::UUID _schema_version_to_publish; public: migration_manager(migration_notifier&, gms::feature_service&, netw::messaging_service& ms, gms::gossiper& gossiper, service::raft_group_registry& raft_gr); migration_notifier& get_notifier() { return _notifier; } const migration_notifier& get_notifier() const { return _notifier; } future<> submit_migration_task(const gms::inet_address& endpoint, bool can_ignore_down_node = true); // Makes sure that this node knows about all schema changes known by "nodes" that were made prior to this call. future<> sync_schema(const database& db, const std::vector<gms::inet_address>& nodes); // Fetches schema from remote node and applies it locally. // Differs from submit_migration_task() in that all errors are propagated. // Coalesces requests. future<> merge_schema_from(netw::msg_addr); future<> do_merge_schema_from(netw::msg_addr); // Merge mutations received from src. // Keep mutations alive around whole async operation. future<> merge_schema_from(netw::msg_addr src, const std::vector<canonical_mutation>& mutations); // Deprecated. The canonical mutation should be used instead. future<> merge_schema_from(netw::msg_addr src, const std::vector<frozen_mutation>& mutations); template<typename M> requires MergeableMutation<M> future<> merge_schema_in_background(netw::msg_addr src, const std::vector<M>& mutations) { return with_gate(_background_tasks, [this, src, &mutations] { return merge_schema_from(src, mutations); }); } bool should_pull_schema_from(const gms::inet_address& endpoint); bool has_compatible_schema_tables_version(const gms::inet_address& endpoint); future<> announce_keyspace_update(lw_shared_ptr<keyspace_metadata> ksm); std::vector<mutation> prepare_keyspace_update_announcement(lw_shared_ptr<keyspace_metadata> ksm); future<> announce_new_keyspace(lw_shared_ptr<keyspace_metadata> ksm); future<> announce_new_keyspace(lw_shared_ptr<keyspace_metadata> ksm, api::timestamp_type timestamp); std::vector<mutation> prepare_new_keyspace_announcement(lw_shared_ptr<keyspace_metadata> ksm, api::timestamp_type timestamp); // The timestamp parameter can be used to ensure that all nodes update their internal tables' schemas // with identical timestamps, which can prevent an undeeded schema exchange future<> announce_column_family_update(schema_ptr cfm, bool from_thrift, std::optional<api::timestamp_type> timestamp); future<std::vector<mutation>> prepare_column_family_update_announcement(schema_ptr cfm, bool from_thrift, std::vector<view_ptr> view_updates, std::optional<api::timestamp_type> ts_opt); future<> announce_new_column_family(schema_ptr cfm); future<std::vector<mutation>> prepare_new_column_family_announcement(schema_ptr cfm); future<> announce_new_column_family(schema_ptr cfm, api::timestamp_type timestamp); future<std::vector<mutation>> prepare_new_column_family_announcement(schema_ptr cfm, api::timestamp_type timestamp); future<std::vector<mutation>> prepare_new_type_announcement(user_type new_type); future<std::vector<mutation>> prepare_new_function_announcement(shared_ptr<cql3::functions::user_function> func); future<std::vector<mutation>> prepare_new_aggregate_announcement(shared_ptr<cql3::functions::user_aggregate> aggregate); future<std::vector<mutation>> prepare_function_drop_announcement(shared_ptr<cql3::functions::user_function> func); future<std::vector<mutation>> prepare_aggregate_drop_announcement(shared_ptr<cql3::functions::user_aggregate> aggregate); future<std::vector<mutation>> prepare_update_type_announcement(user_type updated_type); future<> announce_keyspace_drop(const sstring& ks_name); std::vector<mutation> prepare_keyspace_drop_announcement(const sstring& ks_name); class drop_views_tag; using drop_views = bool_class<drop_views_tag>; future<> announce_column_family_drop(const sstring& ks_name, const sstring& cf_name, drop_views drop_views = drop_views::no); future<std::vector<mutation>> prepare_column_family_drop_announcement(const sstring& ks_name, const sstring& cf_name, drop_views drop_views = drop_views::no); future<std::vector<mutation>> prepare_type_drop_announcement(user_type dropped_type); future<> announce_new_view(view_ptr view); future<std::vector<mutation>> prepare_new_view_announcement(view_ptr view); future<std::vector<mutation>> prepare_view_update_announcement(view_ptr view); future<std::vector<mutation>> prepare_view_drop_announcement(const sstring& ks_name, const sstring& cf_name); // the function need to be called if a user wants to access most up-to-date schema state future<> schema_read_barrier(); // used to check if raft is enabled on the cluster bool is_raft_enabled() { return _raft_gr.is_enabled(); } /** * actively announce a new version to active hosts via rpc * @param schema The schema mutation to be applied */ // Returns a future on the local application of the schema future<> announce(std::vector<mutation> schema); void passive_announce(utils::UUID version); future<> drain(); future<> stop(); /** * Known peers in the cluster have the same schema version as us. */ bool have_schema_agreement(); void init_messaging_service(); private: future<> uninit_messaging_service(); future<> include_keyspace_and_announce( const keyspace_metadata& keyspace, std::vector<mutation> mutations); future<std::vector<mutation>> include_keyspace(const keyspace_metadata& keyspace, std::vector<mutation> mutations); future<std::vector<mutation>> do_prepare_new_type_announcement(user_type new_type); future<> do_announce_new_type(user_type new_type); future<> push_schema_mutation(const gms::inet_address& endpoint, const std::vector<mutation>& schema); future<> passive_announce(); void schedule_schema_pull(const gms::inet_address& endpoint, const gms::endpoint_state& state); future<> maybe_schedule_schema_pull(const utils::UUID& their_version, const gms::inet_address& endpoint); public: future<> maybe_sync(const schema_ptr& s, netw::msg_addr endpoint); // Returns schema of given version, either from cache or from remote node identified by 'from'. // The returned schema may not be synchronized. See schema::is_synced(). // Intended to be used in the read path. future<schema_ptr> get_schema_for_read(table_schema_version, netw::msg_addr from, netw::messaging_service& ms); // Returns schema of given version, either from cache or from remote node identified by 'from'. // Ensures that this node is synchronized with the returned schema. See schema::is_synced(). // Intended to be used in the write path, which relies on synchronized schema. future<schema_ptr> get_schema_for_write(table_schema_version, netw::msg_addr from, netw::messaging_service& ms); private: virtual void on_join(gms::inet_address endpoint, gms::endpoint_state ep_state) override; virtual void on_change(gms::inet_address endpoint, gms::application_state state, const gms::versioned_value& value) override; virtual void on_alive(gms::inet_address endpoint, gms::endpoint_state state) override; virtual void on_dead(gms::inet_address endpoint, gms::endpoint_state state) override {} virtual void on_remove(gms::inet_address endpoint) override {} virtual void on_restart(gms::inet_address endpoint, gms::endpoint_state state) override {} virtual void before_change(gms::inet_address endpoint, gms::endpoint_state current_state, gms::application_state new_statekey, const gms::versioned_value& newvalue) override {} }; future<column_mapping> get_column_mapping(utils::UUID table_id, table_schema_version v); }
add is_raft_enabled() to check if raft is enabled on a cluster
migration_manager: add is_raft_enabled() to check if raft is enabled on a cluster
C++
agpl-3.0
scylladb/scylla,scylladb/scylla,scylladb/scylla,scylladb/scylla
1f7da7808913e572c73df984293ce7aa855a46c3
kernel/include/arp_layer.hpp
kernel/include/arp_layer.hpp
//======================================================================= // Copyright Baptiste Wicht 2013-2016. // 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) //======================================================================= #ifndef NET_ARP_LAYER_H #define NET_ARP_LAYER_H #include <types.hpp> #include "ethernet_layer.hpp" namespace network { namespace arp { struct header { uint16_t hw_type; uint16_t protocol_type; uint8_t hw_len; uint8_t protocol_len; uint16_t operation; } __attribute__((packed)); void decode(network::ethernet::packet& packet); } // end of arp namespace } // end of network namespace #endif
//======================================================================= // Copyright Baptiste Wicht 2013-2016. // 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) //======================================================================= #ifndef NET_ARP_LAYER_H #define NET_ARP_LAYER_H #include <types.hpp> #include "ethernet_layer.hpp" namespace network { namespace arp { struct header { uint16_t hw_type; uint16_t protocol_type; uint8_t hw_len; uint8_t protocol_len; uint16_t operation; uint16_t source_hw_addr[3]; uint16_t source_protocol_addr[2]; uint16_t target_hw_addr[3]; uint16_t target_protocol_addr[2]; } __attribute__((packed)); void decode(network::ethernet::packet& packet); } // end of arp namespace } // end of network namespace #endif
Complete the header
Complete the header
C++
mit
wichtounet/thor-os,wichtounet/thor-os
2d03e7be8be2c72d7b9f42a8231fd8d00a818fc0
src/spelling/spellchecker_service_main.cc
src/spelling/spellchecker_service_main.cc
// Copyright 2010-2021, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Copyright 2010-2021, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. int main(int argc, char* argv[]) { return 0; }
Fix an OSS build error.
Fix an OSS build error. * cc_binary requires a main function. PiperOrigin-RevId: 450640612
C++
bsd-3-clause
google/mozc,google/mozc,google/mozc,fcitx/mozc,fcitx/mozc,fcitx/mozc,fcitx/mozc,google/mozc,fcitx/mozc,google/mozc
5251d34e4044d3711acd9c18eac3fc3963f421c4
src/tools/rest-backend/service_config.cpp
src/tools/rest-backend/service_config.cpp
/** * @file * * @brief implementation of the config service class * * @copyright BSD License (see doc/LICENSE.md or http://www.libelektra.org) */ #include <algorithm> #include <regex> #include <boost/algorithm/string/predicate.hpp> #include <service.hpp> namespace kdbrest { namespace service { const std::string REGEX_CONF_KEY = "((?:[a-zA-Z_]+(?:\\.?[a-zA-Z_])+)?)\\.?#_?([0-9]+)\\.?((?:[a-zA-Z0-9_#]+(?:\\.?[a-zA-Z0-9_#])+)?)"; /** * @brief can be used to load the configuration of the whole application * * the configuration is loaded from the key database provided by elektra. * the result can be used to bootstrap the application (cppcms service). */ cppcms::json::value ConfigEngine::loadApplicationConfiguration () const { cppcms::json::value result; kdb::KDB kdb; kdb::KeySet ks; kdb.get (ks, ELEKTRA_REST_CONFIG_ROOT); ks = ks.cut (kdb::Key (ELEKTRA_REST_CONFIG_ROOT, KEY_END)); for (auto elem : ks) { std::string key = elem.getName ().substr (elem.getName ().find (ELEKTRA_REST_CONFIG_ROOT) + strlen (ELEKTRA_REST_CONFIG_ROOT) + 1); std::replace (key.begin (), key.end (), '/', '.'); this->setValue (result, key, elem); } return result; } /** * @brief can be used to set a key value to a cppcms::json::value * * checks the path for an array and recursively sets the value then. * for objects the path is simply set. * * @param config the current configuration value * @param path remaining path to set * @param key the elektra key containing the value to set */ void ConfigEngine::setValue (cppcms::json::value & config, std::string path, kdb::Key & key) const { // check if the key contains an array std::regex array_regex (REGEX_CONF_KEY); std::smatch matches; // there is an array in the path if (std::regex_match (path, matches, array_regex) && !matches.empty ()) { // here we have a structure like: some.path.before.#_14.array // so we delegate call! if (!matches.str (1).empty ()) { // next element will be an array, so make one try { config.at (matches.str (1)); } catch (cppcms::json::bad_value_cast & e) { config.set (matches.str (1), cppcms::json::array ()); } this->setValue (config.at (matches.str (1)), matches.str (0).erase (0, matches.str (1).length () + 1), key); return; } // here we have a structure like: #_14.var // while it is not yet sure if ".var" is really there int array_index = std::stoi (matches.str (2)); if (config.type () != cppcms::json::is_array) { config.set_value (cppcms::json::array ()); } // with remaining part like ".var" we need to call recursively if (!matches.str (3).empty ()) { try { config[array_index]; } catch (cppcms::json::bad_value_cast & e) { config[array_index] = cppcms::json::object (); } this->setValue (config[array_index], matches.str (3), key); return; } // otherwise we can set directly try { config[array_index] = key.get<int> (); return; } catch (kdb::KeyTypeConversion & e) { // do nothing, it's fine } try { std::string val = key.getString (); if (val == "true") { config[array_index] = true; } else if (val == "false") { config[array_index] = false; } else { config[array_index] = val; } return; } catch (kdb::KeyTypeConversion & e) { // do nothing, it's fine } } // there is no array in the path, set as object(s) else { try { config.set (path, key.get<int> ()); return; } catch (kdb::KeyTypeConversion & e) { // do nothing, it's fine } try { std::string val = key.getString (); if (val == "true") { config.set (path, true); } else if (val == "false") { config.set (path, false); } else { config.set (path, val); } return; } catch (kdb::KeyTypeConversion & e) { // do nothing, it's fine } } } } // namespace service } // namespace kdbrest
/** * @file * * @brief implementation of the config service class * * @copyright BSD License (see doc/LICENSE.md or http://www.libelektra.org) */ #include <algorithm> #include <regex> #include <boost/algorithm/string/predicate.hpp> #include <service.hpp> namespace kdbrest { namespace service { const std::string REGEX_CONF_KEY = "((?:[a-zA-Z_]+(?:\\.?[a-zA-Z_])+)?)\\.?#_?([0-9]+)\\.?((?:[a-zA-Z0-9_#]+(?:\\.?[a-zA-Z0-9_#])+)?)"; /** * @brief can be used to load the configuration of the whole application * * the configuration is loaded from the key database provided by elektra. * the result can be used to bootstrap the application (cppcms service). */ cppcms::json::value ConfigEngine::loadApplicationConfiguration () const { cppcms::json::value result; kdb::KDB kdb; kdb::KeySet ks; kdb.get (ks, ELEKTRA_REST_CONFIG_ROOT); ks = ks.cut (kdb::Key (ELEKTRA_REST_CONFIG_ROOT, KEY_END)); for (auto elem : ks) { std::string key = elem.getName ().substr (elem.getName ().find (ELEKTRA_REST_CONFIG_ROOT) + strlen (ELEKTRA_REST_CONFIG_ROOT) + 1); std::replace (key.begin (), key.end (), '/', '.'); this->setValue (result, key, elem); } return result; } /** * @brief can be used to set a key value to a cppcms::json::value * * checks the path for an array and recursively sets the value then. * for objects the path is simply set. * * @param config the current configuration value * @param path remaining path to set * @param key the elektra key containing the value to set */ void ConfigEngine::setValue (cppcms::json::value & config, std::string path, kdb::Key & key) const { // check if the key contains an array std::regex array_regex (REGEX_CONF_KEY); std::smatch matches; // there is an array in the path if (std::regex_match (path, matches, array_regex) && !matches.empty ()) { // here we have a structure like: some.path.before.#_14.array // so we delegate call! if (!matches.str (1).empty ()) { // next element will be an array, so make one try { config.at (matches.str (1)); } catch (cppcms::json::bad_value_cast & e) { config.set (matches.str (1), cppcms::json::array ()); } this->setValue (config.at (matches.str (1)), matches.str (0).erase (0, matches.str (1).length () + 1), key); return; } // here we have a structure like: #_14.var // while it is not yet sure if ".var" is really there int array_index = std::stoi (matches.str (2)); if (config.type () != cppcms::json::is_array) { config.set_value (cppcms::json::array ()); } // with remaining part like ".var" we need to call recursively if (!matches.str (3).empty ()) { try { config[array_index]; } catch (cppcms::json::bad_value_cast & e) { config[array_index] = cppcms::json::object (); } this->setValue (config[array_index], matches.str (3), key); return; } // otherwise we can set directly try { if (std::to_string (key.get<int> ()).length () == key.get<std::string> ().length ()) { config[array_index] = key.get<int> (); return; } } catch (kdb::KeyTypeConversion & e) { // do nothing, it's fine } try { std::string val = key.getString (); if (val == "true") { config[array_index] = true; } else if (val == "false") { config[array_index] = false; } else { config[array_index] = val; } return; } catch (kdb::KeyTypeConversion & e) { // do nothing, it's fine } } // there is no array in the path, set as object(s) else { try { if (std::to_string (key.get<int> ()).length () == key.get<std::string> ().length ()) { config.set (path, key.get<int> ()); return; } } catch (kdb::KeyTypeConversion & e) { // do nothing, it's fine } try { std::string val = key.getString (); if (val == "true") { config.set (path, true); } else if (val == "false") { config.set (path, false); } else { config.set (path, val); } return; } catch (kdb::KeyTypeConversion & e) { // do nothing, it's fine } } } } // namespace service } // namespace kdbrest
fix small configuration transformer bug (IP was read as int)
rest-backend: fix small configuration transformer bug (IP was read as int)
C++
bsd-3-clause
BernhardDenner/libelektra,BernhardDenner/libelektra,e1528532/libelektra,BernhardDenner/libelektra,mpranj/libelektra,petermax2/libelektra,mpranj/libelektra,petermax2/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,petermax2/libelektra,e1528532/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,e1528532/libelektra,petermax2/libelektra,BernhardDenner/libelektra,e1528532/libelektra,mpranj/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,e1528532/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,ElektraInitiative/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,petermax2/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,e1528532/libelektra,mpranj/libelektra,petermax2/libelektra
e308e5a49ab904f17d06b91921c1f495558bf66d
gm/bitmapcopy.cpp
gm/bitmapcopy.cpp
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" namespace skiagm { static const char* gConfigNames[] = { "unknown config", "A1", "A8", "Index8", "565", "4444", "8888" }; SkBitmap::Config gConfigs[] = { SkBitmap::kRGB_565_Config, SkBitmap::kARGB_4444_Config, SkBitmap::kARGB_8888_Config, }; #define NUM_CONFIGS (sizeof(gConfigs) / sizeof(SkBitmap::Config)) static void draw_checks(SkCanvas* canvas, int width, int height) { SkPaint paint; paint.setColor(SK_ColorRED); canvas->drawRectCoords(SkIntToScalar(0), SkIntToScalar(0), SkIntToScalar(width / 2), SkIntToScalar(height / 2), paint); paint.setColor(SK_ColorGREEN); canvas->drawRectCoords(SkIntToScalar(width / 2), SkIntToScalar(0), SkIntToScalar(width), SkIntToScalar(height / 2), paint); paint.setColor(SK_ColorBLUE); canvas->drawRectCoords(SkIntToScalar(0), SkIntToScalar(height / 2), SkIntToScalar(width / 2), SkIntToScalar(height), paint); paint.setColor(SK_ColorYELLOW); canvas->drawRectCoords(SkIntToScalar(width / 2), SkIntToScalar(height / 2), SkIntToScalar(width), SkIntToScalar(height), paint); } class BitmapCopyGM : public GM { public: SkBitmap fDst[NUM_CONFIGS]; BitmapCopyGM() { this->setBGColor(0xFFDDDDDD); } protected: virtual SkString onShortName() { return SkString("bitmapcopy"); } virtual SkISize onISize() { return make_isize(540, 330); } virtual void onDraw(SkCanvas* canvas) { SkPaint paint; SkScalar horizMargin(SkIntToScalar(10)); SkScalar vertMargin(SkIntToScalar(10)); draw_checks(canvas, 40, 40); SkBitmap src = canvas->getDevice()->accessBitmap(false); for (unsigned i = 0; i < NUM_CONFIGS; ++i) { if (!src.deepCopyTo(&fDst[i], gConfigs[i])) { src.copyTo(&fDst[i], gConfigs[i]); } } canvas->clear(0xFFDDDDDD); paint.setAntiAlias(true); SkScalar width = SkIntToScalar(40); SkScalar height = SkIntToScalar(40); if (paint.getFontSpacing() > height) { height = paint.getFontSpacing(); } for (unsigned i = 0; i < NUM_CONFIGS; i++) { const char* name = gConfigNames[src.config()]; SkScalar textWidth = paint.measureText(name, strlen(name)); if (textWidth > width) { width = textWidth; } } SkScalar horizOffset = width + horizMargin; SkScalar vertOffset = height + vertMargin; canvas->translate(SkIntToScalar(20), SkIntToScalar(20)); for (unsigned i = 0; i < NUM_CONFIGS; i++) { canvas->save(); // Draw destination config name const char* name = gConfigNames[fDst[i].config()]; SkScalar textWidth = paint.measureText(name, strlen(name)); SkScalar x = (width - textWidth) / SkScalar(2); SkScalar y = paint.getFontSpacing() / SkScalar(2); canvas->drawText(name, strlen(name), x, y, paint); // Draw destination bitmap canvas->translate(0, vertOffset); x = (width - 40) / SkScalar(2); canvas->drawBitmap(fDst[i], x, 0, &paint); canvas->restore(); canvas->translate(horizOffset, 0); } } virtual uint32_t onGetFlags() const { return kSkipPicture_Flag; } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new BitmapCopyGM; } static GMRegistry reg(MyFactory); }
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" namespace skiagm { static const char* gConfigNames[] = { "unknown config", "A1", "A8", "Index8", "565", "4444", "8888" }; SkBitmap::Config gConfigs[] = { SkBitmap::kRGB_565_Config, SkBitmap::kARGB_4444_Config, SkBitmap::kARGB_8888_Config, }; #define NUM_CONFIGS (sizeof(gConfigs) / sizeof(SkBitmap::Config)) static void draw_checks(SkCanvas* canvas, int width, int height) { SkPaint paint; paint.setColor(SK_ColorRED); canvas->drawRectCoords(SkIntToScalar(0), SkIntToScalar(0), SkIntToScalar(width / 2), SkIntToScalar(height / 2), paint); paint.setColor(SK_ColorGREEN); canvas->drawRectCoords(SkIntToScalar(width / 2), SkIntToScalar(0), SkIntToScalar(width), SkIntToScalar(height / 2), paint); paint.setColor(SK_ColorBLUE); canvas->drawRectCoords(SkIntToScalar(0), SkIntToScalar(height / 2), SkIntToScalar(width / 2), SkIntToScalar(height), paint); paint.setColor(SK_ColorYELLOW); canvas->drawRectCoords(SkIntToScalar(width / 2), SkIntToScalar(height / 2), SkIntToScalar(width), SkIntToScalar(height), paint); } class BitmapCopyGM : public GM { public: SkBitmap fDst[NUM_CONFIGS]; BitmapCopyGM() { this->setBGColor(0xFFDDDDDD); } protected: virtual SkString onShortName() { return SkString("bitmapcopy"); } virtual SkISize onISize() { return make_isize(540, 330); } virtual void onDraw(SkCanvas* canvas) { SkPaint paint; SkScalar horizMargin(SkIntToScalar(10)); SkScalar vertMargin(SkIntToScalar(10)); draw_checks(canvas, 40, 40); SkBitmap src = canvas->getDevice()->accessBitmap(false); for (unsigned i = 0; i < NUM_CONFIGS; ++i) { if (!src.deepCopyTo(&fDst[i], gConfigs[i])) { src.copyTo(&fDst[i], gConfigs[i]); } } canvas->clear(0xFFDDDDDD); paint.setAntiAlias(true); SkScalar width = SkIntToScalar(40); SkScalar height = SkIntToScalar(40); if (paint.getFontSpacing() > height) { height = paint.getFontSpacing(); } for (unsigned i = 0; i < NUM_CONFIGS; i++) { const char* name = gConfigNames[src.config()]; SkScalar textWidth = paint.measureText(name, strlen(name)); if (textWidth > width) { width = textWidth; } } SkScalar horizOffset = width + horizMargin; SkScalar vertOffset = height + vertMargin; canvas->translate(SkIntToScalar(20), SkIntToScalar(20)); for (unsigned i = 0; i < NUM_CONFIGS; i++) { canvas->save(); // Draw destination config name const char* name = gConfigNames[fDst[i].config()]; SkScalar textWidth = paint.measureText(name, strlen(name)); SkScalar x = (width - textWidth) / SkScalar(2); SkScalar y = paint.getFontSpacing() / SkScalar(2); canvas->drawText(name, strlen(name), x, y, paint); // Draw destination bitmap canvas->translate(0, vertOffset); x = (width - 40) / SkScalar(2); canvas->drawBitmap(fDst[i], x, 0, &paint); canvas->restore(); canvas->translate(horizOffset, 0); } } virtual uint32_t onGetFlags() const { return kSkipPicture_Flag; } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// #ifndef SK_BUILD_FOR_ANDROID static GM* MyFactory(void*) { return new BitmapCopyGM; } static GMRegistry reg(MyFactory); #endif }
Disable bitmapcopy gm on Android
Disable bitmapcopy gm on Android This has been failing on Nexus S. Disable so that we don't miss further regressions. Bug @ http://code.google.com/p/skia/issues/detail?id=705 Review URL: https://codereview.appspot.com/6427053 git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@4696 2bbb7eff-a529-9590-31e7-b0007b416f81
C++
bsd-3-clause
Frankie-666/color-emoji.skia,Hankuo/color-emoji.skia,Hankuo/color-emoji.skia,hbwhlklive/color-emoji.skia,MatChung/color-emoji.skia,MatChung/color-emoji.skia,Frankie-666/color-emoji.skia,hbwhlklive/color-emoji.skia,Hankuo/color-emoji.skia,Frankie-666/color-emoji.skia,Frankie-666/color-emoji.skia,hbwhlklive/color-emoji.skia,Hankuo/color-emoji.skia,hbwhlklive/color-emoji.skia,MatChung/color-emoji.skia,hbwhlklive/color-emoji.skia,MatChung/color-emoji.skia,Frankie-666/color-emoji.skia,Hankuo/color-emoji.skia,MatChung/color-emoji.skia,MatChung/color-emoji.skia,Hankuo/color-emoji.skia,hbwhlklive/color-emoji.skia,Frankie-666/color-emoji.skia
797af8baa6583d1ac10c951b4e968861d570b61a
npapi/vlcshell.cpp
npapi/vlcshell.cpp
/***************************************************************************** * vlcshell.cpp: a VLC plugin for Mozilla ***************************************************************************** * Copyright (C) 2002-2009 the VideoLAN team * $Id$ * * Authors: Samuel Hocevar <[email protected]> * Jean-Paul Saman <[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 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <stdio.h> #include <string.h> #include <stdlib.h> #include "vlcplugin.h" #include "vlcshell.h" /****************************************************************************** * UNIX-only API calls *****************************************************************************/ NPP_GET_MIME_CONST char * NPP_GetMIMEDescription( void ) { return mimetype; } NPError NPP_GetValue( NPP instance, NPPVariable variable, void *value ) { static char psz_name[] = PLUGIN_NAME; static char psz_desc[1000]; /* plugin class variables */ switch( variable ) { case NPPVpluginNameString: *((char **)value) = psz_name; return NPERR_NO_ERROR; case NPPVpluginDescriptionString: snprintf( psz_desc, sizeof(psz_desc), PLUGIN_DESCRIPTION, libvlc_get_version() ); *((char **)value) = psz_desc; return NPERR_NO_ERROR; #if defined(XP_UNIX) case NPPVpluginNeedsXEmbed: *((bool *)value) = true; return NPERR_NO_ERROR; #endif default: /* move on to instance variables ... */ ; } if( instance == NULL ) { return NPERR_INVALID_INSTANCE_ERROR; } /* plugin instance variables */ VlcPlugin* p_plugin = reinterpret_cast<VlcPlugin*>(instance->pdata); if( NULL == p_plugin ) { /* plugin has not been initialized yet ! */ return NPERR_INVALID_INSTANCE_ERROR; } switch( variable ) { case NPPVpluginScriptableNPObject: { /* retrieve plugin root class */ NPClass *scriptClass = p_plugin->getScriptClass(); if( scriptClass ) { /* create an instance and return it */ *(NPObject**)value = NPN_CreateObject(instance, scriptClass); return NPERR_NO_ERROR; } break; } default: ; } return NPERR_GENERIC_ERROR; } /* * there is some confusion in gecko headers regarding definition of this API * NPPVariable is wrongly defined as NPNVariable, which sounds incorrect. */ NPError NPP_SetValue( NPP instance, NPNVariable variable, void *value ) { return NPERR_GENERIC_ERROR; } /****************************************************************************** * Mac-only API calls *****************************************************************************/ #ifdef XP_MACOSX int16_t NPP_HandleEvent( NPP instance, void * event ) { static UInt32 lastMouseUp = 0; if( instance == NULL ) { return false; } VlcPlugin* p_plugin = reinterpret_cast<VlcPlugin*>(instance->pdata); if( p_plugin == NULL ) { return false; } #ifndef __x86_64__ EventRecord *myEvent = (EventRecord*)event; switch( myEvent->what ) { case nullEvent: return true; case mouseDown: { if( (myEvent->when - lastMouseUp) < GetDblTime() ) { /* double click */ p_plugin->toggle_fullscreen(); } return true; } case mouseUp: lastMouseUp = myEvent->when; return true; case keyUp: case keyDown: case autoKey: return true; case updateEvt: { const NPWindow& npwindow = p_plugin->getWindow(); if( npwindow.window ) { bool hasVout = false; if( p_plugin->playlist_isplaying() ) { hasVout = p_plugin->player_has_vout(); #if 0 if( hasVout ) { libvlc_rectangle_t area; area.left = 0; area.top = 0; area.right = npwindow.width; area.bottom = npwindow.height; libvlc_video_redraw_rectangle(p_plugin->getMD(), &area, NULL); } #else #warning disabled code #endif } if( ! hasVout ) { /* draw the text from p_plugin->psz_text */ ForeColor(blackColor); PenMode( patCopy ); /* seems that firefox forgets to set the following * on occasion (reload) */ SetOrigin(((NP_Port *)npwindow.window)->portx, ((NP_Port *)npwindow.window)->porty); Rect rect; rect.left = 0; rect.top = 0; rect.right = npwindow.width; rect.bottom = npwindow.height; PaintRect( &rect ); ForeColor(whiteColor); MoveTo( (npwindow.width-80)/ 2 , npwindow.height / 2 ); if( p_plugin->psz_text ) DrawText( p_plugin->psz_text, 0, strlen(p_plugin->psz_text) ); } } return true; } case activateEvt: return false; case NPEventType_GetFocusEvent: case NPEventType_LoseFocusEvent: return true; case NPEventType_AdjustCursorEvent: return false; case NPEventType_MenuCommandEvent: return false; case NPEventType_ClippingChangedEvent: return false; case NPEventType_ScrollingBeginsEvent: return true; case NPEventType_ScrollingEndsEvent: return true; default: ; } #endif // __x86_64__ return false; } #endif /* XP_MACOSX */ /****************************************************************************** * General Plug-in Calls *****************************************************************************/ NPError NPP_Initialize( void ) { #ifdef XP_UNIX NPError err = NPERR_NO_ERROR; bool supportsXEmbed = false; err = NPN_GetValue( NULL, NPNVSupportsXEmbedBool, (void *)&supportsXEmbed ); if ( err != NPERR_NO_ERROR || supportsXEmbed != true ) return NPERR_INCOMPATIBLE_VERSION_ERROR; #endif return NPERR_NO_ERROR; } #ifdef OJI jref NPP_GetJavaClass( void ) { return NULL; } #endif void NPP_Shutdown( void ) { ; } NPError NPP_New( NPMIMEType pluginType, NPP instance, NPuint16_t mode, NPint16_t argc, char* argn[], char* argv[], NPSavedData* saved ) { NPError status; if( instance == NULL ) { return NPERR_INVALID_INSTANCE_ERROR; } VlcPlugin * p_plugin = new VlcPlugin( instance, mode ); if( NULL == p_plugin ) { return NPERR_OUT_OF_MEMORY_ERROR; } status = p_plugin->init(argc, argn, argv); if( NPERR_NO_ERROR == status ) { instance->pdata = reinterpret_cast<void*>(p_plugin); } else { delete p_plugin; } return status; } NPError NPP_Destroy( NPP instance, NPSavedData** save ) { if( NULL == instance ) return NPERR_INVALID_INSTANCE_ERROR; VlcPlugin* p_plugin = reinterpret_cast<VlcPlugin*>(instance->pdata); if( NULL == p_plugin ) return NPERR_NO_ERROR; instance->pdata = NULL; if( p_plugin->playlist_isplaying() ) p_plugin->playlist_stop(); delete p_plugin; return NPERR_NO_ERROR; } NPError NPP_SetWindow( NPP instance, NPWindow* window ) { if( ! instance ) { return NPERR_INVALID_INSTANCE_ERROR; } /* NPP_SetWindow may be called before NPP_New (Opera) */ VlcPlugin* p_plugin = reinterpret_cast<VlcPlugin*>(instance->pdata); if( NULL == p_plugin ) { /* we should probably show a splash screen here */ return NPERR_NO_ERROR; } libvlc_instance_t *p_vlc = p_plugin->getVLC(); /* * PLUGIN DEVELOPERS: * Before setting window to point to the * new window, you may wish to compare the new window * info to the previous window (if any) to note window * size changes, etc. */ /* retrieve current window */ NPWindow& curr_window = p_plugin->getWindow(); if (window && window->window) { if (!curr_window.window) { /* we've just been created */ p_plugin->setWindow(*window); p_plugin->create_windows(); p_plugin->resize_windows(); } else { if (window->window == curr_window.window) { /* resize / move notification */ p_plugin->resize_windows(); } else { /* plugin parent window was changed, notify plugin about it */ p_plugin->destroy_windows(); p_plugin->setWindow(*window); p_plugin->create_windows(); p_plugin->resize_windows(); } } } else { if (curr_window.window) { /* we've been destroyed */ p_plugin->destroy_windows(); } } /* now display toolbar if asked through parameters */ if( p_plugin->b_toolbar ) { p_plugin->set_toolbar_visible(true); } if( !p_plugin->b_stream ) { if( p_plugin->psz_target ) { if( p_plugin->playlist_add( p_plugin->psz_target ) != -1 ) { if( p_plugin->b_autoplay ) { p_plugin->playlist_play(); } } p_plugin->b_stream = true; } } return NPERR_NO_ERROR; } NPError NPP_NewStream( NPP instance, NPMIMEType type, NPStream *stream, NPBool seekable, NPuint16_t *stype ) { if( NULL == instance ) { return NPERR_INVALID_INSTANCE_ERROR; } VlcPlugin *p_plugin = reinterpret_cast<VlcPlugin *>(instance->pdata); if( NULL == p_plugin ) { return NPERR_INVALID_INSTANCE_ERROR; } /* ** Firefox/Mozilla may decide to open a stream from the URL specified ** in the SRC parameter of the EMBED tag and pass it to us ** ** since VLC will open the SRC URL as well, we're not interested in ** that stream. Otherwise, we'll take it and queue it up in the playlist */ if( !p_plugin->psz_target || strcmp(stream->url, p_plugin->psz_target) ) { /* TODO: use pipes !!!! */ *stype = NP_ASFILEONLY; return NPERR_NO_ERROR; } return NPERR_GENERIC_ERROR; } NPint32_t NPP_WriteReady( NPP instance, NPStream *stream ) { /* TODO */ return 8*1024; } NPint32_t NPP_Write( NPP instance, NPStream *stream, NPint32_t offset, NPint32_t len, void *buffer ) { /* TODO */ return len; } NPError NPP_DestroyStream( NPP instance, NPStream *stream, NPError reason ) { if( instance == NULL ) { return NPERR_INVALID_INSTANCE_ERROR; } return NPERR_NO_ERROR; } void NPP_StreamAsFile( NPP instance, NPStream *stream, const char* fname ) { if( instance == NULL ) { return; } VlcPlugin *p_plugin = reinterpret_cast<VlcPlugin *>(instance->pdata); if( NULL == p_plugin ) { return; } if( p_plugin->playlist_add( stream->url ) != -1 ) { if( p_plugin->b_autoplay ) { p_plugin->playlist_play(); } } } void NPP_URLNotify( NPP instance, const char* url, NPReason reason, void* notifyData ) { /***** Insert NPP_URLNotify code here *****\ PluginInstance* p_plugin; if (instance != NULL) p_plugin = (PluginInstance*) instance->pdata; \*********************************************/ } void NPP_Print( NPP instance, NPPrint* printInfo ) { if( printInfo == NULL ) { return; } if( instance != NULL ) { /***** Insert NPP_Print code here *****\ PluginInstance* p_plugin = (PluginInstance*) instance->pdata; \**************************************/ if( printInfo->mode == NP_FULL ) { /* * PLUGIN DEVELOPERS: * If your plugin would like to take over * printing completely when it is in full-screen mode, * set printInfo->pluginPrinted to TRUE and print your * plugin as you see fit. If your plugin wants Netscape * to handle printing in this case, set * printInfo->pluginPrinted to FALSE (the default) and * do nothing. If you do want to handle printing * yourself, printOne is true if the print button * (as opposed to the print menu) was clicked. * On the Macintosh, platformPrint is a THPrint; on * Windows, platformPrint is a structure * (defined in npapi.h) containing the printer name, port, * etc. */ /***** Insert NPP_Print code here *****\ void* platformPrint = printInfo->print.fullPrint.platformPrint; NPBool printOne = printInfo->print.fullPrint.printOne; \**************************************/ /* Do the default*/ printInfo->print.fullPrint.pluginPrinted = false; } else { /* If not fullscreen, we must be embedded */ /* * PLUGIN DEVELOPERS: * If your plugin is embedded, or is full-screen * but you returned false in pluginPrinted above, NPP_Print * will be called with mode == NP_EMBED. The NPWindow * in the printInfo gives the location and dimensions of * the embedded plugin on the printed page. On the * Macintosh, platformPrint is the printer port; on * Windows, platformPrint is the handle to the printing * device context. */ /***** Insert NPP_Print code here *****\ NPWindow* printWindow = &(printInfo->print.embedPrint.window); void* platformPrint = printInfo->print.embedPrint.platformPrint; \**************************************/ } } }
/***************************************************************************** * vlcshell.cpp: a VLC plugin for Mozilla ***************************************************************************** * Copyright (C) 2002-2009 the VideoLAN team * $Id$ * * Authors: Samuel Hocevar <[email protected]> * Jean-Paul Saman <[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 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <stdio.h> #include <string.h> #include <stdlib.h> #include "vlcplugin.h" #include "vlcshell.h" /****************************************************************************** * UNIX-only API calls *****************************************************************************/ NPP_GET_MIME_CONST char * NPP_GetMIMEDescription( void ) { return mimetype; } NPError NPP_GetValue( NPP instance, NPPVariable variable, void *value ) { static char psz_name[] = PLUGIN_NAME; static char psz_desc[1000]; /* plugin class variables */ switch( variable ) { case NPPVpluginNameString: *((char **)value) = psz_name; return NPERR_NO_ERROR; case NPPVpluginDescriptionString: snprintf( psz_desc, sizeof(psz_desc), PLUGIN_DESCRIPTION, libvlc_get_version() ); *((char **)value) = psz_desc; return NPERR_NO_ERROR; #if defined(XP_UNIX) case NPPVpluginNeedsXEmbed: *((bool *)value) = true; return NPERR_NO_ERROR; #endif default: /* move on to instance variables ... */ ; } if( instance == NULL ) { return NPERR_INVALID_INSTANCE_ERROR; } /* plugin instance variables */ VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata); if( NULL == p_plugin ) { /* plugin has not been initialized yet ! */ return NPERR_INVALID_INSTANCE_ERROR; } switch( variable ) { case NPPVpluginScriptableNPObject: { /* retrieve plugin root class */ NPClass *scriptClass = p_plugin->getScriptClass(); if( scriptClass ) { /* create an instance and return it */ *(NPObject**)value = NPN_CreateObject(instance, scriptClass); return NPERR_NO_ERROR; } break; } default: ; } return NPERR_GENERIC_ERROR; } /* * there is some confusion in gecko headers regarding definition of this API * NPPVariable is wrongly defined as NPNVariable, which sounds incorrect. */ NPError NPP_SetValue( NPP instance, NPNVariable variable, void *value ) { return NPERR_GENERIC_ERROR; } /****************************************************************************** * Mac-only API calls *****************************************************************************/ #ifdef XP_MACOSX int16_t NPP_HandleEvent( NPP instance, void * event ) { static UInt32 lastMouseUp = 0; if( instance == NULL ) { return false; } VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata); if( p_plugin == NULL ) { return false; } #ifndef __x86_64__ EventRecord *myEvent = (EventRecord*)event; switch( myEvent->what ) { case nullEvent: return true; case mouseDown: { if( (myEvent->when - lastMouseUp) < GetDblTime() ) { /* double click */ p_plugin->toggle_fullscreen(); } return true; } case mouseUp: lastMouseUp = myEvent->when; return true; case keyUp: case keyDown: case autoKey: return true; case updateEvt: { const NPWindow& npwindow = p_plugin->getWindow(); if( npwindow.window ) { bool hasVout = false; if( p_plugin->playlist_isplaying() ) { hasVout = p_plugin->player_has_vout(); #if 0 if( hasVout ) { libvlc_rectangle_t area; area.left = 0; area.top = 0; area.right = npwindow.width; area.bottom = npwindow.height; libvlc_video_redraw_rectangle(p_plugin->getMD(), &area, NULL); } #else #warning disabled code #endif } if( ! hasVout ) { /* draw the text from p_plugin->psz_text */ ForeColor(blackColor); PenMode( patCopy ); /* seems that firefox forgets to set the following * on occasion (reload) */ SetOrigin(((NP_Port *)npwindow.window)->portx, ((NP_Port *)npwindow.window)->porty); Rect rect; rect.left = 0; rect.top = 0; rect.right = npwindow.width; rect.bottom = npwindow.height; PaintRect( &rect ); ForeColor(whiteColor); MoveTo( (npwindow.width-80)/ 2 , npwindow.height / 2 ); if( p_plugin->psz_text ) DrawText( p_plugin->psz_text, 0, strlen(p_plugin->psz_text) ); } } return true; } case activateEvt: return false; case NPEventType_GetFocusEvent: case NPEventType_LoseFocusEvent: return true; case NPEventType_AdjustCursorEvent: return false; case NPEventType_MenuCommandEvent: return false; case NPEventType_ClippingChangedEvent: return false; case NPEventType_ScrollingBeginsEvent: return true; case NPEventType_ScrollingEndsEvent: return true; default: ; } #endif // __x86_64__ return false; } #endif /* XP_MACOSX */ /****************************************************************************** * General Plug-in Calls *****************************************************************************/ NPError NPP_Initialize( void ) { #ifdef XP_UNIX NPError err = NPERR_NO_ERROR; bool supportsXEmbed = false; err = NPN_GetValue( NULL, NPNVSupportsXEmbedBool, (void *)&supportsXEmbed ); if ( err != NPERR_NO_ERROR || supportsXEmbed != true ) return NPERR_INCOMPATIBLE_VERSION_ERROR; #endif return NPERR_NO_ERROR; } #ifdef OJI jref NPP_GetJavaClass( void ) { return NULL; } #endif void NPP_Shutdown( void ) { ; } NPError NPP_New( NPMIMEType pluginType, NPP instance, NPuint16_t mode, NPint16_t argc, char* argn[], char* argv[], NPSavedData* saved ) { NPError status; if( instance == NULL ) { return NPERR_INVALID_INSTANCE_ERROR; } VlcPluginBase *p_plugin = new VlcPlugin( instance, mode ); if( NULL == p_plugin ) { return NPERR_OUT_OF_MEMORY_ERROR; } status = p_plugin->init(argc, argn, argv); if( NPERR_NO_ERROR == status ) { instance->pdata = reinterpret_cast<void*>(p_plugin); } else { delete p_plugin; } return status; } NPError NPP_Destroy( NPP instance, NPSavedData** save ) { if( NULL == instance ) return NPERR_INVALID_INSTANCE_ERROR; VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata); if( NULL == p_plugin ) return NPERR_NO_ERROR; instance->pdata = NULL; if( p_plugin->playlist_isplaying() ) p_plugin->playlist_stop(); delete p_plugin; return NPERR_NO_ERROR; } NPError NPP_SetWindow( NPP instance, NPWindow* window ) { if( ! instance ) { return NPERR_INVALID_INSTANCE_ERROR; } /* NPP_SetWindow may be called before NPP_New (Opera) */ VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata); if( NULL == p_plugin ) { /* we should probably show a splash screen here */ return NPERR_NO_ERROR; } libvlc_instance_t *p_vlc = p_plugin->getVLC(); /* * PLUGIN DEVELOPERS: * Before setting window to point to the * new window, you may wish to compare the new window * info to the previous window (if any) to note window * size changes, etc. */ /* retrieve current window */ NPWindow& curr_window = p_plugin->getWindow(); if (window && window->window) { if (!curr_window.window) { /* we've just been created */ p_plugin->setWindow(*window); p_plugin->create_windows(); p_plugin->resize_windows(); } else { if (window->window == curr_window.window) { /* resize / move notification */ p_plugin->resize_windows(); } else { /* plugin parent window was changed, notify plugin about it */ p_plugin->destroy_windows(); p_plugin->setWindow(*window); p_plugin->create_windows(); p_plugin->resize_windows(); } } } else { if (curr_window.window) { /* we've been destroyed */ p_plugin->destroy_windows(); } } /* now display toolbar if asked through parameters */ if( p_plugin->b_toolbar ) { p_plugin->set_toolbar_visible(true); } if( !p_plugin->b_stream ) { if( p_plugin->psz_target ) { if( p_plugin->playlist_add( p_plugin->psz_target ) != -1 ) { if( p_plugin->b_autoplay ) { p_plugin->playlist_play(); } } p_plugin->b_stream = true; } } return NPERR_NO_ERROR; } NPError NPP_NewStream( NPP instance, NPMIMEType type, NPStream *stream, NPBool seekable, NPuint16_t *stype ) { if( NULL == instance ) { return NPERR_INVALID_INSTANCE_ERROR; } VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata); if( NULL == p_plugin ) { return NPERR_INVALID_INSTANCE_ERROR; } /* ** Firefox/Mozilla may decide to open a stream from the URL specified ** in the SRC parameter of the EMBED tag and pass it to us ** ** since VLC will open the SRC URL as well, we're not interested in ** that stream. Otherwise, we'll take it and queue it up in the playlist */ if( !p_plugin->psz_target || strcmp(stream->url, p_plugin->psz_target) ) { /* TODO: use pipes !!!! */ *stype = NP_ASFILEONLY; return NPERR_NO_ERROR; } return NPERR_GENERIC_ERROR; } NPint32_t NPP_WriteReady( NPP instance, NPStream *stream ) { /* TODO */ return 8*1024; } NPint32_t NPP_Write( NPP instance, NPStream *stream, NPint32_t offset, NPint32_t len, void *buffer ) { /* TODO */ return len; } NPError NPP_DestroyStream( NPP instance, NPStream *stream, NPError reason ) { if( instance == NULL ) { return NPERR_INVALID_INSTANCE_ERROR; } return NPERR_NO_ERROR; } void NPP_StreamAsFile( NPP instance, NPStream *stream, const char* fname ) { if( instance == NULL ) { return; } VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata); if( NULL == p_plugin ) { return; } if( p_plugin->playlist_add( stream->url ) != -1 ) { if( p_plugin->b_autoplay ) { p_plugin->playlist_play(); } } } void NPP_URLNotify( NPP instance, const char* url, NPReason reason, void* notifyData ) { /***** Insert NPP_URLNotify code here *****\ PluginInstance* p_plugin; if (instance != NULL) p_plugin = (PluginInstance*) instance->pdata; \*********************************************/ } void NPP_Print( NPP instance, NPPrint* printInfo ) { if( printInfo == NULL ) { return; } if( instance != NULL ) { /***** Insert NPP_Print code here *****\ PluginInstance* p_plugin = (PluginInstance*) instance->pdata; \**************************************/ if( printInfo->mode == NP_FULL ) { /* * PLUGIN DEVELOPERS: * If your plugin would like to take over * printing completely when it is in full-screen mode, * set printInfo->pluginPrinted to TRUE and print your * plugin as you see fit. If your plugin wants Netscape * to handle printing in this case, set * printInfo->pluginPrinted to FALSE (the default) and * do nothing. If you do want to handle printing * yourself, printOne is true if the print button * (as opposed to the print menu) was clicked. * On the Macintosh, platformPrint is a THPrint; on * Windows, platformPrint is a structure * (defined in npapi.h) containing the printer name, port, * etc. */ /***** Insert NPP_Print code here *****\ void* platformPrint = printInfo->print.fullPrint.platformPrint; NPBool printOne = printInfo->print.fullPrint.printOne; \**************************************/ /* Do the default*/ printInfo->print.fullPrint.pluginPrinted = false; } else { /* If not fullscreen, we must be embedded */ /* * PLUGIN DEVELOPERS: * If your plugin is embedded, or is full-screen * but you returned false in pluginPrinted above, NPP_Print * will be called with mode == NP_EMBED. The NPWindow * in the printInfo gives the location and dimensions of * the embedded plugin on the printed page. On the * Macintosh, platformPrint is the printer port; on * Windows, platformPrint is the handle to the printing * device context. */ /***** Insert NPP_Print code here *****\ NPWindow* printWindow = &(printInfo->print.embedPrint.window); void* platformPrint = printInfo->print.embedPrint.platformPrint; \**************************************/ } } }
Use more generic VlcPluginBase when possible in vlcshell.cpp
Use more generic VlcPluginBase when possible in vlcshell.cpp Signed-off-by: Jean-Baptiste Kempf <[email protected]>
C++
lgpl-2.1
chengsun/gtk-npapi-vlc,chengsun/gtk-npapi-vlc,jamesbates/npapi-vlc,jamesbates/npapi-vlc,chengsun/gtk-npapi-vlc,jamesbates/npapi-vlc
b0fa11ca41d85e35d3c1155c6a3af1b67788fce6
lib/CodeGen/LiveInterval.cpp
lib/CodeGen/LiveInterval.cpp
//===-- LiveInterval.cpp - Live Interval Representation -------------------===// // // 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 file implements the LiveRange and LiveInterval classes. Given some // numbering of each the machine instructions an interval [i, j) is said to be a // live interval for register v if there is no instruction with number j' > j // such that v is live at j' abd there is no instruction with number i' < i such // that v is live at i'. In this implementation intervals can have holes, // i.e. an interval might look like [1,20), [50,65), [1000,1001). Each // individual range is represented as an instance of LiveRange, and the whole // interval is represented as an instance of LiveInterval. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/LiveInterval.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Target/MRegisterInfo.h" #include <algorithm> #include <iostream> #include <map> using namespace llvm; // An example for liveAt(): // // this = [1,4), liveAt(0) will return false. The instruction defining this // spans slots [0,3]. The interval belongs to an spilled definition of the // variable it represents. This is because slot 1 is used (def slot) and spans // up to slot 3 (store slot). // bool LiveInterval::liveAt(unsigned I) const { Ranges::const_iterator r = std::upper_bound(ranges.begin(), ranges.end(), I); if (r == ranges.begin()) return false; --r; return r->contains(I); } // overlaps - Return true if the intersection of the two live intervals is // not empty. // // An example for overlaps(): // // 0: A = ... // 4: B = ... // 8: C = A + B ;; last use of A // // The live intervals should look like: // // A = [3, 11) // B = [7, x) // C = [11, y) // // A->overlaps(C) should return false since we want to be able to join // A and C. // bool LiveInterval::overlapsFrom(const LiveInterval& other, const_iterator StartPos) const { const_iterator i = begin(); const_iterator ie = end(); const_iterator j = StartPos; const_iterator je = other.end(); assert((StartPos->start <= i->start || StartPos == other.begin()) && StartPos != other.end() && "Bogus start position hint!"); if (i->start < j->start) { i = std::upper_bound(i, ie, j->start); if (i != ranges.begin()) --i; } else if (j->start < i->start) { ++StartPos; if (StartPos != other.end() && StartPos->start <= i->start) { assert(StartPos < other.end() && i < end()); j = std::upper_bound(j, je, i->start); if (j != other.ranges.begin()) --j; } } else { return true; } if (j == je) return false; while (i != ie) { if (i->start > j->start) { std::swap(i, j); std::swap(ie, je); } if (i->end > j->start) return true; ++i; } return false; } /// NontrivialOverlap - Check to see if the two live ranges specified by i and j /// overlap. If so, check to see if they have value numbers that are not /// iIdx/jIdx respectively. If both conditions are true, return true. static inline bool NontrivialOverlap(LiveInterval::Ranges::const_iterator i, LiveInterval::Ranges::const_iterator j, unsigned iIdx, unsigned jIdx) { if (i->start == j->start) { // If this is not the allowed value merge, we cannot join. if (i->ValId != iIdx || j->ValId != jIdx) return true; } else if (i->start < j->start) { if (i->end > j->start && i->ValId != iIdx || j->ValId != jIdx) { return true; } } else { if (j->end > i->start && i->ValId != iIdx || j->ValId != jIdx) return true; } return false; } /// joinable - Two intervals are joinable if the either don't overlap at all /// or if the destination of the copy is a single assignment value, and it /// only overlaps with one value in the source interval. bool LiveInterval::joinable(const LiveInterval &other, unsigned CopyIdx) const { const LiveRange *SourceLR = other.getLiveRangeContaining(CopyIdx-1); const LiveRange *DestLR = getLiveRangeContaining(CopyIdx); assert(SourceLR && DestLR && "Not joining due to a copy?"); unsigned OtherValIdx = SourceLR->ValId; unsigned ThisValIdx = DestLR->ValId; Ranges::const_iterator i = ranges.begin(); Ranges::const_iterator ie = ranges.end(); Ranges::const_iterator j = other.ranges.begin(); Ranges::const_iterator je = other.ranges.end(); if (i->start < j->start) { i = std::upper_bound(i, ie, j->start); if (i != ranges.begin()) --i; } else if (j->start < i->start) { j = std::upper_bound(j, je, i->start); if (j != other.ranges.begin()) --j; } while (i != ie && j != je) { if (NontrivialOverlap(i, j, ThisValIdx, OtherValIdx)) return false; if (i->end < j->end) ++i; else ++j; } return true; } /// extendIntervalEndTo - This method is used when we want to extend the range /// specified by I to end at the specified endpoint. To do this, we should /// merge and eliminate all ranges that this will overlap with. The iterator is /// not invalidated. void LiveInterval::extendIntervalEndTo(Ranges::iterator I, unsigned NewEnd) { assert(I != ranges.end() && "Not a valid interval!"); unsigned ValId = I->ValId; // Search for the first interval that we can't merge with. Ranges::iterator MergeTo = next(I); for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) { assert(MergeTo->ValId == ValId && "Cannot merge with differing values!"); } // If NewEnd was in the middle of an interval, make sure to get its endpoint. I->end = std::max(NewEnd, prior(MergeTo)->end); // Erase any dead ranges ranges.erase(next(I), MergeTo); } /// extendIntervalStartTo - This method is used when we want to extend the range /// specified by I to start at the specified endpoint. To do this, we should /// merge and eliminate all ranges that this will overlap with. LiveInterval::Ranges::iterator LiveInterval::extendIntervalStartTo(Ranges::iterator I, unsigned NewStart) { assert(I != ranges.end() && "Not a valid interval!"); unsigned ValId = I->ValId; // Search for the first interval that we can't merge with. Ranges::iterator MergeTo = I; do { if (MergeTo == ranges.begin()) { I->start = NewStart; ranges.erase(MergeTo, I); return I; } assert(MergeTo->ValId == ValId && "Cannot merge with differing values!"); --MergeTo; } while (NewStart <= MergeTo->start); // If we start in the middle of another interval, just delete a range and // extend that interval. if (MergeTo->end >= NewStart && MergeTo->ValId == ValId) { MergeTo->end = I->end; } else { // Otherwise, extend the interval right after. ++MergeTo; MergeTo->start = NewStart; MergeTo->end = I->end; } ranges.erase(next(MergeTo), next(I)); return MergeTo; } LiveInterval::Ranges::iterator LiveInterval::addRangeFrom(LiveRange LR, Ranges::iterator From) { unsigned Start = LR.start, End = LR.end; Ranges::iterator it = std::upper_bound(From, ranges.end(), Start); // If the inserted interval starts in the middle or right at the end of // another interval, just extend that interval to contain the range of LR. if (it != ranges.begin()) { Ranges::iterator B = prior(it); if (LR.ValId == B->ValId) { if (B->start <= Start && B->end >= Start) { extendIntervalEndTo(B, End); return B; } } else { // Check to make sure that we are not overlapping two live ranges with // different ValId's. assert(B->end <= Start && "Cannot overlap two LiveRanges with differing ValID's" " (did you def the same reg twice in a MachineInstr?)"); } } // Otherwise, if this range ends in the middle of, or right next to, another // interval, merge it into that interval. if (it != ranges.end()) if (LR.ValId == it->ValId) { if (it->start <= End) { it = extendIntervalStartTo(it, Start); // If LR is a complete superset of an interval, we may need to grow its // endpoint as well. if (End > it->end) extendIntervalEndTo(it, End); return it; } } else { // Check to make sure that we are not overlapping two live ranges with // different ValId's. assert(it->start >= End && "Cannot overlap two LiveRanges with differing ValID's"); } // Otherwise, this is just a new range that doesn't interact with anything. // Insert it. return ranges.insert(it, LR); } /// removeRange - Remove the specified range from this interval. Note that /// the range must already be in this interval in its entirety. void LiveInterval::removeRange(unsigned Start, unsigned End) { // Find the LiveRange containing this span. Ranges::iterator I = std::upper_bound(ranges.begin(), ranges.end(), Start); assert(I != ranges.begin() && "Range is not in interval!"); --I; assert(I->contains(Start) && I->contains(End-1) && "Range is not entirely in interval!"); // If the span we are removing is at the start of the LiveRange, adjust it. if (I->start == Start) { if (I->end == End) ranges.erase(I); // Removed the whole LiveRange. else I->start = End; return; } // Otherwise if the span we are removing is at the end of the LiveRange, // adjust the other way. if (I->end == End) { I->end = Start; return; } // Otherwise, we are splitting the LiveRange into two pieces. unsigned OldEnd = I->end; I->end = Start; // Trim the old interval. // Insert the new one. ranges.insert(next(I), LiveRange(End, OldEnd, I->ValId)); } /// getLiveRangeContaining - Return the live range that contains the /// specified index, or null if there is none. const LiveRange *LiveInterval::getLiveRangeContaining(unsigned Idx) const { Ranges::const_iterator It = std::upper_bound(ranges.begin(),ranges.end(),Idx); if (It != ranges.begin()) { const LiveRange &LR = *prior(It); if (LR.contains(Idx)) return &LR; } return 0; } /// join - Join two live intervals (this, and other) together. This operation /// is the result of a copy instruction in the source program, that occurs at /// index 'CopyIdx' that copies from 'Other' to 'this'. void LiveInterval::join(LiveInterval &Other, unsigned CopyIdx) { const LiveRange *SourceLR = Other.getLiveRangeContaining(CopyIdx-1); const LiveRange *DestLR = getLiveRangeContaining(CopyIdx); assert(SourceLR && DestLR && "Not joining due to a copy?"); unsigned MergedSrcValIdx = SourceLR->ValId; unsigned MergedDstValIdx = DestLR->ValId; // Try to do the least amount of work possible. In particular, if there are // more liverange chunks in the other set than there are in the 'this' set, // swap sets to merge the fewest chunks in possible. if (Other.ranges.size() > ranges.size()) { std::swap(MergedSrcValIdx, MergedDstValIdx); std::swap(ranges, Other.ranges); std::swap(NumValues, Other.NumValues); } // Join the ranges of other into the ranges of this interval. Ranges::iterator InsertPos = ranges.begin(); std::map<unsigned, unsigned> Dst2SrcIdxMap; for (Ranges::iterator I = Other.ranges.begin(), E = Other.ranges.end(); I != E; ++I) { // Map the ValId in the other live range to the current live range. if (I->ValId == MergedSrcValIdx) I->ValId = MergedDstValIdx; else { unsigned &NV = Dst2SrcIdxMap[I->ValId]; if (NV == 0) NV = getNextValue(); I->ValId = NV; } InsertPos = addRangeFrom(*I, InsertPos); } weight += Other.weight; } std::ostream& llvm::operator<<(std::ostream& os, const LiveRange &LR) { return os << '[' << LR.start << ',' << LR.end << ':' << LR.ValId << ")"; } void LiveRange::dump() const { std::cerr << *this << "\n"; } void LiveInterval::print(std::ostream &OS, const MRegisterInfo *MRI) const { if (MRI && MRegisterInfo::isPhysicalRegister(reg)) OS << MRI->getName(reg); else OS << "%reg" << reg; OS << ',' << weight; if (empty()) OS << "EMPTY"; else { OS << " = "; for (LiveInterval::Ranges::const_iterator I = ranges.begin(), E = ranges.end(); I != E; ++I) OS << *I; } } void LiveInterval::dump() const { std::cerr << *this << "\n"; }
//===-- LiveInterval.cpp - Live Interval Representation -------------------===// // // 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 file implements the LiveRange and LiveInterval classes. Given some // numbering of each the machine instructions an interval [i, j) is said to be a // live interval for register v if there is no instruction with number j' > j // such that v is live at j' abd there is no instruction with number i' < i such // that v is live at i'. In this implementation intervals can have holes, // i.e. an interval might look like [1,20), [50,65), [1000,1001). Each // individual range is represented as an instance of LiveRange, and the whole // interval is represented as an instance of LiveInterval. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/LiveInterval.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Target/MRegisterInfo.h" #include <algorithm> #include <iostream> #include <map> using namespace llvm; // An example for liveAt(): // // this = [1,4), liveAt(0) will return false. The instruction defining this // spans slots [0,3]. The interval belongs to an spilled definition of the // variable it represents. This is because slot 1 is used (def slot) and spans // up to slot 3 (store slot). // bool LiveInterval::liveAt(unsigned I) const { Ranges::const_iterator r = std::upper_bound(ranges.begin(), ranges.end(), I); if (r == ranges.begin()) return false; --r; return r->contains(I); } // overlaps - Return true if the intersection of the two live intervals is // not empty. // // An example for overlaps(): // // 0: A = ... // 4: B = ... // 8: C = A + B ;; last use of A // // The live intervals should look like: // // A = [3, 11) // B = [7, x) // C = [11, y) // // A->overlaps(C) should return false since we want to be able to join // A and C. // bool LiveInterval::overlapsFrom(const LiveInterval& other, const_iterator StartPos) const { const_iterator i = begin(); const_iterator ie = end(); const_iterator j = StartPos; const_iterator je = other.end(); assert((StartPos->start <= i->start || StartPos == other.begin()) && StartPos != other.end() && "Bogus start position hint!"); if (i->start < j->start) { i = std::upper_bound(i, ie, j->start); if (i != ranges.begin()) --i; } else if (j->start < i->start) { ++StartPos; if (StartPos != other.end() && StartPos->start <= i->start) { assert(StartPos < other.end() && i < end()); j = std::upper_bound(j, je, i->start); if (j != other.ranges.begin()) --j; } } else { return true; } if (j == je) return false; while (i != ie) { if (i->start > j->start) { std::swap(i, j); std::swap(ie, je); } if (i->end > j->start) return true; ++i; } return false; } /// NontrivialOverlap - Check to see if the two live ranges specified by i and j /// overlap. If so, check to see if they have value numbers that are not /// iIdx/jIdx respectively. If both conditions are true, return true. static inline bool NontrivialOverlap(const LiveRange &I, const LiveRange &J, unsigned iIdx, unsigned jIdx) { if (I.start == J.start) { // If this is not the allowed value merge, we cannot join. if (I.ValId != iIdx || J.ValId != jIdx) return true; } else if (I.start < J.start) { if (I.end > J.start && I.ValId != iIdx || J.ValId != jIdx) { return true; } } else { if (J.end > I.start && I.ValId != iIdx || J.ValId != jIdx) return true; } return false; } /// joinable - Two intervals are joinable if the either don't overlap at all /// or if the destination of the copy is a single assignment value, and it /// only overlaps with one value in the source interval. bool LiveInterval::joinable(const LiveInterval &other, unsigned CopyIdx) const { const LiveRange *SourceLR = other.getLiveRangeContaining(CopyIdx-1); const LiveRange *DestLR = getLiveRangeContaining(CopyIdx); assert(SourceLR && DestLR && "Not joining due to a copy?"); unsigned OtherValIdx = SourceLR->ValId; unsigned ThisValIdx = DestLR->ValId; Ranges::const_iterator i = ranges.begin(); Ranges::const_iterator ie = ranges.end(); Ranges::const_iterator j = other.ranges.begin(); Ranges::const_iterator je = other.ranges.end(); if (i->start < j->start) { i = std::upper_bound(i, ie, j->start); if (i != ranges.begin()) --i; } else if (j->start < i->start) { j = std::upper_bound(j, je, i->start); if (j != other.ranges.begin()) --j; } while (i != ie && j != je) { if (NontrivialOverlap(*i, *j, ThisValIdx, OtherValIdx)) return false; if (i->end < j->end) ++i; else ++j; } return true; } /// getOverlapingRanges - Given another live interval which is defined as a /// copy from this one, return a list of all of the live ranges where the /// two overlap and have different value numbers. void LiveInterval::getOverlapingRanges(const LiveInterval &other, unsigned CopyIdx, std::vector<LiveRange*> &Ranges) { const LiveRange *SourceLR = other.getLiveRangeContaining(CopyIdx-1); const LiveRange *DestLR = getLiveRangeContaining(CopyIdx); assert(SourceLR && DestLR && "Not joining due to a copy?"); unsigned OtherValIdx = SourceLR->ValId; unsigned ThisValIdx = DestLR->ValId; Ranges::iterator i = ranges.begin(); Ranges::iterator ie = ranges.end(); Ranges::const_iterator j = other.ranges.begin(); Ranges::const_iterator je = other.ranges.end(); if (i->start < j->start) { i = std::upper_bound(i, ie, j->start); if (i != ranges.begin()) --i; } else if (j->start < i->start) { j = std::upper_bound(j, je, i->start); if (j != other.ranges.begin()) --j; } while (i != ie && j != je) { if (NontrivialOverlap(*i, *j, ThisValIdx, OtherValIdx)) Ranges.push_back(&*i); if (i->end < j->end) ++i; else ++j; } } /// extendIntervalEndTo - This method is used when we want to extend the range /// specified by I to end at the specified endpoint. To do this, we should /// merge and eliminate all ranges that this will overlap with. The iterator is /// not invalidated. void LiveInterval::extendIntervalEndTo(Ranges::iterator I, unsigned NewEnd) { assert(I != ranges.end() && "Not a valid interval!"); unsigned ValId = I->ValId; // Search for the first interval that we can't merge with. Ranges::iterator MergeTo = next(I); for (; MergeTo != ranges.end() && NewEnd >= MergeTo->end; ++MergeTo) { assert(MergeTo->ValId == ValId && "Cannot merge with differing values!"); } // If NewEnd was in the middle of an interval, make sure to get its endpoint. I->end = std::max(NewEnd, prior(MergeTo)->end); // Erase any dead ranges. ranges.erase(next(I), MergeTo); // If the newly formed range now touches the range after it and if they have // the same value number, merge the two ranges into one range. if (I != ranges.end()) { Ranges::iterator Next = next(I); if (Next->start == I->end && Next->ValId == ValId) { I->end = Next->end; ranges.erase(Next); } } } /// extendIntervalStartTo - This method is used when we want to extend the range /// specified by I to start at the specified endpoint. To do this, we should /// merge and eliminate all ranges that this will overlap with. LiveInterval::Ranges::iterator LiveInterval::extendIntervalStartTo(Ranges::iterator I, unsigned NewStart) { assert(I != ranges.end() && "Not a valid interval!"); unsigned ValId = I->ValId; // Search for the first interval that we can't merge with. Ranges::iterator MergeTo = I; do { if (MergeTo == ranges.begin()) { I->start = NewStart; ranges.erase(MergeTo, I); return I; } assert(MergeTo->ValId == ValId && "Cannot merge with differing values!"); --MergeTo; } while (NewStart <= MergeTo->start); // If we start in the middle of another interval, just delete a range and // extend that interval. if (MergeTo->end >= NewStart && MergeTo->ValId == ValId) { MergeTo->end = I->end; } else { // Otherwise, extend the interval right after. ++MergeTo; MergeTo->start = NewStart; MergeTo->end = I->end; } ranges.erase(next(MergeTo), next(I)); return MergeTo; } LiveInterval::Ranges::iterator LiveInterval::addRangeFrom(LiveRange LR, Ranges::iterator From) { unsigned Start = LR.start, End = LR.end; Ranges::iterator it = std::upper_bound(From, ranges.end(), Start); // If the inserted interval starts in the middle or right at the end of // another interval, just extend that interval to contain the range of LR. if (it != ranges.begin()) { Ranges::iterator B = prior(it); if (LR.ValId == B->ValId) { if (B->start <= Start && B->end >= Start) { extendIntervalEndTo(B, End); return B; } } else { // Check to make sure that we are not overlapping two live ranges with // different ValId's. assert(B->end <= Start && "Cannot overlap two LiveRanges with differing ValID's" " (did you def the same reg twice in a MachineInstr?)"); } } // Otherwise, if this range ends in the middle of, or right next to, another // interval, merge it into that interval. if (it != ranges.end()) if (LR.ValId == it->ValId) { if (it->start <= End) { it = extendIntervalStartTo(it, Start); // If LR is a complete superset of an interval, we may need to grow its // endpoint as well. if (End > it->end) extendIntervalEndTo(it, End); return it; } } else { // Check to make sure that we are not overlapping two live ranges with // different ValId's. assert(it->start >= End && "Cannot overlap two LiveRanges with differing ValID's"); } // Otherwise, this is just a new range that doesn't interact with anything. // Insert it. return ranges.insert(it, LR); } /// removeRange - Remove the specified range from this interval. Note that /// the range must already be in this interval in its entirety. void LiveInterval::removeRange(unsigned Start, unsigned End) { // Find the LiveRange containing this span. Ranges::iterator I = std::upper_bound(ranges.begin(), ranges.end(), Start); assert(I != ranges.begin() && "Range is not in interval!"); --I; assert(I->contains(Start) && I->contains(End-1) && "Range is not entirely in interval!"); // If the span we are removing is at the start of the LiveRange, adjust it. if (I->start == Start) { if (I->end == End) ranges.erase(I); // Removed the whole LiveRange. else I->start = End; return; } // Otherwise if the span we are removing is at the end of the LiveRange, // adjust the other way. if (I->end == End) { I->end = Start; return; } // Otherwise, we are splitting the LiveRange into two pieces. unsigned OldEnd = I->end; I->end = Start; // Trim the old interval. // Insert the new one. ranges.insert(next(I), LiveRange(End, OldEnd, I->ValId)); } /// getLiveRangeContaining - Return the live range that contains the /// specified index, or null if there is none. const LiveRange *LiveInterval::getLiveRangeContaining(unsigned Idx) const { Ranges::const_iterator It = std::upper_bound(ranges.begin(),ranges.end(),Idx); if (It != ranges.begin()) { const LiveRange &LR = *prior(It); if (LR.contains(Idx)) return &LR; } return 0; } /// join - Join two live intervals (this, and other) together. This operation /// is the result of a copy instruction in the source program, that occurs at /// index 'CopyIdx' that copies from 'Other' to 'this'. void LiveInterval::join(LiveInterval &Other, unsigned CopyIdx) { const LiveRange *SourceLR = Other.getLiveRangeContaining(CopyIdx-1); const LiveRange *DestLR = getLiveRangeContaining(CopyIdx); assert(SourceLR && DestLR && "Not joining due to a copy?"); unsigned MergedSrcValIdx = SourceLR->ValId; unsigned MergedDstValIdx = DestLR->ValId; // Try to do the least amount of work possible. In particular, if there are // more liverange chunks in the other set than there are in the 'this' set, // swap sets to merge the fewest chunks in possible. if (Other.ranges.size() > ranges.size()) { std::swap(MergedSrcValIdx, MergedDstValIdx); std::swap(ranges, Other.ranges); std::swap(NumValues, Other.NumValues); } // Join the ranges of other into the ranges of this interval. Ranges::iterator InsertPos = ranges.begin(); std::map<unsigned, unsigned> Dst2SrcIdxMap; for (Ranges::iterator I = Other.ranges.begin(), E = Other.ranges.end(); I != E; ++I) { // Map the ValId in the other live range to the current live range. if (I->ValId == MergedSrcValIdx) I->ValId = MergedDstValIdx; else { unsigned &NV = Dst2SrcIdxMap[I->ValId]; if (NV == 0) NV = getNextValue(); I->ValId = NV; } InsertPos = addRangeFrom(*I, InsertPos); } weight += Other.weight; } std::ostream& llvm::operator<<(std::ostream& os, const LiveRange &LR) { return os << '[' << LR.start << ',' << LR.end << ':' << LR.ValId << ")"; } void LiveRange::dump() const { std::cerr << *this << "\n"; } void LiveInterval::print(std::ostream &OS, const MRegisterInfo *MRI) const { if (MRI && MRegisterInfo::isPhysicalRegister(reg)) OS << MRI->getName(reg); else OS << "%reg" << reg; OS << ',' << weight; if (empty()) OS << "EMPTY"; else { OS << " = "; for (LiveInterval::Ranges::const_iterator I = ranges.begin(), E = ranges.end(); I != E; ++I) OS << *I; } } void LiveInterval::dump() const { std::cerr << *this << "\n"; }
add a new method, play around with some code.
add a new method, play around with some code. Fix a *bug* in the extendIntervalEndTo method. In particular, if adding [2:10) to an interval containing [0:2),[10:30), we produced [0:10),[10,30). Which is not the most smart thing to do. Now produce [0:30). git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@23841 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-2-clause
dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap
53b0a2d8c6e00fcd602afcaaeb3efab69e672f27
lib/IR/PassManager.cpp
lib/IR/PassManager.cpp
//===- PassManager.cpp - Infrastructure for managing & running IR passes --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/PassManager.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" using namespace llvm; static cl::opt<bool> DebugPM("debug-pass-manager", cl::Hidden, cl::desc("Print pass management debugging information")); PreservedAnalyses ModulePassManager::run(Module *M, ModuleAnalysisManager *AM) { PreservedAnalyses PA = PreservedAnalyses::all(); if (DebugPM) dbgs() << "Starting module pass manager run.\n"; for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) { if (DebugPM) dbgs() << "Running module pass: " << Passes[Idx]->name() << "\n"; PreservedAnalyses PassPA = Passes[Idx]->run(M, AM); if (AM) AM->invalidate(M, PassPA); PA.intersect(std::move(PassPA)); M->getContext().yield(); } if (DebugPM) dbgs() << "Finished module pass manager run.\n"; return PA; } ModuleAnalysisManager::ResultConceptT & ModuleAnalysisManager::getResultImpl(void *PassID, Module *M) { ModuleAnalysisResultMapT::iterator RI; bool Inserted; std::tie(RI, Inserted) = ModuleAnalysisResults.insert(std::make_pair( PassID, std::unique_ptr<detail::AnalysisResultConcept<Module *>>())); // If we don't have a cached result for this module, look up the pass and run // it to produce a result, which we then add to the cache. if (Inserted) RI->second = std::move(lookupPass(PassID).run(M, this)); return *RI->second; } ModuleAnalysisManager::ResultConceptT * ModuleAnalysisManager::getCachedResultImpl(void *PassID, Module *M) const { ModuleAnalysisResultMapT::const_iterator RI = ModuleAnalysisResults.find(PassID); return RI == ModuleAnalysisResults.end() ? nullptr : &*RI->second; } void ModuleAnalysisManager::invalidateImpl(void *PassID, Module *M) { ModuleAnalysisResults.erase(PassID); } void ModuleAnalysisManager::invalidateImpl(Module *M, const PreservedAnalyses &PA) { // FIXME: This is a total hack based on the fact that erasure doesn't // invalidate iteration for DenseMap. for (ModuleAnalysisResultMapT::iterator I = ModuleAnalysisResults.begin(), E = ModuleAnalysisResults.end(); I != E; ++I) if (I->second->invalidate(M, PA)) ModuleAnalysisResults.erase(I); } PreservedAnalyses FunctionPassManager::run(Function *F, FunctionAnalysisManager *AM) { PreservedAnalyses PA = PreservedAnalyses::all(); if (DebugPM) dbgs() << "Starting function pass manager run.\n"; for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) { if (DebugPM) dbgs() << "Running function pass: " << Passes[Idx]->name() << "\n"; PreservedAnalyses PassPA = Passes[Idx]->run(F, AM); if (AM) AM->invalidate(F, PassPA); PA.intersect(std::move(PassPA)); F->getContext().yield(); } if (DebugPM) dbgs() << "Finished function pass manager run.\n"; return PA; } bool FunctionAnalysisManager::empty() const { assert(FunctionAnalysisResults.empty() == FunctionAnalysisResultLists.empty() && "The storage and index of analysis results disagree on how many there " "are!"); return FunctionAnalysisResults.empty(); } void FunctionAnalysisManager::clear() { FunctionAnalysisResults.clear(); FunctionAnalysisResultLists.clear(); } FunctionAnalysisManager::ResultConceptT & FunctionAnalysisManager::getResultImpl(void *PassID, Function *F) { FunctionAnalysisResultMapT::iterator RI; bool Inserted; std::tie(RI, Inserted) = FunctionAnalysisResults.insert(std::make_pair( std::make_pair(PassID, F), FunctionAnalysisResultListT::iterator())); // If we don't have a cached result for this function, look up the pass and // run it to produce a result, which we then add to the cache. if (Inserted) { FunctionAnalysisResultListT &ResultList = FunctionAnalysisResultLists[F]; ResultList.emplace_back(PassID, lookupPass(PassID).run(F, this)); RI->second = std::prev(ResultList.end()); } return *RI->second->second; } FunctionAnalysisManager::ResultConceptT * FunctionAnalysisManager::getCachedResultImpl(void *PassID, Function *F) const { FunctionAnalysisResultMapT::const_iterator RI = FunctionAnalysisResults.find(std::make_pair(PassID, F)); return RI == FunctionAnalysisResults.end() ? nullptr : &*RI->second->second; } void FunctionAnalysisManager::invalidateImpl(void *PassID, Function *F) { FunctionAnalysisResultMapT::iterator RI = FunctionAnalysisResults.find(std::make_pair(PassID, F)); if (RI == FunctionAnalysisResults.end()) return; FunctionAnalysisResultLists[F].erase(RI->second); } void FunctionAnalysisManager::invalidateImpl(Function *F, const PreservedAnalyses &PA) { // Clear all the invalidated results associated specifically with this // function. SmallVector<void *, 8> InvalidatedPassIDs; FunctionAnalysisResultListT &ResultsList = FunctionAnalysisResultLists[F]; for (FunctionAnalysisResultListT::iterator I = ResultsList.begin(), E = ResultsList.end(); I != E;) if (I->second->invalidate(F, PA)) { InvalidatedPassIDs.push_back(I->first); I = ResultsList.erase(I); } else { ++I; } while (!InvalidatedPassIDs.empty()) FunctionAnalysisResults.erase( std::make_pair(InvalidatedPassIDs.pop_back_val(), F)); if (ResultsList.empty()) FunctionAnalysisResultLists.erase(F); } char FunctionAnalysisManagerModuleProxy::PassID; FunctionAnalysisManagerModuleProxy::Result FunctionAnalysisManagerModuleProxy::run(Module *M) { assert(FAM->empty() && "Function analyses ran prior to the module proxy!"); return Result(*FAM); } FunctionAnalysisManagerModuleProxy::Result::~Result() { // Clear out the analysis manager if we're being destroyed -- it means we // didn't even see an invalidate call when we got invalidated. FAM->clear(); } bool FunctionAnalysisManagerModuleProxy::Result::invalidate( Module *M, const PreservedAnalyses &PA) { // If this proxy isn't marked as preserved, then we can't even invalidate // individual function analyses, there may be an invalid set of Function // objects in the cache making it impossible to incrementally preserve them. // Just clear the entire manager. if (!PA.preserved(ID())) FAM->clear(); // Return false to indicate that this result is still a valid proxy. return false; } char ModuleAnalysisManagerFunctionProxy::PassID;
//===- PassManager.cpp - Infrastructure for managing & running IR passes --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/PassManager.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" using namespace llvm; static cl::opt<bool> DebugPM("debug-pass-manager", cl::Hidden, cl::desc("Print pass management debugging information")); PreservedAnalyses ModulePassManager::run(Module *M, ModuleAnalysisManager *AM) { PreservedAnalyses PA = PreservedAnalyses::all(); if (DebugPM) dbgs() << "Starting module pass manager run.\n"; for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) { if (DebugPM) dbgs() << "Running module pass: " << Passes[Idx]->name() << "\n"; PreservedAnalyses PassPA = Passes[Idx]->run(M, AM); if (AM) AM->invalidate(M, PassPA); PA.intersect(std::move(PassPA)); M->getContext().yield(); } if (DebugPM) dbgs() << "Finished module pass manager run.\n"; return PA; } ModuleAnalysisManager::ResultConceptT & ModuleAnalysisManager::getResultImpl(void *PassID, Module *M) { ModuleAnalysisResultMapT::iterator RI; bool Inserted; std::tie(RI, Inserted) = ModuleAnalysisResults.insert(std::make_pair( PassID, std::unique_ptr<detail::AnalysisResultConcept<Module *>>())); // If we don't have a cached result for this module, look up the pass and run // it to produce a result, which we then add to the cache. if (Inserted) RI->second = lookupPass(PassID).run(M, this); return *RI->second; } ModuleAnalysisManager::ResultConceptT * ModuleAnalysisManager::getCachedResultImpl(void *PassID, Module *M) const { ModuleAnalysisResultMapT::const_iterator RI = ModuleAnalysisResults.find(PassID); return RI == ModuleAnalysisResults.end() ? nullptr : &*RI->second; } void ModuleAnalysisManager::invalidateImpl(void *PassID, Module *M) { ModuleAnalysisResults.erase(PassID); } void ModuleAnalysisManager::invalidateImpl(Module *M, const PreservedAnalyses &PA) { // FIXME: This is a total hack based on the fact that erasure doesn't // invalidate iteration for DenseMap. for (ModuleAnalysisResultMapT::iterator I = ModuleAnalysisResults.begin(), E = ModuleAnalysisResults.end(); I != E; ++I) if (I->second->invalidate(M, PA)) ModuleAnalysisResults.erase(I); } PreservedAnalyses FunctionPassManager::run(Function *F, FunctionAnalysisManager *AM) { PreservedAnalyses PA = PreservedAnalyses::all(); if (DebugPM) dbgs() << "Starting function pass manager run.\n"; for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) { if (DebugPM) dbgs() << "Running function pass: " << Passes[Idx]->name() << "\n"; PreservedAnalyses PassPA = Passes[Idx]->run(F, AM); if (AM) AM->invalidate(F, PassPA); PA.intersect(std::move(PassPA)); F->getContext().yield(); } if (DebugPM) dbgs() << "Finished function pass manager run.\n"; return PA; } bool FunctionAnalysisManager::empty() const { assert(FunctionAnalysisResults.empty() == FunctionAnalysisResultLists.empty() && "The storage and index of analysis results disagree on how many there " "are!"); return FunctionAnalysisResults.empty(); } void FunctionAnalysisManager::clear() { FunctionAnalysisResults.clear(); FunctionAnalysisResultLists.clear(); } FunctionAnalysisManager::ResultConceptT & FunctionAnalysisManager::getResultImpl(void *PassID, Function *F) { FunctionAnalysisResultMapT::iterator RI; bool Inserted; std::tie(RI, Inserted) = FunctionAnalysisResults.insert(std::make_pair( std::make_pair(PassID, F), FunctionAnalysisResultListT::iterator())); // If we don't have a cached result for this function, look up the pass and // run it to produce a result, which we then add to the cache. if (Inserted) { FunctionAnalysisResultListT &ResultList = FunctionAnalysisResultLists[F]; ResultList.emplace_back(PassID, lookupPass(PassID).run(F, this)); RI->second = std::prev(ResultList.end()); } return *RI->second->second; } FunctionAnalysisManager::ResultConceptT * FunctionAnalysisManager::getCachedResultImpl(void *PassID, Function *F) const { FunctionAnalysisResultMapT::const_iterator RI = FunctionAnalysisResults.find(std::make_pair(PassID, F)); return RI == FunctionAnalysisResults.end() ? nullptr : &*RI->second->second; } void FunctionAnalysisManager::invalidateImpl(void *PassID, Function *F) { FunctionAnalysisResultMapT::iterator RI = FunctionAnalysisResults.find(std::make_pair(PassID, F)); if (RI == FunctionAnalysisResults.end()) return; FunctionAnalysisResultLists[F].erase(RI->second); } void FunctionAnalysisManager::invalidateImpl(Function *F, const PreservedAnalyses &PA) { // Clear all the invalidated results associated specifically with this // function. SmallVector<void *, 8> InvalidatedPassIDs; FunctionAnalysisResultListT &ResultsList = FunctionAnalysisResultLists[F]; for (FunctionAnalysisResultListT::iterator I = ResultsList.begin(), E = ResultsList.end(); I != E;) if (I->second->invalidate(F, PA)) { InvalidatedPassIDs.push_back(I->first); I = ResultsList.erase(I); } else { ++I; } while (!InvalidatedPassIDs.empty()) FunctionAnalysisResults.erase( std::make_pair(InvalidatedPassIDs.pop_back_val(), F)); if (ResultsList.empty()) FunctionAnalysisResultLists.erase(F); } char FunctionAnalysisManagerModuleProxy::PassID; FunctionAnalysisManagerModuleProxy::Result FunctionAnalysisManagerModuleProxy::run(Module *M) { assert(FAM->empty() && "Function analyses ran prior to the module proxy!"); return Result(*FAM); } FunctionAnalysisManagerModuleProxy::Result::~Result() { // Clear out the analysis manager if we're being destroyed -- it means we // didn't even see an invalidate call when we got invalidated. FAM->clear(); } bool FunctionAnalysisManagerModuleProxy::Result::invalidate( Module *M, const PreservedAnalyses &PA) { // If this proxy isn't marked as preserved, then we can't even invalidate // individual function analyses, there may be an invalid set of Function // objects in the cache making it impossible to incrementally preserve them. // Just clear the entire manager. if (!PA.preserved(ID())) FAM->clear(); // Return false to indicate that this result is still a valid proxy. return false; } char ModuleAnalysisManagerFunctionProxy::PassID;
Remove unnecessary/redundant std::move
Remove unnecessary/redundant std::move (run returns unique_ptr by value already) git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@213174 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm
13c3208403159c5e41342bff9b4685cbc4703dd2
lib/Support/CachePruning.cpp
lib/Support/CachePruning.cpp
//===-CachePruning.cpp - LLVM Cache Directory Pruning ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the pruning of a directory based on least recently used. // //===----------------------------------------------------------------------===// #include "llvm/Support/CachePruning.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Errc.h" #include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #define DEBUG_TYPE "cache-pruning" #include <set> #include <system_error> using namespace llvm; /// Write a new timestamp file with the given path. This is used for the pruning /// interval option. static void writeTimestampFile(StringRef TimestampFile) { std::error_code EC; raw_fd_ostream Out(TimestampFile.str(), EC, sys::fs::F_None); } static Expected<std::chrono::seconds> parseDuration(StringRef Duration) { if (Duration.empty()) return make_error<StringError>("Duration must not be empty", inconvertibleErrorCode()); StringRef NumStr = Duration.slice(0, Duration.size()-1); uint64_t Num; if (NumStr.getAsInteger(0, Num)) return make_error<StringError>("'" + NumStr + "' not an integer", inconvertibleErrorCode()); switch (Duration.back()) { case 's': return std::chrono::seconds(Num); case 'm': return std::chrono::minutes(Num); case 'h': return std::chrono::hours(Num); default: return make_error<StringError>("'" + Duration + "' must end with one of 's', 'm' or 'h'", inconvertibleErrorCode()); } } Expected<CachePruningPolicy> llvm::parseCachePruningPolicy(StringRef PolicyStr) { CachePruningPolicy Policy; std::pair<StringRef, StringRef> P = {"", PolicyStr}; while (!P.second.empty()) { P = P.second.split(':'); StringRef Key, Value; std::tie(Key, Value) = P.first.split('='); if (Key == "prune_interval") { auto DurationOrErr = parseDuration(Value); if (!DurationOrErr) return std::move(DurationOrErr.takeError()); Policy.Interval = *DurationOrErr; } else if (Key == "prune_after") { auto DurationOrErr = parseDuration(Value); if (!DurationOrErr) return std::move(DurationOrErr.takeError()); Policy.Expiration = *DurationOrErr; } else if (Key == "cache_size") { if (Value.back() != '%') return make_error<StringError>("'" + Value + "' must be a percentage", inconvertibleErrorCode()); StringRef SizeStr = Value.slice(0, Value.size() - 1); uint64_t Size; if (SizeStr.getAsInteger(0, Size)) return make_error<StringError>("'" + SizeStr + "' not an integer", inconvertibleErrorCode()); if (Size > 100) return make_error<StringError>("'" + SizeStr + "' must be between 0 and 100", inconvertibleErrorCode()); Policy.PercentageOfAvailableSpace = Size; } else { return make_error<StringError>("Unknown key: '" + Key + "'", inconvertibleErrorCode()); } } return Policy; } /// Prune the cache of files that haven't been accessed in a long time. bool llvm::pruneCache(StringRef Path, CachePruningPolicy Policy) { using namespace std::chrono; if (Path.empty()) return false; bool isPathDir; if (sys::fs::is_directory(Path, isPathDir)) return false; if (!isPathDir) return false; Policy.PercentageOfAvailableSpace = std::min(Policy.PercentageOfAvailableSpace, 100u); if (Policy.Expiration == seconds(0) && Policy.PercentageOfAvailableSpace == 0) { DEBUG(dbgs() << "No pruning settings set, exit early\n"); // Nothing will be pruned, early exit return false; } // Try to stat() the timestamp file. SmallString<128> TimestampFile(Path); sys::path::append(TimestampFile, "llvmcache.timestamp"); sys::fs::file_status FileStatus; const auto CurrentTime = system_clock::now(); if (auto EC = sys::fs::status(TimestampFile, FileStatus)) { if (EC == errc::no_such_file_or_directory) { // If the timestamp file wasn't there, create one now. writeTimestampFile(TimestampFile); } else { // Unknown error? return false; } } else { if (Policy.Interval == seconds(0)) { // Check whether the time stamp is older than our pruning interval. // If not, do nothing. const auto TimeStampModTime = FileStatus.getLastModificationTime(); auto TimeStampAge = CurrentTime - TimeStampModTime; if (TimeStampAge <= Policy.Interval) { DEBUG(dbgs() << "Timestamp file too recent (" << duration_cast<seconds>(TimeStampAge).count() << "s old), do not prune.\n"); return false; } } // Write a new timestamp file so that nobody else attempts to prune. // There is a benign race condition here, if two processes happen to // notice at the same time that the timestamp is out-of-date. writeTimestampFile(TimestampFile); } bool ShouldComputeSize = (Policy.PercentageOfAvailableSpace > 0); // Keep track of space std::set<std::pair<uint64_t, std::string>> FileSizes; uint64_t TotalSize = 0; // Helper to add a path to the set of files to consider for size-based // pruning, sorted by size. auto AddToFileListForSizePruning = [&](StringRef Path) { if (!ShouldComputeSize) return; TotalSize += FileStatus.getSize(); FileSizes.insert( std::make_pair(FileStatus.getSize(), std::string(Path))); }; // Walk the entire directory cache, looking for unused files. std::error_code EC; SmallString<128> CachePathNative; sys::path::native(Path, CachePathNative); // Walk all of the files within this directory. for (sys::fs::directory_iterator File(CachePathNative, EC), FileEnd; File != FileEnd && !EC; File.increment(EC)) { // Do not touch the timestamp. if (File->path() == TimestampFile) continue; // Look at this file. If we can't stat it, there's nothing interesting // there. if (sys::fs::status(File->path(), FileStatus)) { DEBUG(dbgs() << "Ignore " << File->path() << " (can't stat)\n"); continue; } // If the file hasn't been used recently enough, delete it const auto FileAccessTime = FileStatus.getLastAccessedTime(); auto FileAge = CurrentTime - FileAccessTime; if (FileAge > Policy.Expiration) { DEBUG(dbgs() << "Remove " << File->path() << " (" << duration_cast<seconds>(FileAge).count() << "s old)\n"); sys::fs::remove(File->path()); continue; } // Leave it here for now, but add it to the list of size-based pruning. AddToFileListForSizePruning(File->path()); } // Prune for size now if needed if (ShouldComputeSize) { auto ErrOrSpaceInfo = sys::fs::disk_space(Path); if (!ErrOrSpaceInfo) { report_fatal_error("Can't get available size"); } sys::fs::space_info SpaceInfo = ErrOrSpaceInfo.get(); auto AvailableSpace = TotalSize + SpaceInfo.free; auto FileAndSize = FileSizes.rbegin(); DEBUG(dbgs() << "Occupancy: " << ((100 * TotalSize) / AvailableSpace) << "% target is: " << Policy.PercentageOfAvailableSpace << "\n"); // Remove the oldest accessed files first, till we get below the threshold while (((100 * TotalSize) / AvailableSpace) > Policy.PercentageOfAvailableSpace && FileAndSize != FileSizes.rend()) { // Remove the file. sys::fs::remove(FileAndSize->second); // Update size TotalSize -= FileAndSize->first; DEBUG(dbgs() << " - Remove " << FileAndSize->second << " (size " << FileAndSize->first << "), new occupancy is " << TotalSize << "%\n"); ++FileAndSize; } } return true; }
//===-CachePruning.cpp - LLVM Cache Directory Pruning ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the pruning of a directory based on least recently used. // //===----------------------------------------------------------------------===// #include "llvm/Support/CachePruning.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Errc.h" #include "llvm/Support/Error.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #define DEBUG_TYPE "cache-pruning" #include <set> #include <system_error> using namespace llvm; /// Write a new timestamp file with the given path. This is used for the pruning /// interval option. static void writeTimestampFile(StringRef TimestampFile) { std::error_code EC; raw_fd_ostream Out(TimestampFile.str(), EC, sys::fs::F_None); } static Expected<std::chrono::seconds> parseDuration(StringRef Duration) { if (Duration.empty()) return make_error<StringError>("Duration must not be empty", inconvertibleErrorCode()); StringRef NumStr = Duration.slice(0, Duration.size()-1); uint64_t Num; if (NumStr.getAsInteger(0, Num)) return make_error<StringError>("'" + NumStr + "' not an integer", inconvertibleErrorCode()); switch (Duration.back()) { case 's': return std::chrono::seconds(Num); case 'm': return std::chrono::minutes(Num); case 'h': return std::chrono::hours(Num); default: return make_error<StringError>("'" + Duration + "' must end with one of 's', 'm' or 'h'", inconvertibleErrorCode()); } } Expected<CachePruningPolicy> llvm::parseCachePruningPolicy(StringRef PolicyStr) { CachePruningPolicy Policy; std::pair<StringRef, StringRef> P = {"", PolicyStr}; while (!P.second.empty()) { P = P.second.split(':'); StringRef Key, Value; std::tie(Key, Value) = P.first.split('='); if (Key == "prune_interval") { auto DurationOrErr = parseDuration(Value); if (!DurationOrErr) return DurationOrErr.takeError(); Policy.Interval = *DurationOrErr; } else if (Key == "prune_after") { auto DurationOrErr = parseDuration(Value); if (!DurationOrErr) return DurationOrErr.takeError(); Policy.Expiration = *DurationOrErr; } else if (Key == "cache_size") { if (Value.back() != '%') return make_error<StringError>("'" + Value + "' must be a percentage", inconvertibleErrorCode()); StringRef SizeStr = Value.slice(0, Value.size() - 1); uint64_t Size; if (SizeStr.getAsInteger(0, Size)) return make_error<StringError>("'" + SizeStr + "' not an integer", inconvertibleErrorCode()); if (Size > 100) return make_error<StringError>("'" + SizeStr + "' must be between 0 and 100", inconvertibleErrorCode()); Policy.PercentageOfAvailableSpace = Size; } else { return make_error<StringError>("Unknown key: '" + Key + "'", inconvertibleErrorCode()); } } return Policy; } /// Prune the cache of files that haven't been accessed in a long time. bool llvm::pruneCache(StringRef Path, CachePruningPolicy Policy) { using namespace std::chrono; if (Path.empty()) return false; bool isPathDir; if (sys::fs::is_directory(Path, isPathDir)) return false; if (!isPathDir) return false; Policy.PercentageOfAvailableSpace = std::min(Policy.PercentageOfAvailableSpace, 100u); if (Policy.Expiration == seconds(0) && Policy.PercentageOfAvailableSpace == 0) { DEBUG(dbgs() << "No pruning settings set, exit early\n"); // Nothing will be pruned, early exit return false; } // Try to stat() the timestamp file. SmallString<128> TimestampFile(Path); sys::path::append(TimestampFile, "llvmcache.timestamp"); sys::fs::file_status FileStatus; const auto CurrentTime = system_clock::now(); if (auto EC = sys::fs::status(TimestampFile, FileStatus)) { if (EC == errc::no_such_file_or_directory) { // If the timestamp file wasn't there, create one now. writeTimestampFile(TimestampFile); } else { // Unknown error? return false; } } else { if (Policy.Interval == seconds(0)) { // Check whether the time stamp is older than our pruning interval. // If not, do nothing. const auto TimeStampModTime = FileStatus.getLastModificationTime(); auto TimeStampAge = CurrentTime - TimeStampModTime; if (TimeStampAge <= Policy.Interval) { DEBUG(dbgs() << "Timestamp file too recent (" << duration_cast<seconds>(TimeStampAge).count() << "s old), do not prune.\n"); return false; } } // Write a new timestamp file so that nobody else attempts to prune. // There is a benign race condition here, if two processes happen to // notice at the same time that the timestamp is out-of-date. writeTimestampFile(TimestampFile); } bool ShouldComputeSize = (Policy.PercentageOfAvailableSpace > 0); // Keep track of space std::set<std::pair<uint64_t, std::string>> FileSizes; uint64_t TotalSize = 0; // Helper to add a path to the set of files to consider for size-based // pruning, sorted by size. auto AddToFileListForSizePruning = [&](StringRef Path) { if (!ShouldComputeSize) return; TotalSize += FileStatus.getSize(); FileSizes.insert( std::make_pair(FileStatus.getSize(), std::string(Path))); }; // Walk the entire directory cache, looking for unused files. std::error_code EC; SmallString<128> CachePathNative; sys::path::native(Path, CachePathNative); // Walk all of the files within this directory. for (sys::fs::directory_iterator File(CachePathNative, EC), FileEnd; File != FileEnd && !EC; File.increment(EC)) { // Do not touch the timestamp. if (File->path() == TimestampFile) continue; // Look at this file. If we can't stat it, there's nothing interesting // there. if (sys::fs::status(File->path(), FileStatus)) { DEBUG(dbgs() << "Ignore " << File->path() << " (can't stat)\n"); continue; } // If the file hasn't been used recently enough, delete it const auto FileAccessTime = FileStatus.getLastAccessedTime(); auto FileAge = CurrentTime - FileAccessTime; if (FileAge > Policy.Expiration) { DEBUG(dbgs() << "Remove " << File->path() << " (" << duration_cast<seconds>(FileAge).count() << "s old)\n"); sys::fs::remove(File->path()); continue; } // Leave it here for now, but add it to the list of size-based pruning. AddToFileListForSizePruning(File->path()); } // Prune for size now if needed if (ShouldComputeSize) { auto ErrOrSpaceInfo = sys::fs::disk_space(Path); if (!ErrOrSpaceInfo) { report_fatal_error("Can't get available size"); } sys::fs::space_info SpaceInfo = ErrOrSpaceInfo.get(); auto AvailableSpace = TotalSize + SpaceInfo.free; auto FileAndSize = FileSizes.rbegin(); DEBUG(dbgs() << "Occupancy: " << ((100 * TotalSize) / AvailableSpace) << "% target is: " << Policy.PercentageOfAvailableSpace << "\n"); // Remove the oldest accessed files first, till we get below the threshold while (((100 * TotalSize) / AvailableSpace) > Policy.PercentageOfAvailableSpace && FileAndSize != FileSizes.rend()) { // Remove the file. sys::fs::remove(FileAndSize->second); // Update size TotalSize -= FileAndSize->first; DEBUG(dbgs() << " - Remove " << FileAndSize->second << " (size " << FileAndSize->first << "), new occupancy is " << TotalSize << "%\n"); ++FileAndSize; } } return true; }
Fix pessimising moves.
Fix pessimising moves. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@297928 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm
73c56243758d6ef2f35587cdc7ab0ab11767e47c
lib/Target/TargetMachine.cpp
lib/Target/TargetMachine.cpp
//===-- TargetMachine.cpp - General Target Information ---------------------==// // // 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 file describes the general parts of a Target machine. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetAsmInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Support/CommandLine.h" using namespace llvm; //--------------------------------------------------------------------------- // Command-line options that tend to be useful on more than one back-end. // namespace llvm { bool PrintMachineCode; bool NoFramePointerElim; bool NoExcessFPPrecision; bool UnsafeFPMath; bool FiniteOnlyFPMathOption; bool UseSoftFloat; bool NoZerosInBSS; bool ExceptionHandling; Reloc::Model RelocationModel; CodeModel::Model CMModel; } namespace { cl::opt<bool, true> PrintCode("print-machineinstrs", cl::desc("Print generated machine code"), cl::location(PrintMachineCode), cl::init(false)); cl::opt<bool, true> DisableFPElim("disable-fp-elim", cl::desc("Disable frame pointer elimination optimization"), cl::location(NoFramePointerElim), cl::init(false)); cl::opt<bool, true> DisableExcessPrecision("disable-excess-fp-precision", cl::desc("Disable optimizations that may increase FP precision"), cl::location(NoExcessFPPrecision), cl::init(false)); cl::opt<bool, true> EnableUnsafeFPMath("enable-unsafe-fp-math", cl::desc("Enable optimizations that may decrease FP precision"), cl::location(UnsafeFPMath), cl::init(false)); cl::opt<bool, true> EnableFiniteOnltFPMath("enable-finite-only-fp-math", cl::desc("Enable optimizations that assumes non- NaNs / +-Infs"), cl::location(FiniteOnlyFPMathOption), cl::init(false)); cl::opt<bool, true> GenerateSoftFloatCalls("soft-float", cl::desc("Generate software floating point library calls"), cl::location(UseSoftFloat), cl::init(false)); cl::opt<bool, true> DontPlaceZerosInBSS("nozero-initialized-in-bss", cl::desc("Don't place zero-initialized symbols into bss section"), cl::location(NoZerosInBSS), cl::init(false)); cl::opt<bool, true> EnableExceptionHandling("exception-handling", cl::desc("Exception handling should be emitted."), cl::location(ExceptionHandling), cl::init(false)); cl::opt<llvm::Reloc::Model, true> DefRelocationModel( "relocation-model", cl::desc("Choose relocation model"), cl::location(RelocationModel), cl::init(Reloc::Default), cl::values( clEnumValN(Reloc::Default, "default", " Target default relocation model"), clEnumValN(Reloc::Static, "static", " Non-relocatable code"), clEnumValN(Reloc::PIC_, "pic", " Fully relocatable, position independent code"), clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic", " Relocatable external references, non-relocatable code"), clEnumValEnd)); cl::opt<llvm::CodeModel::Model, true> DefCodeModel( "code-model", cl::desc("Choose relocation model"), cl::location(CMModel), cl::init(CodeModel::Default), cl::values( clEnumValN(CodeModel::Default, "default", " Target default code model"), clEnumValN(CodeModel::Small, "small", " Small code model"), clEnumValN(CodeModel::Kernel, "kernel", " Kernel code model"), clEnumValN(CodeModel::Medium, "medium", " Medium code model"), clEnumValN(CodeModel::Large, "large", " Large code model"), clEnumValEnd)); } //--------------------------------------------------------------------------- // TargetMachine Class // TargetMachine::~TargetMachine() { delete AsmInfo; } /// getRelocationModel - Returns the code generation relocation model. The /// choices are static, PIC, and dynamic-no-pic, and target default. Reloc::Model TargetMachine::getRelocationModel() { return RelocationModel; } /// setRelocationModel - Sets the code generation relocation model. void TargetMachine::setRelocationModel(Reloc::Model Model) { RelocationModel = Model; } /// getCodeModel - Returns the code model. The choices are small, kernel, /// medium, large, and target default. CodeModel::Model TargetMachine::getCodeModel() { return CMModel; } /// setCodeModel - Sets the code model. void TargetMachine::setCodeModel(CodeModel::Model Model) { CMModel = Model; } namespace llvm { /// FiniteOnlyFPMath - This returns true when the -enable-finite-only-fp-math /// option is specified on the command line. If this returns false (default), /// the code generator is not allowed to assume that FP arithmetic arguments /// and results are never NaNs or +-Infs. bool FiniteOnlyFPMath() { return UnsafeFPMath || FiniteOnlyFPMathOption; } }
//===-- TargetMachine.cpp - General Target Information ---------------------==// // // 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 file describes the general parts of a Target machine. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetAsmInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Support/CommandLine.h" using namespace llvm; //--------------------------------------------------------------------------- // Command-line options that tend to be useful on more than one back-end. // namespace llvm { bool PrintMachineCode; bool NoFramePointerElim; bool NoExcessFPPrecision; bool UnsafeFPMath; bool FiniteOnlyFPMathOption; bool UseSoftFloat; bool NoZerosInBSS; bool ExceptionHandling; Reloc::Model RelocationModel; CodeModel::Model CMModel; } namespace { cl::opt<bool, true> PrintCode("print-machineinstrs", cl::desc("Print generated machine code"), cl::location(PrintMachineCode), cl::init(false)); cl::opt<bool, true> DisableFPElim("disable-fp-elim", cl::desc("Disable frame pointer elimination optimization"), cl::location(NoFramePointerElim), cl::init(false)); cl::opt<bool, true> DisableExcessPrecision("disable-excess-fp-precision", cl::desc("Disable optimizations that may increase FP precision"), cl::location(NoExcessFPPrecision), cl::init(false)); cl::opt<bool, true> EnableUnsafeFPMath("enable-unsafe-fp-math", cl::desc("Enable optimizations that may decrease FP precision"), cl::location(UnsafeFPMath), cl::init(false)); cl::opt<bool, true> EnableFiniteOnltFPMath("enable-finite-only-fp-math", cl::desc("Enable optimizations that assumes non- NaNs / +-Infs"), cl::location(FiniteOnlyFPMathOption), cl::init(false)); cl::opt<bool, true> GenerateSoftFloatCalls("soft-float", cl::desc("Generate software floating point library calls"), cl::location(UseSoftFloat), cl::init(false)); cl::opt<bool, true> DontPlaceZerosInBSS("nozero-initialized-in-bss", cl::desc("Don't place zero-initialized symbols into bss section"), cl::location(NoZerosInBSS), cl::init(false)); cl::opt<bool, true> EnableExceptionHandling("enable-eh", cl::desc("Exception handling should be emitted."), cl::location(ExceptionHandling), cl::init(false)); cl::opt<llvm::Reloc::Model, true> DefRelocationModel( "relocation-model", cl::desc("Choose relocation model"), cl::location(RelocationModel), cl::init(Reloc::Default), cl::values( clEnumValN(Reloc::Default, "default", " Target default relocation model"), clEnumValN(Reloc::Static, "static", " Non-relocatable code"), clEnumValN(Reloc::PIC_, "pic", " Fully relocatable, position independent code"), clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic", " Relocatable external references, non-relocatable code"), clEnumValEnd)); cl::opt<llvm::CodeModel::Model, true> DefCodeModel( "code-model", cl::desc("Choose relocation model"), cl::location(CMModel), cl::init(CodeModel::Default), cl::values( clEnumValN(CodeModel::Default, "default", " Target default code model"), clEnumValN(CodeModel::Small, "small", " Small code model"), clEnumValN(CodeModel::Kernel, "kernel", " Kernel code model"), clEnumValN(CodeModel::Medium, "medium", " Medium code model"), clEnumValN(CodeModel::Large, "large", " Large code model"), clEnumValEnd)); } //--------------------------------------------------------------------------- // TargetMachine Class // TargetMachine::~TargetMachine() { delete AsmInfo; } /// getRelocationModel - Returns the code generation relocation model. The /// choices are static, PIC, and dynamic-no-pic, and target default. Reloc::Model TargetMachine::getRelocationModel() { return RelocationModel; } /// setRelocationModel - Sets the code generation relocation model. void TargetMachine::setRelocationModel(Reloc::Model Model) { RelocationModel = Model; } /// getCodeModel - Returns the code model. The choices are small, kernel, /// medium, large, and target default. CodeModel::Model TargetMachine::getCodeModel() { return CMModel; } /// setCodeModel - Sets the code model. void TargetMachine::setCodeModel(CodeModel::Model Model) { CMModel = Model; } namespace llvm { /// FiniteOnlyFPMath - This returns true when the -enable-finite-only-fp-math /// option is specified on the command line. If this returns false (default), /// the code generator is not allowed to assume that FP arithmetic arguments /// and results are never NaNs or +-Infs. bool FiniteOnlyFPMath() { return UnsafeFPMath || FiniteOnlyFPMathOption; } }
rename flag
rename flag git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@33634 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm
7775c1f1363ca92609f3529ea05bbaad88a09926
lib/VMCore/iMemory.cpp
lib/VMCore/iMemory.cpp
//===-- iMemory.cpp - Implement Memory instructions -----------------------===// // // 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 file implements the various memory related classes defined in iMemory.h // //===----------------------------------------------------------------------===// #include "llvm/iMemory.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" using namespace llvm; AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy, const std::string &Name, Instruction *InsertBef) : Instruction(PointerType::get(Ty), iTy, Name, InsertBef) { // ArraySize defaults to 1. if (!ArraySize) ArraySize = ConstantUInt::get(Type::UIntTy, 1); Operands.reserve(1); assert(ArraySize->getType() == Type::UIntTy && "Malloc/Allocation array size != UIntTy!"); Operands.push_back(Use(ArraySize, this)); } bool AllocationInst::isArrayAllocation() const { return getOperand(0) != ConstantUInt::get(Type::UIntTy, 1); } const Type *AllocationInst::getAllocatedType() const { return getType()->getElementType(); } AllocaInst::AllocaInst(const AllocaInst &AI) : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0), Instruction::Alloca) { } MallocInst::MallocInst(const MallocInst &MI) : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0), Instruction::Malloc) { } //===----------------------------------------------------------------------===// // FreeInst Implementation //===----------------------------------------------------------------------===// FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore) : Instruction(Type::VoidTy, Free, "", InsertBefore) { assert(isa<PointerType>(Ptr->getType()) && "Can't free nonpointer!"); Operands.reserve(1); Operands.push_back(Use(Ptr, this)); } //===----------------------------------------------------------------------===// // LoadInst Implementation //===----------------------------------------------------------------------===// LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef) : Instruction(cast<PointerType>(Ptr->getType())->getElementType(), Load, Name, InsertBef), Volatile(false) { Operands.reserve(1); Operands.push_back(Use(Ptr, this)); } LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile, Instruction *InsertBef) : Instruction(cast<PointerType>(Ptr->getType())->getElementType(), Load, Name, InsertBef), Volatile(isVolatile) { Operands.reserve(1); Operands.push_back(Use(Ptr, this)); } //===----------------------------------------------------------------------===// // StoreInst Implementation //===----------------------------------------------------------------------===// StoreInst::StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore) : Instruction(Type::VoidTy, Store, "", InsertBefore), Volatile(false) { Operands.reserve(2); Operands.push_back(Use(Val, this)); Operands.push_back(Use(Ptr, this)); } StoreInst::StoreInst(Value *Val, Value *Ptr, bool isVolatile, Instruction *InsertBefore) : Instruction(Type::VoidTy, Store, "", InsertBefore), Volatile(isVolatile) { Operands.reserve(2); Operands.push_back(Use(Val, this)); Operands.push_back(Use(Ptr, this)); } //===----------------------------------------------------------------------===// // GetElementPtrInst Implementation //===----------------------------------------------------------------------===// // checkType - Simple wrapper function to give a better assertion failure // message on bad indexes for a gep instruction. // static inline const Type *checkType(const Type *Ty) { assert(Ty && "Invalid indices for type!"); return Ty; } GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx, const std::string &Name, Instruction *InBe) : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(), Idx, true))), GetElementPtr, Name, InBe) { Operands.reserve(1+Idx.size()); Operands.push_back(Use(Ptr, this)); for (unsigned i = 0, E = Idx.size(); i != E; ++i) Operands.push_back(Use(Idx[i], this)); } // getIndexedType - Returns the type of the element that would be loaded with // a load instruction with the specified parameters. // // A null type is returned if the indices are invalid for the specified // pointer type. // const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, const std::vector<Value*> &Idx, bool AllowCompositeLeaf) { if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type! // Handle the special case of the empty set index set... if (Idx.empty()) if (AllowCompositeLeaf || cast<PointerType>(Ptr)->getElementType()->isFirstClassType()) return cast<PointerType>(Ptr)->getElementType(); else return 0; unsigned CurIdx = 0; while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) { if (Idx.size() == CurIdx) { if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr; return 0; // Can't load a whole structure or array!?!? } Value *Index = Idx[CurIdx++]; if (isa<PointerType>(CT) && CurIdx != 1) return 0; // Can only index into pointer types at the first index! if (!CT->indexValid(Index)) return 0; Ptr = CT->getTypeAtIndex(Index); } return CurIdx == Idx.size() ? Ptr : 0; }
//===-- iMemory.cpp - Implement Memory instructions -----------------------===// // // 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 file implements the various memory related classes defined in iMemory.h // //===----------------------------------------------------------------------===// #include "llvm/iMemory.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" using namespace llvm; AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy, const std::string &Name, Instruction *InsertBef) : Instruction(PointerType::get(Ty), iTy, Name, InsertBef) { // ArraySize defaults to 1. if (!ArraySize) ArraySize = ConstantUInt::get(Type::UIntTy, 1); Operands.reserve(1); assert(ArraySize->getType() == Type::UIntTy && "Malloc/Allocation array size != UIntTy!"); Operands.push_back(Use(ArraySize, this)); } bool AllocationInst::isArrayAllocation() const { return getOperand(0) != ConstantUInt::get(Type::UIntTy, 1); } const Type *AllocationInst::getAllocatedType() const { return getType()->getElementType(); } AllocaInst::AllocaInst(const AllocaInst &AI) : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0), Instruction::Alloca) { } MallocInst::MallocInst(const MallocInst &MI) : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0), Instruction::Malloc) { } //===----------------------------------------------------------------------===// // FreeInst Implementation //===----------------------------------------------------------------------===// FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore) : Instruction(Type::VoidTy, Free, "", InsertBefore) { assert(isa<PointerType>(Ptr->getType()) && "Can't free nonpointer!"); Operands.reserve(1); Operands.push_back(Use(Ptr, this)); } //===----------------------------------------------------------------------===// // LoadInst Implementation //===----------------------------------------------------------------------===// LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef) : Instruction(cast<PointerType>(Ptr->getType())->getElementType(), Load, Name, InsertBef), Volatile(false) { Operands.reserve(1); Operands.push_back(Use(Ptr, this)); } LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile, Instruction *InsertBef) : Instruction(cast<PointerType>(Ptr->getType())->getElementType(), Load, Name, InsertBef), Volatile(isVolatile) { Operands.reserve(1); Operands.push_back(Use(Ptr, this)); } //===----------------------------------------------------------------------===// // StoreInst Implementation //===----------------------------------------------------------------------===// StoreInst::StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore) : Instruction(Type::VoidTy, Store, "", InsertBefore), Volatile(false) { Operands.reserve(2); Operands.push_back(Use(Val, this)); Operands.push_back(Use(Ptr, this)); } StoreInst::StoreInst(Value *Val, Value *Ptr, bool isVolatile, Instruction *InsertBefore) : Instruction(Type::VoidTy, Store, "", InsertBefore), Volatile(isVolatile) { Operands.reserve(2); Operands.push_back(Use(Val, this)); Operands.push_back(Use(Ptr, this)); } //===----------------------------------------------------------------------===// // GetElementPtrInst Implementation //===----------------------------------------------------------------------===// // checkType - Simple wrapper function to give a better assertion failure // message on bad indexes for a gep instruction. // static inline const Type *checkType(const Type *Ty) { assert(Ty && "Invalid indices for type!"); return Ty; } GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx, const std::string &Name, Instruction *InBe) : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(), Idx, true))), GetElementPtr, Name, InBe) { Operands.reserve(1+Idx.size()); Operands.push_back(Use(Ptr, this)); for (unsigned i = 0, E = Idx.size(); i != E; ++i) Operands.push_back(Use(Idx[i], this)); } // getIndexedType - Returns the type of the element that would be loaded with // a load instruction with the specified parameters. // // A null type is returned if the indices are invalid for the specified // pointer type. // const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, const std::vector<Value*> &Idx, bool AllowCompositeLeaf) { if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type! // Handle the special case of the empty set index set... if (Idx.empty()) if (AllowCompositeLeaf || cast<PointerType>(Ptr)->getElementType()->isFirstClassType()) return cast<PointerType>(Ptr)->getElementType(); else return 0; unsigned CurIdx = 0; while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) { if (Idx.size() == CurIdx) { if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr; return 0; // Can't load a whole structure or array!?!? } Value *Index = Idx[CurIdx++]; if (isa<PointerType>(CT) && CurIdx != 1) return 0; // Can only index into pointer types at the first index! if (!CT->indexValid(Index)) return 0; Ptr = CT->getTypeAtIndex(Index); // If the new type forwards to another type, then it is in the middle // of being refined to another type (and hence, may have dropped all // references to what it was using before). So, use the new forwarded // type. if (Ptr->getForwardedType()) { Ptr = Ptr->getForwardedType(); } } return CurIdx == Idx.size() ? Ptr : 0; }
Fix for PR#330. When looking at getelementptr instructions, make sure to use a forwarded type. We want to do this because a DerivedType may drop its uses and then refine its users, who may then use another user who hasn't been refined yet. By getting the forwarded type, we always ensure that we're looking at a Type that isn't in a halfway refined state.
Fix for PR#330. When looking at getelementptr instructions, make sure to use a forwarded type. We want to do this because a DerivedType may drop its uses and then refine its users, who may then use another user who hasn't been refined yet. By getting the forwarded type, we always ensure that we're looking at a Type that isn't in a halfway refined state. Now, I should be able to put this stuff in PATypeHandle, but it doesn't work for some reason. This should do for now. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@13386 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap
2e86b99200dd9be3621f1d0bad1ab2d6ec9b517a
gui/xyconvert.cpp
gui/xyconvert.cpp
// xyconvert - GUI to xylib // Licence: Lesser GNU Public License 2.1 (LGPL) #include <wx/wx.h> #include <wx/aboutdlg.h> #include <wx/cmdline.h> #include <wx/filefn.h> #include <wx/ffile.h> #include <wx/filepicker.h> #include <wx/settings.h> #include <wx/infobar.h> #include "xyconvert16.xpm" #include "xyconvert48.xpm" #include "xybrowser.h" using namespace std; class App : public wxApp { public: bool OnInit(); void OnAbout(wxCommandEvent&); void OnConvert(wxCommandEvent&); void OnClose(wxCommandEvent&) { GetTopWindow()->Close(); } void OnDirCheckBox(wxCommandEvent&); void OnFolderChanged(wxFileCtrlEvent& event); private: wxCheckBox *dir_cb, *overwrite, *header; wxDirPickerCtrl *dirpicker; XyFileBrowser *browser; wxTextCtrl *ext_tc; wxInfoBar *info_bar; }; DECLARE_APP(App) IMPLEMENT_APP(App) static const wxCmdLineEntryDesc cmdLineDesc[] = { { wxCMD_LINE_SWITCH, "V", "version", "output version information and exit", wxCMD_LINE_VAL_NONE, 0 }, { wxCMD_LINE_PARAM, 0, 0, "default-path", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL}, { wxCMD_LINE_NONE, 0, 0, 0, wxCMD_LINE_VAL_NONE, 0 } }; bool App::OnInit() { // to make life simpler, use the same version number as xylib wxString version = xylib_get_version(); // reading numbers won't work with decimal points different than '.' setlocale(LC_NUMERIC, "C"); SetAppName("xyConvert"); wxCmdLineParser cmdLineParser(cmdLineDesc, argc, argv); if (cmdLineParser.Parse(false) != 0) { cmdLineParser.Usage(); return false; } if (cmdLineParser.Found(wxT("V"))) { wxMessageOutput::Get()->Printf("xyConvert, powered by xylib " + version + "\n"); return false; } wxFrame *frame = new wxFrame(NULL, wxID_ANY, "xyConvert"); #ifdef __WXOSX__ wxMenu* dummy_menu = new wxMenu; dummy_menu->Append(wxID_ABOUT, "&About xyConvert"); dummy_menu->Append(wxID_EXIT, ""); wxMenuBar *menuBar = new wxMenuBar(); menuBar->Append(dummy_menu, " "); frame->SetMenuBar(menuBar); Connect(wxID_ABOUT, wxEVT_MENU, wxCommandEventHandler(App::OnAbout)); #endif #ifdef __WXMSW__ // use icon resource, the name is assigned in xyconvert.rc frame->SetIcon(wxIcon("a_xyconvert")); #else wxIconBundle ib; ib.AddIcon(wxIcon(xyconvert48_xpm)); ib.AddIcon(wxIcon(xyconvert16_xpm)); frame->SetIcons(ib); #endif wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL); info_bar = new wxInfoBar(frame); sizer->Add(info_bar, wxSizerFlags().Expand()); browser = new XyFileBrowser(frame); sizer->Add(browser, wxSizerFlags(1).Expand()); wxStaticBoxSizer *outsizer = new wxStaticBoxSizer(wxVERTICAL, frame, "text output"); wxBoxSizer *hsizer = new wxBoxSizer(wxHORIZONTAL); dir_cb = new wxCheckBox(frame, wxID_ANY, "directory:"); hsizer->Add(dir_cb, wxSizerFlags().Centre().Border()); dirpicker = new wxDirPickerCtrl(frame, wxID_ANY); hsizer->Add(dirpicker, wxSizerFlags(1)); hsizer->AddSpacer(10); hsizer->Add(new wxStaticText(frame, wxID_ANY, "extension:"), wxSizerFlags().Centre().Border()); ext_tc = new wxTextCtrl(frame, wxID_ANY, "xy"); ext_tc->SetMinSize(wxSize(50, -1)); hsizer->Add(ext_tc, wxSizerFlags().Centre()); hsizer->AddSpacer(10); overwrite = new wxCheckBox(frame, wxID_ANY, "allow overwrite"); hsizer->Add(overwrite, wxSizerFlags().Centre()); outsizer->Add(hsizer, wxSizerFlags().Expand()); header = new wxCheckBox(frame, wxID_ANY, "add header"); outsizer->Add(header, wxSizerFlags().Border()); sizer->Add(outsizer, wxSizerFlags().Expand().Border()); wxBoxSizer *btn_sizer = new wxBoxSizer(wxHORIZONTAL); wxButton *about = new wxButton(frame, wxID_ABOUT); wxButton *convert = new wxButton(frame, wxID_CONVERT); wxButton *close = new wxButton(frame, wxID_EXIT); btn_sizer->Add(about, wxSizerFlags().Border()); btn_sizer->AddStretchSpacer(); btn_sizer->Add(convert, wxSizerFlags().Border()); btn_sizer->Add(close, wxSizerFlags().Border()); sizer->Add(btn_sizer, wxSizerFlags().Expand().Border()); if (cmdLineParser.GetParamCount() > 0) { wxFileName fn(cmdLineParser.GetParam(0)); if (fn.FileExists()) { browser->filectrl->SetPath(fn.GetFullPath()); browser->update_file_options(); } } wxString ini_directory = browser->filectrl->GetDirectory(); if (ini_directory.empty()) dirpicker->SetPath(wxGetCwd()); else dirpicker->SetPath(ini_directory); dirpicker->Enable(false); frame->SetSizerAndFit(sizer); //#ifdef __WXGTK__ int screen_height = wxSystemSettings::GetMetric(wxSYS_SCREEN_Y); frame->SetSize(-1, screen_height > 760 ? 680 : 550); //#endif #ifdef __WXMSW__ // wxMSW bug workaround frame->SetBackgroundColour(browser->GetBackgroundColour()); #endif frame->Show(); Connect(dir_cb->GetId(), wxEVT_COMMAND_CHECKBOX_CLICKED, (wxObjectEventFunction) &App::OnDirCheckBox); browser->Connect(browser->filectrl->GetId(), wxEVT_FILECTRL_FOLDERCHANGED, (wxObjectEventFunction) &App::OnFolderChanged, NULL, this); Connect(about->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction) &App::OnAbout); Connect(convert->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction) &App::OnConvert); Connect(close->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction) &App::OnClose); return true; } void App::OnConvert(wxCommandEvent&) { bool with_header = header->GetValue(); int block_nr = browser->block_ch->GetSelection(); int idx_x = browser->x_column->GetValue(); int idx_y = browser->y_column->GetValue(); bool has_err = browser->std_dev_cb->GetValue(); int idx_err = browser->s_column->GetValue(); bool dec_comma = browser->comma_cb->GetValue(); wxArrayString paths; browser->filectrl->GetPaths(paths); string options; if (dec_comma) options = "decimal-comma"; int conv_counter = 0; wxString new_path; for (size_t i = 0; i < paths.GetCount(); ++i) { wxFileName old_filename(paths[i]); wxString fn = old_filename.GetName() + "." + ext_tc->GetValue(); new_path = dirpicker->GetPath() + wxFILE_SEP_PATH + fn; if (!overwrite->GetValue() && wxFileExists(new_path)) { int answer = wxMessageBox("File " + fn + " exists.\n" "Overwrite?", "Overwrite?", wxYES|wxNO|wxCANCEL|wxICON_QUESTION); if (answer == wxCANCEL) break; if (answer != wxYES) continue; } try { wxBusyCursor wait; xylib::DataSet const *ds = xylib::load_file( (const char*) paths[i].ToUTF8(), browser->get_filetype(), options); xylib::Block const *block = ds->get_block(block_nr); xylib::Column const& xcol = block->get_column(idx_x); xylib::Column const& ycol = block->get_column(idx_y); xylib::Column const* ecol = (has_err ? &block->get_column(idx_err) : NULL); const int np = block->get_point_count(); wxFFile f(new_path, "w"); if (!f.IsOpened()) { wxMessageBox("Cannot open file for writing:\n" + new_path, "Error", wxOK|wxICON_ERROR); continue; } if (with_header) { f.Write(wxString("# Converted by xyConvert ") + xylib_get_version() + ".\n" "# Original file: " + paths[i] + "\n"); if (ds->get_block_count() > 1) fprintf(f.fp(), "# (block %d) %s\n", block_nr, block->get_name().c_str()); if (block->get_column_count() > 2) { string xname = (xcol.get_name().empty() ? string("x") : xcol.get_name()); string yname = (ycol.get_name().empty() ? string("y") : ycol.get_name()); fprintf(f.fp(), "#%s\t%s", xname.c_str(), yname.c_str()); if (has_err) { string ename = (ecol->get_name().empty() ? string("err") : ecol->get_name()); fprintf(f.fp(), "\t%s", ename.c_str()); } fprintf(f.fp(), "\n"); } } for (int j = 0; j < np; ++j) { fprintf(f.fp(), "%.9g\t%.9g", xcol.get_value(j), ycol.get_value(j)); if (has_err) fprintf(f.fp(), "\t%.9g", ecol->get_value(j)); fprintf(f.fp(), "\n"); } conv_counter++; } catch (runtime_error const& e) { wxMessageBox(e.what(), "Error", wxOK|wxICON_ERROR); } } if (conv_counter >= 1) { wxString str = "[" + wxDateTime::Now().FormatISOTime() + "] "; if (conv_counter == 1) str += "file converted: " + new_path; else str += wxString::Format("%d files converted", conv_counter); info_bar->ShowMessage(str, wxICON_INFORMATION); } } void App::OnAbout(wxCommandEvent&) { wxAboutDialogInfo adi; adi.SetVersion(xylib_get_version()); wxString desc = "A simple converter based on the xylib library.\n" "It can convert files supported by xylib\n" "into two- or three-column text format.\n" "This tool is designed to convert multiple files\n" "so the output filename is not explicit."; adi.SetDescription(desc); adi.SetWebSite("http://xylib.sf.net/"); adi.SetCopyright("(C) 2008-2015 Marcin Wojdyr <[email protected]>"); wxAboutBox(adi); } void App::OnDirCheckBox(wxCommandEvent& event) { bool checked = event.IsChecked(); dirpicker->Enable(checked); if (!checked) dirpicker->SetPath(browser->filectrl->GetDirectory()); } void App::OnFolderChanged(wxFileCtrlEvent& event) { if (!dir_cb->GetValue()) dirpicker->SetPath(event.GetDirectory()); }
// xyconvert - GUI to xylib // Licence: Lesser GNU Public License 2.1 (LGPL) #include <wx/wx.h> #include <wx/aboutdlg.h> #include <wx/cmdline.h> #include <wx/filefn.h> #include <wx/ffile.h> #include <wx/filepicker.h> #include <wx/settings.h> #include <wx/infobar.h> #include "xyconvert16.xpm" #include "xyconvert48.xpm" #include "xybrowser.h" using namespace std; class App : public wxApp { public: bool OnInit(); void OnAbout(wxCommandEvent&); void OnConvert(wxCommandEvent&); void OnClose(wxCommandEvent&) { GetTopWindow()->Close(); } void OnDirCheckBox(wxCommandEvent&); void OnFolderChanged(wxFileCtrlEvent& event); private: wxCheckBox *dir_cb, *overwrite, *header; wxDirPickerCtrl *dirpicker; XyFileBrowser *browser; wxTextCtrl *ext_tc; wxInfoBar *info_bar; }; DECLARE_APP(App) IMPLEMENT_APP(App) static const wxCmdLineEntryDesc cmdLineDesc[] = { { wxCMD_LINE_SWITCH, "V", "version", "output version information and exit", wxCMD_LINE_VAL_NONE, 0 }, { wxCMD_LINE_PARAM, 0, 0, "default-path", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL}, { wxCMD_LINE_NONE, 0, 0, 0, wxCMD_LINE_VAL_NONE, 0 } }; bool App::OnInit() { // to make life simpler, use the same version number as xylib wxString version = xylib_get_version(); // reading numbers won't work with decimal points different than '.' setlocale(LC_NUMERIC, "C"); SetAppName("xyConvert"); wxCmdLineParser cmdLineParser(cmdLineDesc, argc, argv); if (cmdLineParser.Parse(false) != 0) { cmdLineParser.Usage(); return false; } if (cmdLineParser.Found(wxT("V"))) { wxMessageOutput::Get()->Printf("xyConvert, powered by xylib " + version + "\n"); return false; } //wxInitAllImageHandlers(); #ifdef __WXOSX__ // wxInfoBar uses close_png in wxRendererMac::DrawTitleBarBitmap() wxImage::AddHandler(new wxPNGHandler); #endif wxFrame *frame = new wxFrame(NULL, wxID_ANY, "xyConvert"); #ifdef __WXOSX__ wxMenu* dummy_menu = new wxMenu; dummy_menu->Append(wxID_ABOUT, "&About xyConvert"); dummy_menu->Append(wxID_EXIT, ""); wxMenuBar *menuBar = new wxMenuBar(); menuBar->Append(dummy_menu, " "); frame->SetMenuBar(menuBar); Connect(wxID_ABOUT, wxEVT_MENU, wxCommandEventHandler(App::OnAbout)); #endif #ifdef __WXMSW__ // use icon resource, the name is assigned in xyconvert.rc frame->SetIcon(wxIcon("a_xyconvert")); #else wxIconBundle ib; ib.AddIcon(wxIcon(xyconvert48_xpm)); ib.AddIcon(wxIcon(xyconvert16_xpm)); frame->SetIcons(ib); #endif wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL); info_bar = new wxInfoBar(frame); sizer->Add(info_bar, wxSizerFlags().Expand()); browser = new XyFileBrowser(frame); sizer->Add(browser, wxSizerFlags(1).Expand()); wxStaticBoxSizer *outsizer = new wxStaticBoxSizer(wxVERTICAL, frame, "text output"); wxBoxSizer *hsizer = new wxBoxSizer(wxHORIZONTAL); dir_cb = new wxCheckBox(frame, wxID_ANY, "directory:"); hsizer->Add(dir_cb, wxSizerFlags().Centre().Border()); dirpicker = new wxDirPickerCtrl(frame, wxID_ANY); hsizer->Add(dirpicker, wxSizerFlags(1)); hsizer->AddSpacer(10); hsizer->Add(new wxStaticText(frame, wxID_ANY, "extension:"), wxSizerFlags().Centre().Border()); ext_tc = new wxTextCtrl(frame, wxID_ANY, "xy"); ext_tc->SetMinSize(wxSize(50, -1)); hsizer->Add(ext_tc, wxSizerFlags().Centre()); hsizer->AddSpacer(10); overwrite = new wxCheckBox(frame, wxID_ANY, "allow overwrite"); hsizer->Add(overwrite, wxSizerFlags().Centre()); outsizer->Add(hsizer, wxSizerFlags().Expand()); header = new wxCheckBox(frame, wxID_ANY, "add header"); outsizer->Add(header, wxSizerFlags().Border()); sizer->Add(outsizer, wxSizerFlags().Expand().Border()); wxBoxSizer *btn_sizer = new wxBoxSizer(wxHORIZONTAL); wxButton *about = new wxButton(frame, wxID_ABOUT); wxButton *convert = new wxButton(frame, wxID_CONVERT); wxButton *close = new wxButton(frame, wxID_EXIT); btn_sizer->Add(about, wxSizerFlags().Border()); btn_sizer->AddStretchSpacer(); btn_sizer->Add(convert, wxSizerFlags().Border()); btn_sizer->Add(close, wxSizerFlags().Border()); sizer->Add(btn_sizer, wxSizerFlags().Expand().Border()); if (cmdLineParser.GetParamCount() > 0) { wxFileName fn(cmdLineParser.GetParam(0)); if (fn.FileExists()) { browser->filectrl->SetPath(fn.GetFullPath()); browser->update_file_options(); } } wxString ini_directory = browser->filectrl->GetDirectory(); if (ini_directory.empty()) dirpicker->SetPath(wxGetCwd()); else dirpicker->SetPath(ini_directory); dirpicker->Enable(false); frame->SetSizerAndFit(sizer); //#ifdef __WXGTK__ int screen_height = wxSystemSettings::GetMetric(wxSYS_SCREEN_Y); frame->SetSize(-1, screen_height > 760 ? 680 : 550); //#endif #ifdef __WXMSW__ // wxMSW bug workaround frame->SetBackgroundColour(browser->GetBackgroundColour()); #endif frame->Show(); Connect(dir_cb->GetId(), wxEVT_COMMAND_CHECKBOX_CLICKED, (wxObjectEventFunction) &App::OnDirCheckBox); browser->Connect(browser->filectrl->GetId(), wxEVT_FILECTRL_FOLDERCHANGED, (wxObjectEventFunction) &App::OnFolderChanged, NULL, this); Connect(about->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction) &App::OnAbout); Connect(convert->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction) &App::OnConvert); Connect(close->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction) &App::OnClose); return true; } void App::OnConvert(wxCommandEvent&) { bool with_header = header->GetValue(); int block_nr = browser->block_ch->GetSelection(); int idx_x = browser->x_column->GetValue(); int idx_y = browser->y_column->GetValue(); bool has_err = browser->std_dev_cb->GetValue(); int idx_err = browser->s_column->GetValue(); bool dec_comma = browser->comma_cb->GetValue(); wxArrayString paths; browser->filectrl->GetPaths(paths); string options; if (dec_comma) options = "decimal-comma"; int conv_counter = 0; wxString new_path; for (size_t i = 0; i < paths.GetCount(); ++i) { wxFileName old_filename(paths[i]); wxString fn = old_filename.GetName() + "." + ext_tc->GetValue(); new_path = dirpicker->GetPath() + wxFILE_SEP_PATH + fn; if (!overwrite->GetValue() && wxFileExists(new_path)) { int answer = wxMessageBox("File " + fn + " exists.\n" "Overwrite?", "Overwrite?", wxYES|wxNO|wxCANCEL|wxICON_QUESTION); if (answer == wxCANCEL) break; if (answer != wxYES) continue; } try { wxBusyCursor wait; xylib::DataSet const *ds = xylib::load_file( (const char*) paths[i].ToUTF8(), browser->get_filetype(), options); xylib::Block const *block = ds->get_block(block_nr); xylib::Column const& xcol = block->get_column(idx_x); xylib::Column const& ycol = block->get_column(idx_y); xylib::Column const* ecol = (has_err ? &block->get_column(idx_err) : NULL); const int np = block->get_point_count(); wxFFile f(new_path, "w"); if (!f.IsOpened()) { wxMessageBox("Cannot open file for writing:\n" + new_path, "Error", wxOK|wxICON_ERROR); continue; } if (with_header) { f.Write(wxString("# Converted by xyConvert ") + xylib_get_version() + ".\n" "# Original file: " + paths[i] + "\n"); if (ds->get_block_count() > 1) fprintf(f.fp(), "# (block %d) %s\n", block_nr, block->get_name().c_str()); if (block->get_column_count() > 2) { string xname = (xcol.get_name().empty() ? string("x") : xcol.get_name()); string yname = (ycol.get_name().empty() ? string("y") : ycol.get_name()); fprintf(f.fp(), "#%s\t%s", xname.c_str(), yname.c_str()); if (has_err) { string ename = (ecol->get_name().empty() ? string("err") : ecol->get_name()); fprintf(f.fp(), "\t%s", ename.c_str()); } fprintf(f.fp(), "\n"); } } for (int j = 0; j < np; ++j) { fprintf(f.fp(), "%.9g\t%.9g", xcol.get_value(j), ycol.get_value(j)); if (has_err) fprintf(f.fp(), "\t%.9g", ecol->get_value(j)); fprintf(f.fp(), "\n"); } conv_counter++; } catch (runtime_error const& e) { wxMessageBox(e.what(), "Error", wxOK|wxICON_ERROR); } } if (conv_counter >= 1) { wxString str = "[" + wxDateTime::Now().FormatISOTime() + "] "; if (conv_counter == 1) str += "file converted: " + new_path; else str += wxString::Format("%d files converted", conv_counter); info_bar->ShowMessage(str, wxICON_INFORMATION); } } void App::OnAbout(wxCommandEvent&) { wxAboutDialogInfo adi; adi.SetVersion(xylib_get_version()); wxString desc = "A simple converter based on the xylib library.\n" "It can convert files supported by xylib\n" "into two- or three-column text format.\n" "This tool is designed to convert multiple files\n" "so the output filename is not explicit."; adi.SetDescription(desc); adi.SetWebSite("http://xylib.sf.net/"); adi.SetCopyright("(C) 2008-2015 Marcin Wojdyr <[email protected]>"); wxAboutBox(adi); } void App::OnDirCheckBox(wxCommandEvent& event) { bool checked = event.IsChecked(); dirpicker->Enable(checked); if (!checked) dirpicker->SetPath(browser->filectrl->GetDirectory()); } void App::OnFolderChanged(wxFileCtrlEvent& event) { if (!dir_cb->GetValue()) dirpicker->SetPath(event.GetDirectory()); }
fix for OSX
gui/xyconvert.cpp: fix for OSX
C++
lgpl-2.1
wojdyr/xylib,wojdyr/xylib,wojdyr/xylib
653b62bf6a9a14d5dfbfe8bd05bdbd7692d72ea1
chrome/browser/extensions/external_extension_loader.cc
chrome/browser/extensions/external_extension_loader.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/external_extension_loader.h" #include "base/logging.h" #include "base/values.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/extensions/external_extension_provider_impl.h" ExternalExtensionLoader::ExternalExtensionLoader() : running_(false) {} void ExternalExtensionLoader::Init( ExternalExtensionProviderImpl* owner) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); owner_ = owner; } const FilePath ExternalExtensionLoader::GetBaseCrxFilePath() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // By default, relative paths are not supported. // Subclasses that wish to support them should override this method. return FilePath(); } void ExternalExtensionLoader::OwnerShutdown() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); owner_ = NULL; } ExternalExtensionLoader::~ExternalExtensionLoader() {} void ExternalExtensionLoader::LoadFinished() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); running_ = false; if (owner_) { owner_->SetPrefs(prefs_.release()); } }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/external_extension_loader.h" #include "base/logging.h" #include "base/values.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/extensions/external_extension_provider_impl.h" ExternalExtensionLoader::ExternalExtensionLoader() : owner_(NULL), running_(false) { } void ExternalExtensionLoader::Init( ExternalExtensionProviderImpl* owner) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); owner_ = owner; } const FilePath ExternalExtensionLoader::GetBaseCrxFilePath() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // By default, relative paths are not supported. // Subclasses that wish to support them should override this method. return FilePath(); } void ExternalExtensionLoader::OwnerShutdown() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); owner_ = NULL; } ExternalExtensionLoader::~ExternalExtensionLoader() {} void ExternalExtensionLoader::LoadFinished() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); running_ = false; if (owner_) { owner_->SetPrefs(prefs_.release()); } }
Initialize ExternalExtensionLoader member.
Initialize ExternalExtensionLoader member. BUG=None TEST=None CID=14460 Review URL: http://codereview.chromium.org/6471022 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@74795 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium
3cb1554de2e62efaf3853e5b1a07b8e8d69c9ef3
chrome/browser/geolocation/network_location_request.cc
chrome/browser/geolocation/network_location_request.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/geolocation/network_location_request.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/string_util.h" #include "base/values.h" #include "chrome/browser/net/url_request_context_getter.h" #include "chrome/common/geoposition.h" #include "net/url_request/url_request_status.h" namespace { const char* const kMimeApplicationJson = "application/json"; // See http://code.google.com/apis/gears/geolocation_network_protocol.html const char* kGeoLocationNetworkProtocolVersion = "1.1.0"; const wchar_t* kAccessTokenString = L"access_token"; const wchar_t* kLocationString = L"location"; const wchar_t* kLatitudeString = L"latitude"; const wchar_t* kLongitudeString = L"longitude"; const wchar_t* kAltitudeString = L"altitude"; const wchar_t* kAccuracyString = L"accuracy"; const wchar_t* kAltitudeAccuracyString = L"altitude_accuracy"; // Local functions // Creates the request payload to send to the server. bool FormRequestBody(const string16& host_name, const string16& access_token, const RadioData& radio_data, const WifiData& wifi_data, std::string* data); // Parsers the server response. void GetLocationFromResponse(bool http_post_result, int status_code, const std::string& response_body, int64 timestamp, const GURL& server_url, Geoposition* position, string16* access_token); const char* RadioTypeToString(RadioType type); // Adds a string if it's valid to the JSON object. void AddString(const std::wstring& property_name, const string16& value, DictionaryValue* object); // Adds an integer if it's valid to the JSON object. void AddInteger(const std::wstring& property_name, int value, DictionaryValue* object); // Parses the server response body. Returns true if parsing was successful. bool ParseServerResponse(const std::string& response_body, int64 timestamp, Geoposition* position, string16* access_token); void AddRadioData(const RadioData& radio_data, DictionaryValue* body_object); void AddWifiData(const WifiData& wifi_data, DictionaryValue* body_object); } // namespace NetworkLocationRequest::NetworkLocationRequest(URLRequestContextGetter* context, const GURL& url, const string16& host_name, ListenerInterface* listener) : url_context_(context), timestamp_(kint64min), listener_(listener), url_(url), host_name_(host_name) { DCHECK(listener); } NetworkLocationRequest::~NetworkLocationRequest() { } bool NetworkLocationRequest::MakeRequest(const string16& access_token, const RadioData& radio_data, const WifiData& wifi_data, int64 timestamp) { if (url_fetcher_ != NULL) { DLOG(INFO) << "NetworkLocationRequest : Cancelling pending request"; url_fetcher_.reset(); } std::string post_body; if (!FormRequestBody(host_name_, access_token, radio_data, wifi_data, &post_body)) { return false; } timestamp_ = timestamp; url_fetcher_.reset(URLFetcher::Create( wifi_data.access_point_data.size(), // Used for testing url_, URLFetcher::POST, this)); url_fetcher_->set_upload_data(kMimeApplicationJson, post_body); url_fetcher_->set_request_context(url_context_); url_fetcher_->Start(); return true; } void NetworkLocationRequest::OnURLFetchComplete(const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { DCHECK_EQ(url_fetcher_.get(), source); DCHECK(url_.possibly_invalid_spec() == url.possibly_invalid_spec()); Geoposition position; string16 access_token; GetLocationFromResponse(status.is_success(), response_code, data, timestamp_, url, &position, &access_token); const bool server_error = !status.is_success() || (response_code >= 500 && response_code < 600); url_fetcher_.reset(); DCHECK(listener_); DLOG(INFO) << "NetworkLocationRequest::Run() : " "Calling listener with position.\n"; listener_->LocationResponseAvailable(position, server_error, access_token); } // Local functions. namespace { bool FormRequestBody(const string16& host_name, const string16& access_token, const RadioData& radio_data, const WifiData& wifi_data, std::string* data) { DCHECK(data); DictionaryValue body_object; // Version and host are required. if (host_name.empty()) { return false; } body_object.SetString(L"version", kGeoLocationNetworkProtocolVersion); AddString(L"host", host_name, &body_object); AddString(L"access_token", access_token, &body_object); body_object.SetBoolean(L"request_address", false); AddRadioData(radio_data, &body_object); AddWifiData(wifi_data, &body_object); // TODO(joth): Do we need to mess with locales? // We always use the platform independent 'C' locale when writing the JSON // request, irrespective of the browser's locale. This avoids the need for // the network location provider to determine the locale of the request and // parse the JSON accordingly. // char* current_locale = setlocale(LC_NUMERIC, "C"); base::JSONWriter::Write(&body_object, false, data); // setlocale(LC_NUMERIC, current_locale); DLOG(INFO) << "NetworkLocationRequest::FormRequestBody(): Formed body " << data << ".\n"; return true; } void FormatPositionError(const GURL& server_url, const std::wstring& message, Geoposition* position) { position->error_code = Geoposition::ERROR_CODE_POSITION_UNAVAILABLE; position->error_message = L"Network location provider at '"; position->error_message += ASCIIToWide(server_url.possibly_invalid_spec()); position->error_message += L"' : "; position->error_message += message; position->error_message += L"."; LOG(INFO) << "NetworkLocationRequest::GetLocationFromResponse() : " << position->error_message; } void GetLocationFromResponse(bool http_post_result, int status_code, const std::string& response_body, int64 timestamp, const GURL& server_url, Geoposition* position, string16* access_token) { DCHECK(position); DCHECK(access_token); // HttpPost can fail for a number of reasons. Most likely this is because // we're offline, or there was no response. if (!http_post_result) { FormatPositionError(server_url, L"No response received", position); return; } if (status_code != 200) { // XXX is '200' in a constant? Can't see it // The response was bad. std::wstring message = L"Returned error code "; message += IntToWString(status_code); FormatPositionError(server_url, message, position); return; } // We use the timestamp from the device data that was used to generate // this position fix. if (!ParseServerResponse(response_body, timestamp, position, access_token)) { // We failed to parse the repsonse. FormatPositionError(server_url, L"Response was malformed", position); return; } // The response was successfully parsed, but it may not be a valid // position fix. if (!position->IsValidFix()) { FormatPositionError(server_url, L"Did not provide a good position fix", position); return; } } const char* RadioTypeToString(RadioType type) { switch (type) { case RADIO_TYPE_UNKNOWN: break; case RADIO_TYPE_GSM: return "gsm"; case RADIO_TYPE_CDMA: return "cdma"; case RADIO_TYPE_WCDMA: return "wcdma"; default: LOG(DFATAL) << "Bad RadioType"; } return "unknown"; } void AddString(const std::wstring& property_name, const string16& value, DictionaryValue* object) { DCHECK(object); if (!value.empty()) { object->SetStringFromUTF16(property_name, value); } } void AddInteger(const std::wstring& property_name, int value, DictionaryValue* object) { DCHECK(object); if (kint32min != value) { object->SetInteger(property_name, value); } } // Numeric values without a decimal point have type integer and IsDouble() will // return false. This is convenience function for detecting integer or floating // point numeric values. Note that isIntegral() includes boolean values, which // is not what we want. bool GetAsDouble(const DictionaryValue& object, const std::wstring& property_name, double* out) { DCHECK(out); Value* value = NULL; if (!object.Get(property_name, &value)) return false; int value_as_int; DCHECK(value); if (value->GetAsInteger(&value_as_int)) { *out = value_as_int; return true; } return value->GetAsReal(out); } bool ParseServerResponse(const std::string& response_body, int64 timestamp, Geoposition* position, string16* access_token) { DCHECK(position); DCHECK(access_token); DCHECK(timestamp != kint64min); if (response_body.empty()) { LOG(WARNING) << "ParseServerResponse() : Response was empty.\n"; return false; } DLOG(INFO) << "ParseServerResponse() : Parsing response " << response_body << ".\n"; // Parse the response, ignoring comments. // TODO(joth): Gears version stated: The JSON reponse from the network // location provider should always use the 'C' locale. // Chromium JSON parser works in UTF8 so hopefully we can ignore setlocale? // char* current_locale = setlocale(LC_NUMERIC, "C"); std::string error_msg; scoped_ptr<Value> response_value(base::JSONReader::ReadAndReturnError( response_body, false, &error_msg)); // setlocale(LC_NUMERIC, current_locale); if (response_value == NULL) { LOG(WARNING) << "ParseServerResponse() : JSONReader failed : " << error_msg << ".\n"; return false; } if (!response_value->IsType(Value::TYPE_DICTIONARY)) { LOG(INFO) << "ParseServerResponse() : Unexpected resopnse type " << response_value->GetType() << ".\n"; return false; } const DictionaryValue* response_object = static_cast<DictionaryValue*>(response_value.get()); // Get the access token, if any. response_object->GetStringAsUTF16(kAccessTokenString, access_token); // Get the location Value* location_value = NULL; if (!response_object->Get(kLocationString, &location_value)) { LOG(INFO) << "ParseServerResponse() : Missing location attribute.\n"; return false; } DCHECK(location_value); if (!location_value->IsType(Value::TYPE_DICTIONARY)) { if (!location_value->IsType(Value::TYPE_NULL)) { LOG(INFO) << "ParseServerResponse() : Unexpected location type" << location_value->GetType() << ".\n"; // If the network provider was unable to provide a position fix, it should // return a HTTP 200, with "location" : null. Otherwise it's an error. return false; } return true; // Successfully parsed response containing no fix. } DictionaryValue* location_object = static_cast<DictionaryValue*>(location_value); // latitude and longitude fields are always required. double latitude, longitude; if (!GetAsDouble(*location_object, kLatitudeString, &latitude) || !GetAsDouble(*location_object, kLongitudeString, &longitude)) { LOG(INFO) << "ParseServerResponse() : location lacks lat and/or long.\n"; return false; } // All error paths covered: now start actually modifying postion. position->latitude = latitude; position->longitude = longitude; position->timestamp = timestamp; // Other fields are optional. GetAsDouble(*location_object, kAccuracyString, &position->accuracy); GetAsDouble(*location_object, kAltitudeString, &position->altitude); GetAsDouble(*location_object, kAltitudeAccuracyString, &position->altitude_accuracy); return true; } void AddRadioData(const RadioData& radio_data, DictionaryValue* body_object) { DCHECK(body_object); AddInteger(L"home_mobile_country_code", radio_data.home_mobile_country_code, body_object); AddInteger(L"home_mobile_network_code", radio_data.home_mobile_network_code, body_object); AddString(L"radio_type", ASCIIToUTF16(RadioTypeToString(radio_data.radio_type)), body_object); AddString(L"carrier", radio_data.carrier, body_object); const int num_cell_towers = static_cast<int>(radio_data.cell_data.size()); if (num_cell_towers == 0) { return; } ListValue* cell_towers = new ListValue; for (int i = 0; i < num_cell_towers; ++i) { DictionaryValue* cell_tower = new DictionaryValue; AddInteger(L"cell_id", radio_data.cell_data[i].cell_id, cell_tower); AddInteger(L"location_area_code", radio_data.cell_data[i].location_area_code, cell_tower); AddInteger(L"mobile_country_code", radio_data.cell_data[i].mobile_country_code, cell_tower); AddInteger(L"mobile_network_code", radio_data.cell_data[i].mobile_network_code, cell_tower); AddInteger(L"age", radio_data.cell_data[i].age, cell_tower); AddInteger(L"signal_strength", radio_data.cell_data[i].radio_signal_strength, cell_tower); AddInteger(L"timing_advance", radio_data.cell_data[i].timing_advance, cell_tower); cell_towers->Append(cell_tower); } body_object->Set(L"cell_towers", cell_towers); } void AddWifiData(const WifiData& wifi_data, DictionaryValue* body_object) { DCHECK(body_object); if (wifi_data.access_point_data.empty()) { return; } ListValue* wifi_towers = new ListValue; for (WifiData::AccessPointDataSet::const_iterator iter = wifi_data.access_point_data.begin(); iter != wifi_data.access_point_data.end(); iter++) { DictionaryValue* wifi_tower = new DictionaryValue; AddString(L"mac_address", iter->mac_address, wifi_tower); AddInteger(L"signal_strength", iter->radio_signal_strength, wifi_tower); AddInteger(L"age", iter->age, wifi_tower); AddInteger(L"channel", iter->channel, wifi_tower); AddInteger(L"signal_to_noise", iter->signal_to_noise, wifi_tower); AddString(L"ssid", iter->ssid, wifi_tower); wifi_towers->Append(wifi_tower); } body_object->Set(L"wifi_towers", wifi_towers); } } // namespace
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/geolocation/network_location_request.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/string_util.h" #include "base/values.h" #include "chrome/browser/net/url_request_context_getter.h" #include "chrome/common/geoposition.h" #include "net/base/load_flags.h" #include "net/url_request/url_request_status.h" namespace { const char* const kMimeApplicationJson = "application/json"; // See http://code.google.com/apis/gears/geolocation_network_protocol.html const char* kGeoLocationNetworkProtocolVersion = "1.1.0"; const wchar_t* kAccessTokenString = L"access_token"; const wchar_t* kLocationString = L"location"; const wchar_t* kLatitudeString = L"latitude"; const wchar_t* kLongitudeString = L"longitude"; const wchar_t* kAltitudeString = L"altitude"; const wchar_t* kAccuracyString = L"accuracy"; const wchar_t* kAltitudeAccuracyString = L"altitude_accuracy"; // Local functions // Creates the request payload to send to the server. bool FormRequestBody(const string16& host_name, const string16& access_token, const RadioData& radio_data, const WifiData& wifi_data, std::string* data); // Parsers the server response. void GetLocationFromResponse(bool http_post_result, int status_code, const std::string& response_body, int64 timestamp, const GURL& server_url, Geoposition* position, string16* access_token); const char* RadioTypeToString(RadioType type); // Adds a string if it's valid to the JSON object. void AddString(const std::wstring& property_name, const string16& value, DictionaryValue* object); // Adds an integer if it's valid to the JSON object. void AddInteger(const std::wstring& property_name, int value, DictionaryValue* object); // Parses the server response body. Returns true if parsing was successful. bool ParseServerResponse(const std::string& response_body, int64 timestamp, Geoposition* position, string16* access_token); void AddRadioData(const RadioData& radio_data, DictionaryValue* body_object); void AddWifiData(const WifiData& wifi_data, DictionaryValue* body_object); } // namespace NetworkLocationRequest::NetworkLocationRequest(URLRequestContextGetter* context, const GURL& url, const string16& host_name, ListenerInterface* listener) : url_context_(context), timestamp_(kint64min), listener_(listener), url_(url), host_name_(host_name) { DCHECK(listener); } NetworkLocationRequest::~NetworkLocationRequest() { } bool NetworkLocationRequest::MakeRequest(const string16& access_token, const RadioData& radio_data, const WifiData& wifi_data, int64 timestamp) { if (url_fetcher_ != NULL) { DLOG(INFO) << "NetworkLocationRequest : Cancelling pending request"; url_fetcher_.reset(); } std::string post_body; if (!FormRequestBody(host_name_, access_token, radio_data, wifi_data, &post_body)) { return false; } timestamp_ = timestamp; url_fetcher_.reset(URLFetcher::Create( wifi_data.access_point_data.size(), // Used for testing url_, URLFetcher::POST, this)); url_fetcher_->set_upload_data(kMimeApplicationJson, post_body); url_fetcher_->set_request_context(url_context_); url_fetcher_->set_load_flags( net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE | net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SEND_AUTH_DATA); url_fetcher_->Start(); return true; } void NetworkLocationRequest::OnURLFetchComplete(const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { DCHECK_EQ(url_fetcher_.get(), source); DCHECK(url_.possibly_invalid_spec() == url.possibly_invalid_spec()); Geoposition position; string16 access_token; GetLocationFromResponse(status.is_success(), response_code, data, timestamp_, url, &position, &access_token); const bool server_error = !status.is_success() || (response_code >= 500 && response_code < 600); url_fetcher_.reset(); DCHECK(listener_); DLOG(INFO) << "NetworkLocationRequest::Run() : " "Calling listener with position.\n"; listener_->LocationResponseAvailable(position, server_error, access_token); } // Local functions. namespace { bool FormRequestBody(const string16& host_name, const string16& access_token, const RadioData& radio_data, const WifiData& wifi_data, std::string* data) { DCHECK(data); DictionaryValue body_object; // Version and host are required. if (host_name.empty()) { return false; } body_object.SetString(L"version", kGeoLocationNetworkProtocolVersion); AddString(L"host", host_name, &body_object); AddString(L"access_token", access_token, &body_object); body_object.SetBoolean(L"request_address", false); AddRadioData(radio_data, &body_object); AddWifiData(wifi_data, &body_object); base::JSONWriter::Write(&body_object, false, data); DLOG(INFO) << "NetworkLocationRequest::FormRequestBody(): Formed body " << data << ".\n"; return true; } void FormatPositionError(const GURL& server_url, const std::wstring& message, Geoposition* position) { position->error_code = Geoposition::ERROR_CODE_POSITION_UNAVAILABLE; position->error_message = L"Network location provider at '"; position->error_message += ASCIIToWide(server_url.possibly_invalid_spec()); position->error_message += L"' : "; position->error_message += message; position->error_message += L"."; LOG(INFO) << "NetworkLocationRequest::GetLocationFromResponse() : " << position->error_message; } void GetLocationFromResponse(bool http_post_result, int status_code, const std::string& response_body, int64 timestamp, const GURL& server_url, Geoposition* position, string16* access_token) { DCHECK(position); DCHECK(access_token); // HttpPost can fail for a number of reasons. Most likely this is because // we're offline, or there was no response. if (!http_post_result) { FormatPositionError(server_url, L"No response received", position); return; } if (status_code != 200) { // XXX is '200' in a constant? Can't see it // The response was bad. std::wstring message = L"Returned error code "; message += IntToWString(status_code); FormatPositionError(server_url, message, position); return; } // We use the timestamp from the device data that was used to generate // this position fix. if (!ParseServerResponse(response_body, timestamp, position, access_token)) { // We failed to parse the repsonse. FormatPositionError(server_url, L"Response was malformed", position); return; } // The response was successfully parsed, but it may not be a valid // position fix. if (!position->IsValidFix()) { FormatPositionError(server_url, L"Did not provide a good position fix", position); return; } } const char* RadioTypeToString(RadioType type) { switch (type) { case RADIO_TYPE_UNKNOWN: break; case RADIO_TYPE_GSM: return "gsm"; case RADIO_TYPE_CDMA: return "cdma"; case RADIO_TYPE_WCDMA: return "wcdma"; default: LOG(DFATAL) << "Bad RadioType"; } return "unknown"; } void AddString(const std::wstring& property_name, const string16& value, DictionaryValue* object) { DCHECK(object); if (!value.empty()) { object->SetStringFromUTF16(property_name, value); } } void AddInteger(const std::wstring& property_name, int value, DictionaryValue* object) { DCHECK(object); if (kint32min != value) { object->SetInteger(property_name, value); } } // Numeric values without a decimal point have type integer and IsDouble() will // return false. This is convenience function for detecting integer or floating // point numeric values. Note that isIntegral() includes boolean values, which // is not what we want. bool GetAsDouble(const DictionaryValue& object, const std::wstring& property_name, double* out) { DCHECK(out); Value* value = NULL; if (!object.Get(property_name, &value)) return false; int value_as_int; DCHECK(value); if (value->GetAsInteger(&value_as_int)) { *out = value_as_int; return true; } return value->GetAsReal(out); } bool ParseServerResponse(const std::string& response_body, int64 timestamp, Geoposition* position, string16* access_token) { DCHECK(position); DCHECK(access_token); DCHECK(timestamp != kint64min); if (response_body.empty()) { LOG(WARNING) << "ParseServerResponse() : Response was empty.\n"; return false; } DLOG(INFO) << "ParseServerResponse() : Parsing response " << response_body << ".\n"; // Parse the response, ignoring comments. std::string error_msg; scoped_ptr<Value> response_value(base::JSONReader::ReadAndReturnError( response_body, false, &error_msg)); if (response_value == NULL) { LOG(WARNING) << "ParseServerResponse() : JSONReader failed : " << error_msg << ".\n"; return false; } if (!response_value->IsType(Value::TYPE_DICTIONARY)) { LOG(INFO) << "ParseServerResponse() : Unexpected resopnse type " << response_value->GetType() << ".\n"; return false; } const DictionaryValue* response_object = static_cast<DictionaryValue*>(response_value.get()); // Get the access token, if any. response_object->GetStringAsUTF16(kAccessTokenString, access_token); // Get the location Value* location_value = NULL; if (!response_object->Get(kLocationString, &location_value)) { LOG(INFO) << "ParseServerResponse() : Missing location attribute.\n"; return false; } DCHECK(location_value); if (!location_value->IsType(Value::TYPE_DICTIONARY)) { if (!location_value->IsType(Value::TYPE_NULL)) { LOG(INFO) << "ParseServerResponse() : Unexpected location type" << location_value->GetType() << ".\n"; // If the network provider was unable to provide a position fix, it should // return a HTTP 200, with "location" : null. Otherwise it's an error. return false; } return true; // Successfully parsed response containing no fix. } DictionaryValue* location_object = static_cast<DictionaryValue*>(location_value); // latitude and longitude fields are always required. double latitude, longitude; if (!GetAsDouble(*location_object, kLatitudeString, &latitude) || !GetAsDouble(*location_object, kLongitudeString, &longitude)) { LOG(INFO) << "ParseServerResponse() : location lacks lat and/or long.\n"; return false; } // All error paths covered: now start actually modifying postion. position->latitude = latitude; position->longitude = longitude; position->timestamp = timestamp; // Other fields are optional. GetAsDouble(*location_object, kAccuracyString, &position->accuracy); GetAsDouble(*location_object, kAltitudeString, &position->altitude); GetAsDouble(*location_object, kAltitudeAccuracyString, &position->altitude_accuracy); return true; } void AddRadioData(const RadioData& radio_data, DictionaryValue* body_object) { DCHECK(body_object); AddInteger(L"home_mobile_country_code", radio_data.home_mobile_country_code, body_object); AddInteger(L"home_mobile_network_code", radio_data.home_mobile_network_code, body_object); AddString(L"radio_type", ASCIIToUTF16(RadioTypeToString(radio_data.radio_type)), body_object); AddString(L"carrier", radio_data.carrier, body_object); const int num_cell_towers = static_cast<int>(radio_data.cell_data.size()); if (num_cell_towers == 0) { return; } ListValue* cell_towers = new ListValue; for (int i = 0; i < num_cell_towers; ++i) { DictionaryValue* cell_tower = new DictionaryValue; AddInteger(L"cell_id", radio_data.cell_data[i].cell_id, cell_tower); AddInteger(L"location_area_code", radio_data.cell_data[i].location_area_code, cell_tower); AddInteger(L"mobile_country_code", radio_data.cell_data[i].mobile_country_code, cell_tower); AddInteger(L"mobile_network_code", radio_data.cell_data[i].mobile_network_code, cell_tower); AddInteger(L"age", radio_data.cell_data[i].age, cell_tower); AddInteger(L"signal_strength", radio_data.cell_data[i].radio_signal_strength, cell_tower); AddInteger(L"timing_advance", radio_data.cell_data[i].timing_advance, cell_tower); cell_towers->Append(cell_tower); } body_object->Set(L"cell_towers", cell_towers); } void AddWifiData(const WifiData& wifi_data, DictionaryValue* body_object) { DCHECK(body_object); if (wifi_data.access_point_data.empty()) { return; } ListValue* wifi_towers = new ListValue; for (WifiData::AccessPointDataSet::const_iterator iter = wifi_data.access_point_data.begin(); iter != wifi_data.access_point_data.end(); iter++) { DictionaryValue* wifi_tower = new DictionaryValue; AddString(L"mac_address", iter->mac_address, wifi_tower); AddInteger(L"signal_strength", iter->radio_signal_strength, wifi_tower); AddInteger(L"age", iter->age, wifi_tower); AddInteger(L"channel", iter->channel, wifi_tower); AddInteger(L"signal_to_noise", iter->signal_to_noise, wifi_tower); AddString(L"ssid", iter->ssid, wifi_tower); wifi_towers->Append(wifi_tower); } body_object->Set(L"wifi_towers", wifi_towers); } } // namespace
Fix geolocation network request to not send/save cookies or send authentication data when accessing the network location server. This is to conserve user privacy. Remove obsolete todos whilst in there.
Fix geolocation network request to not send/save cookies or send authentication data when accessing the network location server. This is to conserve user privacy. Remove obsolete todos whilst in there. BUG=http://crbug.com/11246 TEST=use wireshark to inspect request headers sent. Review URL: http://codereview.chromium.org/650144 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@39629 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
ropik/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,ropik/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,adobe/chromium
1711e5c0d145367f9bcd2cba9f1ce2f8da51d8c0
stan/math/opencl/opencl_context.hpp
stan/math/opencl/opencl_context.hpp
#ifndef STAN_MATH_OPENCL_OPENCL_CONTEXT_HPP #define STAN_MATH_OPENCL_OPENCL_CONTEXT_HPP #ifdef STAN_OPENCL #define __CL_ENABLE_EXCEPTIONS #define DEVICE_FILTER CL_DEVICE_TYPE_ALL #ifndef OPENCL_DEVICE_ID #error OPENCL_DEVICE_ID_NOT_SET #endif #ifndef OPENCL_PLATFORM_ID #error OPENCL_PLATFORM_ID_NOT_SET #endif #include <stan/math/prim/arr/err/check_opencl.hpp> #include <stan/math/opencl/constants.hpp> #include <stan/math/prim/scal/err/system_error.hpp> #include <CL/cl.hpp> #include <string> #include <iostream> #include <fstream> #include <map> #include <vector> #include <cmath> #include <cerrno> /** * @file stan/math/opencl/opencl_context.hpp * @brief Initialization for OpenCL: * 1. create context * 2. Find OpenCL platforms and devices available * 3. set up command queue * 4. set architecture dependent kernel parameters */ namespace stan { namespace math { namespace opencl { /** * A helper function to convert an array to a cl::size_t<N>. * * @param the input array to be converted * @return the cl::size_t<N> converted from the input array */ template <int N> auto to_size_t(const size_t (&values)[N]) { cl::size_t<N> s; for (size_t i = 0; i < N; i++) s[i] = values[i]; return s; } } // namespace opencl /** * The <code>opencl_context_base</code> class represents an OpenCL context * in the standard Meyers singleton design pattern. * * See the OpenCL specification glossary for a list of terms: * https://www.khronos.org/registry/OpenCL/specs/opencl-1.2.pdf. * The context includes the set of devices available on the host, command * queues, manages kernels. * * This is designed so there's only one instance running on the host. * * Some design decisions that may need to be addressed later: * - we are assuming a single OpenCL platform. We may want to run on multiple * platforms simulatenously * - we are assuming a single OpenCL device. We may want to run on multiple * devices simulatenously */ class opencl_context_base { friend class opencl_context; private: /** * Construct the opencl_context by initializing the * OpenCL context, devices, command queues, and kernel * groups. * * This constructor does the following: * 1. Gets the available platforms and selects the platform * with id OPENCL_PLATFORM_ID. * 2. Gets the available devices and selects the device with id * OPENCL_DEVICE_ID. * 3. Creates the OpenCL context with the device. * 4. Creates the OpenCL command queue for the selected device. * 5. Sets OpenCL device dependent kernel parameters * @throw std::system_error if an OpenCL error occurs. */ opencl_context_base() { try { // platform cl::Platform::get(&platforms_); if (OPENCL_PLATFORM_ID >= platforms_.size()) { system_error("OpenCL Initialization", "[Platform]", -1, "CL_INVALID_PLATFORM"); } platform_ = platforms_[OPENCL_PLATFORM_ID]; platform_name_ = platform_.getInfo<CL_PLATFORM_NAME>(); platform_.getDevices(DEVICE_FILTER, &devices_); if (devices_.size() == 0) { system_error("OpenCL Initialization", "[Device]", -1, "CL_DEVICE_NOT_FOUND"); } if (OPENCL_DEVICE_ID >= devices_.size()) { system_error("OpenCL Initialization", "[Device]", -1, "CL_INVALID_DEVICE"); } device_ = devices_[OPENCL_DEVICE_ID]; // context and queue context_ = cl::Context(device_); command_queue_ = cl::CommandQueue(context_, device_, CL_QUEUE_PROFILING_ENABLE, nullptr); device_.getInfo<size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE, &max_thread_block_size_); int thread_block_size_sqrt = static_cast<int>(sqrt(static_cast<double>(max_thread_block_size_))); // Does a compile time check of the maximum allowed // dimension of a square thread block size // WG size of (32,32) works on all recent GPUs but would fail on some // older integrated GPUs or CPUs if (thread_block_size_sqrt < base_opts_["THREAD_BLOCK_SIZE"]) { base_opts_["THREAD_BLOCK_SIZE"] = thread_block_size_sqrt; base_opts_["WORK_PER_THREAD"] = 1; } // Thread block size for the Cholesky // TODO(Steve): This should be tuned in a higher part of the stan language if (max_thread_block_size_ >= 256) { tuning_opts_.cholesky_min_L11_size = 256; } else { tuning_opts_.cholesky_min_L11_size = max_thread_block_size_; } } catch (const cl::Error& e) { check_opencl_error("opencl_context", e); } } protected: cl::Context context_; // Manages the the device, queue, platform, memory,etc. cl::CommandQueue command_queue_; // job queue for device, one per device std::vector<cl::Platform> platforms_; // Vector of available platforms cl::Platform platform_; // The platform for compiling kernels std::string platform_name_; // The platform such as NVIDIA OpenCL or AMD SDK std::vector<cl::Device> devices_; // All available OpenCL devices cl::Device device_; // The selected OpenCL device std::string device_name_; // The name of OpenCL device size_t max_thread_block_size_; // The maximum size of a block of workers on // the device // Holds Default parameter values for each Kernel. typedef std::map<const char*, int> map_base_opts; map_base_opts base_opts_ = {{"LOWER", static_cast<int>(TriangularViewCL::Lower)}, {"UPPER", static_cast<int>(TriangularViewCL::Upper)}, {"ENTIRE", static_cast<int>(TriangularViewCL::Entire)}, {"UPPER_TO_LOWER", static_cast<int>(TriangularMapCL::UpperToLower)}, {"LOWER_TO_UPPER", static_cast<int>(TriangularMapCL::LowerToUpper)}, {"THREAD_BLOCK_SIZE", 32}, {"WORK_PER_THREAD", 8}}; // TODO(Steve): Make these tunable during warmup struct tuning_struct { // Used in stan/math/opencl/cholesky_decompose int cholesky_min_L11_size = 256; int cholesky_partition = 4; int cholesky_size_worth_transfer = 1250; // Used in math/rev/mat/fun/cholesky_decompose int cholesky_rev_min_block_size = 512; int cholesky_rev_block_partition = 8; } tuning_opts_; static opencl_context_base& getInstance() { static opencl_context_base instance_; return instance_; } opencl_context_base(opencl_context_base const&) = delete; void operator=(opencl_context_base const&) = delete; }; /** * The API to access the methods and values in opencl_context_base */ class opencl_context { public: opencl_context() = default; /** * Returns the description of the OpenCL platform and device that is used. * Devices will be an OpenCL and Platforms are a specific OpenCL implimenation * such as AMD SDK's or Nvidia's OpenCL implimentation. */ inline std::string description() const { std::ostringstream msg; msg << "Platform ID: " << OPENCL_DEVICE_ID << "\n"; msg << "Platform Name: " << opencl_context_base::getInstance() .platform_.getInfo<CL_PLATFORM_NAME>() << "\n"; msg << "Platform Vendor: " << opencl_context_base::getInstance() .platform_.getInfo<CL_PLATFORM_VENDOR>() << "\n"; msg << "\tDevice " << OPENCL_DEVICE_ID << ": " << "\n"; msg << "\t\tDevice Name: " << opencl_context_base::getInstance().device_.getInfo<CL_DEVICE_NAME>() << "\n"; msg << "\t\tDevice Type: " << opencl_context_base::getInstance().device_.getInfo<CL_DEVICE_TYPE>() << "\n"; msg << "\t\tDevice Vendor: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_VENDOR>() << "\n"; msg << "\t\tDevice Max Compute Units: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>() << "\n"; msg << "\t\tDevice Global Memory: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Max Clock Frequency: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_MAX_CLOCK_FREQUENCY>() << "\n"; msg << "\t\tDevice Max Allocateable Memory: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>() << "\n"; msg << "\t\tDevice Local Memory: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Available: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_AVAILABLE>() << "\n"; return msg.str(); } /** * Returns the description of the OpenCL platforms and devices that * are available. Devices will be an OpenCL and Platforms are a specific * OpenCL implimenation such as AMD SDK's or Nvidia's OpenCL implimentation. */ inline std::string capabilities() const { std::vector<cl::Platform> all_platforms; cl::Platform::get(&all_platforms); std::ostringstream msg; int platform_id = 0; int device_id = 0; msg << "Number of Platforms: " << all_platforms.size() << "\n"; for (auto plat_iter : all_platforms) { cl::Platform platform(plat_iter); msg << "Platform ID: " << platform_id++ << "\n"; msg << "Platform Name: " << platform.getInfo<CL_PLATFORM_NAME>() << "\n"; msg << "Platform Vendor: " << platform.getInfo<CL_PLATFORM_VENDOR>() << "\n"; try { std::vector<cl::Device> all_devices; platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices); for (auto device_iter : all_devices) { cl::Device device(device_iter); msg << "\tDevice " << device_id++ << ": " << "\n"; msg << "\t\tDevice Name: " << device.getInfo<CL_DEVICE_NAME>() << "\n"; msg << "\t\tDevice Type: " << device.getInfo<CL_DEVICE_TYPE>() << "\n"; msg << "\t\tDevice Vendor: " << device.getInfo<CL_DEVICE_VENDOR>() << "\n"; msg << "\t\tDevice Max Compute Units: " << device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>() << "\n"; msg << "\t\tDevice Global Memory: " << device.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Max Clock Frequency: " << device.getInfo<CL_DEVICE_MAX_CLOCK_FREQUENCY>() << "\n"; msg << "\t\tDevice Max Allocateable Memory: " << device.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>() << "\n"; msg << "\t\tDevice Local Memory: " << device.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Available: " << device.getInfo<CL_DEVICE_AVAILABLE>() << "\n"; } } catch (const cl::Error& e) { // if one of the platforms have no devices that match the device type // it will throw the error == -1 (DEVICE_NOT_FOUND) // other errors will throw a system error if (e.err() == -1) { msg << "\tno (OpenCL) devices in the platform with ID " << platform_id << "\n"; } else { check_opencl_error("capabilities", e); } } } return msg.str(); } /** * Returns the reference to the OpenCL context. The OpenCL context manages * objects such as the device, memory, command queue, program, and kernel * objects. For stan, there should only be one context, queue, device, and * program with multiple kernels. */ inline cl::Context& context() { return opencl_context_base::getInstance().context_; } /** * Returns the reference to the active OpenCL command queue for the device. * One command queue will exist per device where * kernels are placed on the command queue and by default executed in order. */ inline cl::CommandQueue& queue() { return opencl_context_base::getInstance().command_queue_; } /** * Returns a copy of the map of kernel defines */ inline opencl_context_base::map_base_opts base_opts() { return opencl_context_base::getInstance().base_opts_; } /** * Returns the maximum thread block size defined by * CL_DEVICE_MAX_WORK_GROUP_SIZE for the device in the context. This is the * maximum product of thread block dimensions for a particular device. IE a * max workgoup of 256 would allow thread blocks of sizes (16,16), (128,2), * (8, 32), etc. */ inline int max_thread_block_size() { return opencl_context_base::getInstance().max_thread_block_size_; } /** * Returns the thread block size for the Cholesky Decompositions L_11. */ inline opencl_context_base::tuning_struct& tuning_opts() { return opencl_context_base::getInstance().tuning_opts_; } /** * Returns a vector containing the OpenCL device used to create the context */ inline std::vector<cl::Device> device() { return {opencl_context_base::getInstance().device_}; } /** * Returns a vector containing the OpenCL platform used to create the context */ inline std::vector<cl::Platform> platform() { return {opencl_context_base::getInstance().platform_}; } }; static opencl_context opencl_context; } // namespace math } // namespace stan #endif #endif
#ifndef STAN_MATH_OPENCL_OPENCL_CONTEXT_HPP #define STAN_MATH_OPENCL_OPENCL_CONTEXT_HPP #ifdef STAN_OPENCL #define __CL_ENABLE_EXCEPTIONS #define DEVICE_FILTER CL_DEVICE_TYPE_ALL #ifndef OPENCL_DEVICE_ID #error OPENCL_DEVICE_ID_NOT_SET #endif #ifndef OPENCL_PLATFORM_ID #error OPENCL_PLATFORM_ID_NOT_SET #endif #include <stan/math/prim/arr/err/check_opencl.hpp> #include <stan/math/opencl/constants.hpp> #include <stan/math/prim/scal/err/system_error.hpp> #include <CL/cl.hpp> #include <string> #include <iostream> #include <fstream> #include <map> #include <vector> #include <cmath> #include <cerrno> /** * @file stan/math/opencl/opencl_context.hpp * @brief Initialization for OpenCL: * 1. create context * 2. Find OpenCL platforms and devices available * 3. set up command queue * 4. set architecture dependent kernel parameters */ namespace stan { namespace math { namespace opencl { /** * A helper function to convert an array to a cl::size_t<N>. * * @param values the input array to be converted * @return the cl::size_t<N> converted from the input array */ template <int N> auto to_size_t(const size_t (&values)[N]) { cl::size_t<N> s; for (size_t i = 0; i < N; i++) s[i] = values[i]; return s; } } // namespace opencl /** * The <code>opencl_context_base</code> class represents an OpenCL context * in the standard Meyers singleton design pattern. * * See the OpenCL specification glossary for a list of terms: * https://www.khronos.org/registry/OpenCL/specs/opencl-1.2.pdf. * The context includes the set of devices available on the host, command * queues, manages kernels. * * This is designed so there's only one instance running on the host. * * Some design decisions that may need to be addressed later: * - we are assuming a single OpenCL platform. We may want to run on multiple * platforms simulatenously * - we are assuming a single OpenCL device. We may want to run on multiple * devices simulatenously */ class opencl_context_base { friend class opencl_context; private: /** * Construct the opencl_context by initializing the * OpenCL context, devices, command queues, and kernel * groups. * * This constructor does the following: * 1. Gets the available platforms and selects the platform * with id OPENCL_PLATFORM_ID. * 2. Gets the available devices and selects the device with id * OPENCL_DEVICE_ID. * 3. Creates the OpenCL context with the device. * 4. Creates the OpenCL command queue for the selected device. * 5. Sets OpenCL device dependent kernel parameters * @throw std::system_error if an OpenCL error occurs. */ opencl_context_base() { try { // platform cl::Platform::get(&platforms_); if (OPENCL_PLATFORM_ID >= platforms_.size()) { system_error("OpenCL Initialization", "[Platform]", -1, "CL_INVALID_PLATFORM"); } platform_ = platforms_[OPENCL_PLATFORM_ID]; platform_name_ = platform_.getInfo<CL_PLATFORM_NAME>(); platform_.getDevices(DEVICE_FILTER, &devices_); if (devices_.size() == 0) { system_error("OpenCL Initialization", "[Device]", -1, "CL_DEVICE_NOT_FOUND"); } if (OPENCL_DEVICE_ID >= devices_.size()) { system_error("OpenCL Initialization", "[Device]", -1, "CL_INVALID_DEVICE"); } device_ = devices_[OPENCL_DEVICE_ID]; // context and queue context_ = cl::Context(device_); command_queue_ = cl::CommandQueue(context_, device_, CL_QUEUE_PROFILING_ENABLE, nullptr); device_.getInfo<size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE, &max_thread_block_size_); int thread_block_size_sqrt = static_cast<int>(sqrt(static_cast<double>(max_thread_block_size_))); // Does a compile time check of the maximum allowed // dimension of a square thread block size // WG size of (32,32) works on all recent GPUs but would fail on some // older integrated GPUs or CPUs if (thread_block_size_sqrt < base_opts_["THREAD_BLOCK_SIZE"]) { base_opts_["THREAD_BLOCK_SIZE"] = thread_block_size_sqrt; base_opts_["WORK_PER_THREAD"] = 1; } // Thread block size for the Cholesky // TODO(Steve): This should be tuned in a higher part of the stan language if (max_thread_block_size_ >= 256) { tuning_opts_.cholesky_min_L11_size = 256; } else { tuning_opts_.cholesky_min_L11_size = max_thread_block_size_; } } catch (const cl::Error& e) { check_opencl_error("opencl_context", e); } } protected: cl::Context context_; // Manages the the device, queue, platform, memory,etc. cl::CommandQueue command_queue_; // job queue for device, one per device std::vector<cl::Platform> platforms_; // Vector of available platforms cl::Platform platform_; // The platform for compiling kernels std::string platform_name_; // The platform such as NVIDIA OpenCL or AMD SDK std::vector<cl::Device> devices_; // All available OpenCL devices cl::Device device_; // The selected OpenCL device std::string device_name_; // The name of OpenCL device size_t max_thread_block_size_; // The maximum size of a block of workers on // the device // Holds Default parameter values for each Kernel. typedef std::map<const char*, int> map_base_opts; map_base_opts base_opts_ = {{"LOWER", static_cast<int>(TriangularViewCL::Lower)}, {"UPPER", static_cast<int>(TriangularViewCL::Upper)}, {"ENTIRE", static_cast<int>(TriangularViewCL::Entire)}, {"UPPER_TO_LOWER", static_cast<int>(TriangularMapCL::UpperToLower)}, {"LOWER_TO_UPPER", static_cast<int>(TriangularMapCL::LowerToUpper)}, {"THREAD_BLOCK_SIZE", 32}, {"WORK_PER_THREAD", 8}}; // TODO(Steve): Make these tunable during warmup struct tuning_struct { // Used in stan/math/opencl/cholesky_decompose int cholesky_min_L11_size = 256; int cholesky_partition = 4; int cholesky_size_worth_transfer = 1250; // Used in math/rev/mat/fun/cholesky_decompose int cholesky_rev_min_block_size = 512; int cholesky_rev_block_partition = 8; } tuning_opts_; static opencl_context_base& getInstance() { static opencl_context_base instance_; return instance_; } opencl_context_base(opencl_context_base const&) = delete; void operator=(opencl_context_base const&) = delete; }; /** * The API to access the methods and values in opencl_context_base */ class opencl_context { public: opencl_context() = default; /** * Returns the description of the OpenCL platform and device that is used. * Devices will be an OpenCL and Platforms are a specific OpenCL implimenation * such as AMD SDK's or Nvidia's OpenCL implimentation. */ inline std::string description() const { std::ostringstream msg; msg << "Platform ID: " << OPENCL_DEVICE_ID << "\n"; msg << "Platform Name: " << opencl_context_base::getInstance() .platform_.getInfo<CL_PLATFORM_NAME>() << "\n"; msg << "Platform Vendor: " << opencl_context_base::getInstance() .platform_.getInfo<CL_PLATFORM_VENDOR>() << "\n"; msg << "\tDevice " << OPENCL_DEVICE_ID << ": " << "\n"; msg << "\t\tDevice Name: " << opencl_context_base::getInstance().device_.getInfo<CL_DEVICE_NAME>() << "\n"; msg << "\t\tDevice Type: " << opencl_context_base::getInstance().device_.getInfo<CL_DEVICE_TYPE>() << "\n"; msg << "\t\tDevice Vendor: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_VENDOR>() << "\n"; msg << "\t\tDevice Max Compute Units: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>() << "\n"; msg << "\t\tDevice Global Memory: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Max Clock Frequency: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_MAX_CLOCK_FREQUENCY>() << "\n"; msg << "\t\tDevice Max Allocateable Memory: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>() << "\n"; msg << "\t\tDevice Local Memory: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Available: " << opencl_context_base::getInstance() .device_.getInfo<CL_DEVICE_AVAILABLE>() << "\n"; return msg.str(); } /** * Returns the description of the OpenCL platforms and devices that * are available. Devices will be an OpenCL and Platforms are a specific * OpenCL implimenation such as AMD SDK's or Nvidia's OpenCL implimentation. */ inline std::string capabilities() const { std::vector<cl::Platform> all_platforms; cl::Platform::get(&all_platforms); std::ostringstream msg; int platform_id = 0; int device_id = 0; msg << "Number of Platforms: " << all_platforms.size() << "\n"; for (auto plat_iter : all_platforms) { cl::Platform platform(plat_iter); msg << "Platform ID: " << platform_id++ << "\n"; msg << "Platform Name: " << platform.getInfo<CL_PLATFORM_NAME>() << "\n"; msg << "Platform Vendor: " << platform.getInfo<CL_PLATFORM_VENDOR>() << "\n"; try { std::vector<cl::Device> all_devices; platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices); for (auto device_iter : all_devices) { cl::Device device(device_iter); msg << "\tDevice " << device_id++ << ": " << "\n"; msg << "\t\tDevice Name: " << device.getInfo<CL_DEVICE_NAME>() << "\n"; msg << "\t\tDevice Type: " << device.getInfo<CL_DEVICE_TYPE>() << "\n"; msg << "\t\tDevice Vendor: " << device.getInfo<CL_DEVICE_VENDOR>() << "\n"; msg << "\t\tDevice Max Compute Units: " << device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>() << "\n"; msg << "\t\tDevice Global Memory: " << device.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Max Clock Frequency: " << device.getInfo<CL_DEVICE_MAX_CLOCK_FREQUENCY>() << "\n"; msg << "\t\tDevice Max Allocateable Memory: " << device.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>() << "\n"; msg << "\t\tDevice Local Memory: " << device.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>() << "\n"; msg << "\t\tDevice Available: " << device.getInfo<CL_DEVICE_AVAILABLE>() << "\n"; } } catch (const cl::Error& e) { // if one of the platforms have no devices that match the device type // it will throw the error == -1 (DEVICE_NOT_FOUND) // other errors will throw a system error if (e.err() == -1) { msg << "\tno (OpenCL) devices in the platform with ID " << platform_id << "\n"; } else { check_opencl_error("capabilities", e); } } } return msg.str(); } /** * Returns the reference to the OpenCL context. The OpenCL context manages * objects such as the device, memory, command queue, program, and kernel * objects. For stan, there should only be one context, queue, device, and * program with multiple kernels. */ inline cl::Context& context() { return opencl_context_base::getInstance().context_; } /** * Returns the reference to the active OpenCL command queue for the device. * One command queue will exist per device where * kernels are placed on the command queue and by default executed in order. */ inline cl::CommandQueue& queue() { return opencl_context_base::getInstance().command_queue_; } /** * Returns a copy of the map of kernel defines */ inline opencl_context_base::map_base_opts base_opts() { return opencl_context_base::getInstance().base_opts_; } /** * Returns the maximum thread block size defined by * CL_DEVICE_MAX_WORK_GROUP_SIZE for the device in the context. This is the * maximum product of thread block dimensions for a particular device. IE a * max workgoup of 256 would allow thread blocks of sizes (16,16), (128,2), * (8, 32), etc. */ inline int max_thread_block_size() { return opencl_context_base::getInstance().max_thread_block_size_; } /** * Returns the thread block size for the Cholesky Decompositions L_11. */ inline opencl_context_base::tuning_struct& tuning_opts() { return opencl_context_base::getInstance().tuning_opts_; } /** * Returns a vector containing the OpenCL device used to create the context */ inline std::vector<cl::Device> device() { return {opencl_context_base::getInstance().device_}; } /** * Returns a vector containing the OpenCL platform used to create the context */ inline std::vector<cl::Platform> platform() { return {opencl_context_base::getInstance().platform_}; } }; static opencl_context opencl_context; } // namespace math } // namespace stan #endif #endif
comment fix
comment fix
C++
bsd-3-clause
stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math
84fc392309316172c21f7af0de2dbc4d50b66712
compiler/src/iree/compiler/Codegen/SPIRV/SPIRVTile.cpp
compiler/src/iree/compiler/Codegen/SPIRV/SPIRVTile.cpp
// Copyright 2021 The IREE Authors // // Licensed 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 //===- SPIRVTile.cpp ------------------------------------------------------===// // // This pass tiles and Linalg ops with tensor semantics to invocations. // //===----------------------------------------------------------------------===// #include "iree-dialects/Dialect/LinalgExt/IR/LinalgExtOps.h" #include "iree-dialects/Dialect/LinalgExt/Transforms/Transforms.h" #include "iree/compiler/Codegen/Dialect/LoweringConfig.h" #include "iree/compiler/Codegen/PassDetail.h" #include "iree/compiler/Codegen/Passes.h" #include "iree/compiler/Codegen/SPIRV/Utils.h" #include "iree/compiler/Codegen/Utils/GPUUtils.h" #include "iree/compiler/Codegen/Utils/MarkerUtils.h" #include "iree/compiler/Dialect/Flow/IR/FlowOps.h" #include "llvm/Support/Debug.h" #include "mlir/Dialect/Affine/IR/AffineOps.h" #include "mlir/Dialect/Arith/IR/Arith.h" #include "mlir/Dialect/Linalg/IR/Linalg.h" #include "mlir/Dialect/Linalg/Transforms/Transforms.h" #include "mlir/Dialect/SCF/IR/SCF.h" #include "mlir/Dialect/SCF/Transforms/Transforms.h" #include "mlir/Dialect/SCF/Utils/Utils.h" #include "mlir/Dialect/Tensor/IR/Tensor.h" #include "mlir/Dialect/Tensor/Transforms/Transforms.h" #include "mlir/IR/Matchers.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" using mlir::iree_compiler::IREE::LinalgExt::TilingPatterns; #define DEBUG_TYPE "iree-spirv-tile" namespace mlir { namespace iree_compiler { //===----------------------------------------------------------------------===// // Tiling patterns //===----------------------------------------------------------------------===// /// Populates `patterns` with patterns that tiles convolution/matmul ops with /// markers. static void populateTilingReductionPatterns(RewritePatternSet &patterns) { MLIRContext *context = patterns.getContext(); auto getTileSizeFn = [&](OpBuilder &builder, Operation *op) { return getTileSizes(builder, op, 2); }; auto tilingOptions = linalg::LinalgTilingOptions() .setLoopType(linalg::LinalgTilingLoopType::Loops) .setTileSizeComputationFunction(getTileSizeFn); auto marker = StringAttr::get(context, getTileReductionMarker()); auto filter = linalg::LinalgTransformationFilter({marker}, llvm::None); TilingPatterns<linalg::BatchMatmulOp, linalg::Conv2DNchwFchwOp, linalg::Conv2DNhwcHwcfOp, linalg::DepthwiseConv2DNhwcHwcOp, linalg::GenericOp, linalg::MatmulOp>::insert(patterns, tilingOptions, filter); } //===----------------------------------------------------------------------===// // Main pass //===----------------------------------------------------------------------===// namespace { class SPIRVTilePass final : public SPIRVTileBase<SPIRVTilePass> { public: SPIRVTilePass() = default; SPIRVTilePass(const SPIRVTilePass &pass) = default; void runOnOperation() override { MLIRContext *context = &getContext(); func::FuncOp funcOp = getOperation(); // Try to find computation ops which we will use as anchor to tile and fuse // again. If there are `scf.if` ops, we have both a fast and slow paths for // padding handling. Then we need to scan both regions to discover such // computation ops so that we can tile and fuse both regions. SmallVector<Operation *> computeOps; SmallVector<scf::IfOp, 1> ifOps; funcOp.walk([&ifOps](scf::IfOp ifOp) { ifOps.push_back(ifOp); }); if (ifOps.empty()) { if (failed(getComputeOps(funcOp, computeOps))) { funcOp.emitOpError("does not contain compute ops"); return signalPassFailure(); } while (computeOps.size() > 1) computeOps.erase(computeOps.begin()); } else { if (ifOps.size() > 1) { funcOp.emitError("expected to contain no more than one scf.if ops"); return signalPassFailure(); } for (Operation &op : llvm::reverse(*ifOps.front().thenBlock())) { if (isa<linalg::LinalgOp, TilingInterface>(op)) { computeOps.push_back(&op); break; } } if (Block *elseBlock = ifOps.front().elseBlock()) { for (Operation &op : llvm::reverse(*elseBlock)) { if (isa<linalg::LinalgOp, TilingInterface>(op)) { computeOps.push_back(&op); break; } } } } assert(computeOps.size() <= 2); // Now tile the last computation op to invocations and fuse all operand // computation ops into the materialized loop nest. for (Operation *computeOp : computeOps) { auto consumerOp = dyn_cast<linalg::LinalgOp>(computeOp); OpBuilder builder(context); SmallVector<int64_t> tileSizes = getTileSizes(consumerOp, 1); auto identityLoopOrder = llvm::to_vector<4>(llvm::seq<int64_t>(0, tileSizes.size())); FailureOr<linalg::TileLoopNest> loopNest = linalg::tileConsumerAndFuseProducers(builder, consumerOp, tileSizes, identityLoopOrder, llvm::None); if (failed(loopNest)) { consumerOp.emitOpError("failed tiling and fusing producers"); return signalPassFailure(); } consumerOp->replaceAllUsesWith(loopNest->getRootOpReplacementResults()); // We don't distribute here; instead, it will be done in a later step // after bufferization. So add attributes to the tiled loop nest to // indicate that they should be distributed to invocations. ArrayRef<scf::ForOp> loops = loopNest->getLoopOps(); assert(loops.size() <= kNumGPUDims); const char *attrName = getSPIRVDistributeAttrName(); for (int i = loops.size() - 1, dim = 0; i >= 0; --i) { loops[i]->setAttr(attrName, builder.getIndexAttr(dim++)); } } LLVM_DEBUG({ llvm::dbgs() << "--- After tiling to invocations ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); { // Fuse `tensor.pad` op inside the materalized loop nest too. RewritePatternSet patterns(context); patterns.insert<linalg::ExtractSliceOfPadTensorSwapPattern>( context, [](tensor::ExtractSliceOp) { return false; }); (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); LLVM_DEBUG({ llvm::dbgs() << "--- After fusing padding into consumers ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); } { RewritePatternSet patterns(context); populateConcretizePadResultShapePatterns(context, patterns); (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); LLVM_DEBUG({ llvm::dbgs() << "--- After tiling canonicalization ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); } { // Set markers to drive tiling reduction dimensions. OpBuilder builder(context); auto marker = builder.getStringAttr(getTileReductionMarker()); funcOp.walk([&](linalg::LinalgOp op) { if (isa<linalg::ContractionOpInterface>(*op) || isa<linalg::ConvolutionOpInterface>(*op) || isa<linalg::GenericOp>(*op)) { op->setAttr(linalg::LinalgTransforms::kLinalgTransformMarker, marker); } }); } { // Tile reduction dimensions. RewritePatternSet tilingPatterns(context); populateTilingReductionPatterns(tilingPatterns); if (failed(applyPatternsAndFoldGreedily(funcOp, std::move(tilingPatterns)))) { funcOp.emitError("failed tiling reduction dimensions"); return signalPassFailure(); } LLVM_DEBUG({ llvm::dbgs() << "--- After tiling reduction dimensions ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); } { // Fuse `tensor.pad` op inside the materalized loop nest too. RewritePatternSet patterns(context); patterns.insert<linalg::ExtractSliceOfPadTensorSwapPattern>( context, [](tensor::ExtractSliceOp) { return false; }); (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); LLVM_DEBUG({ llvm::dbgs() << "--- After fusing padding into consumers ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); } { // Tile convolution output window dimension by 1 to prepare downsizing. SmallVector<linalg::ConvolutionOpInterface, 1> convOps; funcOp.walk([&convOps](linalg::ConvolutionOpInterface convOp) { convOps.push_back(convOp); }); for (linalg::ConvolutionOpInterface convOp : convOps) { auto consumerOp = cast<linalg::LinalgOp>(*convOp); OpBuilder builder(context); SmallVector<int64_t> tileSizes = getTileSizes(consumerOp, 3); auto identityLoopOrder = llvm::to_vector<4>(llvm::seq<int64_t>(0, tileSizes.size())); FailureOr<linalg::TileLoopNest> loopNest = linalg::tileConsumerAndFuseProducers(builder, consumerOp, tileSizes, identityLoopOrder, llvm::None); if (failed(loopNest)) { consumerOp.emitOpError("failed tiling and fusing producers"); return signalPassFailure(); } consumerOp->replaceAllUsesWith(loopNest->getRootOpReplacementResults()); // Fully unroll the generated loop. This allows us to remove the loop // for parallel output window dimension, so it helps future vector // transformations. if (!loopNest->getLoopOps().empty()) { assert(loopNest->getLoopOps().size() == 1); scf::ForOp loopOp = loopNest->getLoopOps().front(); IntegerAttr ub; if (!matchPattern(loopOp.getUpperBound(), m_Constant(&ub))) { loopOp.emitOpError("upper bound should be a constant"); return signalPassFailure(); } if (failed(mlir::loopUnrollByFactor(loopOp, ub.getInt()))) { loopOp.emitOpError("failed unrolling by factor 1"); return signalPassFailure(); } } LLVM_DEBUG({ llvm::dbgs() << "--- After tiling convolution output window ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); } } { RewritePatternSet patterns(context); populateConcretizePadResultShapePatterns(context, patterns); (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); LLVM_DEBUG({ llvm::dbgs() << "--- After tiling canonicalization ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); } { // Downsize n-D (n > 1) convolutions to 1-D. RewritePatternSet patterns(context); linalg::populateDecomposeConvolutionPatterns(patterns); // Downsizing creates consecutive extract/insert slice ops. Merge them. tensor::populateMergeConsecutiveInsertExtractSlicePatterns(patterns); // Pull in patterns to fold constant insert/extract slice op parameters. tensor::InsertSliceOp::getCanonicalizationPatterns(patterns, context); tensor::ExtractSliceOp::getCanonicalizationPatterns(patterns, context); // Pull in scf.for op canonicalization patterns to help hoisting across // multiple loops and remove loop carried values unused in the body. scf::ForOp::getCanonicalizationPatterns(patterns, context); (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); LLVM_DEBUG({ llvm::dbgs() << "--- After Downsizing N-D convolution to 1-D ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); } } }; } // namespace std::unique_ptr<OperationPass<func::FuncOp>> createSPIRVTilePass() { return std::make_unique<SPIRVTilePass>(); } } // namespace iree_compiler } // namespace mlir
// Copyright 2021 The IREE Authors // // Licensed 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 //===- SPIRVTile.cpp ------------------------------------------------------===// // // This pass tiles and Linalg ops with tensor semantics to invocations. // //===----------------------------------------------------------------------===// #include "iree-dialects/Dialect/LinalgExt/IR/LinalgExtOps.h" #include "iree-dialects/Dialect/LinalgExt/Transforms/Transforms.h" #include "iree/compiler/Codegen/Dialect/LoweringConfig.h" #include "iree/compiler/Codegen/PassDetail.h" #include "iree/compiler/Codegen/Passes.h" #include "iree/compiler/Codegen/SPIRV/Utils.h" #include "iree/compiler/Codegen/Utils/GPUUtils.h" #include "iree/compiler/Codegen/Utils/MarkerUtils.h" #include "iree/compiler/Dialect/Flow/IR/FlowOps.h" #include "llvm/Support/Debug.h" #include "mlir/Dialect/Affine/IR/AffineOps.h" #include "mlir/Dialect/Arith/IR/Arith.h" #include "mlir/Dialect/Linalg/IR/Linalg.h" #include "mlir/Dialect/Linalg/Transforms/Transforms.h" #include "mlir/Dialect/SCF/IR/SCF.h" #include "mlir/Dialect/SCF/Transforms/Transforms.h" #include "mlir/Dialect/SCF/Utils/Utils.h" #include "mlir/Dialect/Tensor/IR/Tensor.h" #include "mlir/Dialect/Tensor/Transforms/Transforms.h" #include "mlir/IR/Matchers.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" using mlir::iree_compiler::IREE::LinalgExt::TilingPatterns; #define DEBUG_TYPE "iree-spirv-tile" namespace mlir { namespace iree_compiler { //===----------------------------------------------------------------------===// // Tiling and fusion utilities //===----------------------------------------------------------------------===// /// Collects computation ops which we will use as anchor to tile and fuse. static LogicalResult collectComputeOps( func::FuncOp funcOp, SmallVectorImpl<Operation *> &computeOps) { // If there are `scf.if` ops, we have both a fast and slow paths for // padding handling. Then we need to scan both regions to discover such // computation ops so that we can tile and fuse both regions. SmallVector<scf::IfOp, 1> ifOps; funcOp.walk([&ifOps](scf::IfOp ifOp) { ifOps.push_back(ifOp); }); if (ifOps.empty()) { if (failed(getComputeOps(funcOp, computeOps))) { return funcOp.emitOpError("does not contain compute ops"); } while (computeOps.size() > 1) computeOps.erase(computeOps.begin()); return success(); } if (ifOps.size() > 1) { return funcOp.emitError("expected to contain no more than one scf.if ops"); } for (Operation &op : llvm::reverse(*ifOps.front().thenBlock())) { if (isa<linalg::LinalgOp, TilingInterface>(op)) { computeOps.push_back(&op); break; } } if (Block *elseBlock = ifOps.front().elseBlock()) { for (Operation &op : llvm::reverse(*elseBlock)) { if (isa<linalg::LinalgOp, TilingInterface>(op)) { computeOps.push_back(&op); break; } } } return success(); } static LogicalResult tileAndDistributeToThreads(linalg::LinalgOp consumerOp) { MLIRContext *context = consumerOp.getContext(); OpBuilder builder(context); SmallVector<int64_t> tileSizes = getTileSizes(consumerOp, 1); auto identityLoopOrder = llvm::to_vector<4>(llvm::seq<int64_t>(0, tileSizes.size())); FailureOr<linalg::TileLoopNest> loopNest = linalg::tileConsumerAndFuseProducers(builder, consumerOp, tileSizes, identityLoopOrder, llvm::None); if (failed(loopNest)) { return consumerOp.emitOpError("failed tiling and fusing producers"); } consumerOp->replaceAllUsesWith(loopNest->getRootOpReplacementResults()); // We don't distribute here; instead, it will be done in a later step // after bufferization. So add attributes to the tiled loop nest to // indicate that they should be distributed to invocations. ArrayRef<scf::ForOp> loops = loopNest->getLoopOps(); assert(loops.size() <= kNumGPUDims); const char *attrName = getSPIRVDistributeAttrName(); for (int i = loops.size() - 1, dim = 0; i >= 0; --i) { loops[i]->setAttr(attrName, builder.getIndexAttr(dim++)); } return success(); } /// Populates `patterns` with patterns that tiles convolution/matmul ops with /// markers. static void populateTilingReductionPatterns(RewritePatternSet &patterns) { MLIRContext *context = patterns.getContext(); auto getTileSizeFn = [&](OpBuilder &builder, Operation *op) { return getTileSizes(builder, op, 2); }; auto tilingOptions = linalg::LinalgTilingOptions() .setLoopType(linalg::LinalgTilingLoopType::Loops) .setTileSizeComputationFunction(getTileSizeFn); auto marker = StringAttr::get(context, getTileReductionMarker()); auto filter = linalg::LinalgTransformationFilter({marker}, llvm::None); TilingPatterns<linalg::BatchMatmulOp, linalg::Conv2DNchwFchwOp, linalg::Conv2DNhwcHwcfOp, linalg::DepthwiseConv2DNhwcHwcOp, linalg::GenericOp, linalg::MatmulOp>::insert(patterns, tilingOptions, filter); } /// Tiles reduction dimensions. static LogicalResult tileReduction(func::FuncOp funcOp) { MLIRContext *context = funcOp.getContext(); // Set markers to drive tiling reduction dimensions. OpBuilder builder(context); auto marker = builder.getStringAttr(getTileReductionMarker()); funcOp.walk([&](linalg::LinalgOp op) { if (isa<linalg::ContractionOpInterface>(*op) || isa<linalg::ConvolutionOpInterface>(*op) || isa<linalg::GenericOp>(*op)) { op->setAttr(linalg::LinalgTransforms::kLinalgTransformMarker, marker); } }); RewritePatternSet patterns(context); populateTilingReductionPatterns(patterns); if (failed(applyPatternsAndFoldGreedily(funcOp, std::move(patterns)))) { return funcOp.emitError("failed tiling reduction dimensions"); } LLVM_DEBUG({ llvm::dbgs() << "--- After tiling reduction dimensions ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); return success(); } /// Fuses `tensor.pad` ops into the the materalized loop nests containing /// their consumer ops. static void fusePadIntoConsumer(func::FuncOp funcOp) { MLIRContext *context = funcOp.getContext(); RewritePatternSet patterns(context); patterns.insert<linalg::ExtractSliceOfPadTensorSwapPattern>( context, [](tensor::ExtractSliceOp) { return false; }); (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); LLVM_DEBUG({ llvm::dbgs() << "--- After fusing padding into consumers ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); }; /// Concretizes `tensor.pad` ops' result shapes. static void concretizePadShape(func::FuncOp funcOp) { MLIRContext *context = funcOp.getContext(); RewritePatternSet patterns(context); populateConcretizePadResultShapePatterns(context, patterns); (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); LLVM_DEBUG({ llvm::dbgs() << "--- After concretizing pad result shape ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); } /// Tiles one of the convolution output window dimensions with size 1 to prepare /// for downsizing 2-D convolution ops into 1-D ones. static LogicalResult tileAndUnrollConvWindow(func::FuncOp funcOp) { SmallVector<linalg::ConvolutionOpInterface, 1> convOps; funcOp.walk([&convOps](linalg::ConvolutionOpInterface convOp) { convOps.push_back(convOp); }); for (linalg::ConvolutionOpInterface convOp : convOps) { auto consumerOp = cast<linalg::LinalgOp>(*convOp); OpBuilder builder(funcOp.getContext()); SmallVector<int64_t> tileSizes = getTileSizes(consumerOp, 3); auto identityLoopOrder = llvm::to_vector<4>(llvm::seq<int64_t>(0, tileSizes.size())); FailureOr<linalg::TileLoopNest> loopNest = linalg::tileConsumerAndFuseProducers(builder, consumerOp, tileSizes, identityLoopOrder, llvm::None); if (failed(loopNest)) { return consumerOp.emitOpError("failed tiling and fusing producers"); } consumerOp->replaceAllUsesWith(loopNest->getRootOpReplacementResults()); // Fully unroll the generated loop. This allows us to remove the loop // for parallel output window dimension, so it helps future vector // transformations. if (!loopNest->getLoopOps().empty()) { assert(loopNest->getLoopOps().size() == 1); scf::ForOp loopOp = loopNest->getLoopOps().front(); IntegerAttr ub; if (!matchPattern(loopOp.getUpperBound(), m_Constant(&ub))) { return loopOp.emitOpError("upper bound should be a constant"); } if (failed(mlir::loopUnrollByFactor(loopOp, ub.getInt()))) { return loopOp.emitOpError("failed unrolling by factor 1"); } } LLVM_DEBUG({ llvm::dbgs() << "--- After tiling convolution output window ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); } return success(); } //===----------------------------------------------------------------------===// // Main pass //===----------------------------------------------------------------------===// namespace { class SPIRVTilePass final : public SPIRVTileBase<SPIRVTilePass> { public: SPIRVTilePass() = default; SPIRVTilePass(const SPIRVTilePass &pass) = default; void runOnOperation() override { MLIRContext *context = &getContext(); func::FuncOp funcOp = getOperation(); // Try to find computation ops which we will use as anchor to tile and fuse. SmallVector<Operation *> computeOps; if (failed(collectComputeOps(funcOp, computeOps))) return signalPassFailure(); assert(computeOps.size() <= 2); // Now tile the last computation op to invocations and fuse all operand // computation ops into the materialized loop nest. for (Operation *computeOp : computeOps) { auto consumerOp = dyn_cast<linalg::LinalgOp>(computeOp); if (failed(tileAndDistributeToThreads(consumerOp))) return signalPassFailure(); } LLVM_DEBUG({ llvm::dbgs() << "--- After tiling to invocations ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); fusePadIntoConsumer(funcOp); concretizePadShape(funcOp); if (failed(tileReduction(funcOp))) return signalPassFailure(); fusePadIntoConsumer(funcOp); if (failed(tileAndUnrollConvWindow(funcOp))) return signalPassFailure(); concretizePadShape(funcOp); { // Downsize n-D (n > 1) convolutions to 1-D. RewritePatternSet patterns(context); linalg::populateDecomposeConvolutionPatterns(patterns); // Downsizing creates consecutive extract/insert slice ops. Merge them. tensor::populateMergeConsecutiveInsertExtractSlicePatterns(patterns); // Pull in patterns to fold constant insert/extract slice op parameters. tensor::InsertSliceOp::getCanonicalizationPatterns(patterns, context); tensor::ExtractSliceOp::getCanonicalizationPatterns(patterns, context); // Pull in scf.for op canonicalization patterns to help hoisting across // multiple loops and remove loop carried values unused in the body. scf::ForOp::getCanonicalizationPatterns(patterns, context); (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); LLVM_DEBUG({ llvm::dbgs() << "--- After Downsizing N-D convolution to 1-D ---\n"; funcOp.print(llvm::dbgs(), OpPrintingFlags().useLocalScope()); llvm::dbgs() << "\n\n"; }); } } }; } // namespace std::unique_ptr<OperationPass<func::FuncOp>> createSPIRVTilePass() { return std::make_unique<SPIRVTilePass>(); } } // namespace iree_compiler } // namespace mlir
Refactor SPIRVTilePass to be more readable (#10708)
[spirv] NFC: Refactor SPIRVTilePass to be more readable (#10708) Breaking down the long function into multiple smaller utility functions to make the logic clear and easier to read.
C++
apache-2.0
iree-org/iree,iree-org/iree,iree-org/iree,google/iree,iree-org/iree,google/iree,iree-org/iree,google/iree,iree-org/iree,google/iree,iree-org/iree,google/iree,google/iree,google/iree
325961e188cad2ab5966c1ae9bb8bdc6053e6ef3
test/test-organization-ts/datasets-test/test_case_interface-test.cpp
test/test-organization-ts/datasets-test/test_case_interface-test.cpp
// (C) Copyright Gennadiy Rozental 2011-2015. // 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) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : tests singleton dataset // *************************************************************************** // Boost.Test #include <boost/test/unit_test.hpp> #include <boost/test/data/test_case.hpp> #include <boost/test/data/monomorphic.hpp> namespace data=boost::unit_test::data; #include "datasets-test.hpp" //____________________________________________________________________________// int samples1[] = {1,2,3}; int index1 = 0; BOOST_DATA_TEST_CASE( test_case_interface_01, data::make({1,2,3}) ) { BOOST_TEST( sample == samples1[index1++] ); } //____________________________________________________________________________// std::vector<std::string> samples2 = {"qwerty","asdfg"}; int index2 = 0; BOOST_DATA_TEST_CASE( test_case_interface_02, samples2, str ) { BOOST_TEST( str == samples2[index2++] ); } //____________________________________________________________________________// int samples3[] = {7,9}; int index3 = 0; BOOST_DATA_TEST_CASE( test_case_interface_03, data::make({1,2,3}) + samples3, val ) { if( index3 < 3 ) BOOST_TEST( val == samples1[index3] ); else BOOST_TEST( val == samples3[index3-3] ); ++index3; } //____________________________________________________________________________// int index4 = 0; BOOST_DATA_TEST_CASE( test_case_interface_04, samples2 ^ data::make({7,9}), str, intval ) { BOOST_TEST( str == samples2[index4] ); BOOST_TEST( intval == samples3[index4] ); ++index4; } //____________________________________________________________________________// int index5 = 0; BOOST_DATA_TEST_CASE( test_case_interface_05, samples1 * samples2, sample0, sample1 ) { BOOST_TEST( sample0 == samples1[index5/2] ); BOOST_TEST( sample1 == samples2[index5%2] ); ++index5; } //____________________________________________________________________________// int index6 = 0; BOOST_DATA_TEST_CASE( test_case_interface_06, samples1 * samples2 * samples3, intval, str, val2 ) { BOOST_TEST( intval == samples1[index6/4] ); BOOST_TEST( str == samples2[(index6/2)%2] ); BOOST_TEST( val2 == samples3[index6%2] ); ++index6; } //____________________________________________________________________________// // EOF
// (C) Copyright Gennadiy Rozental 2011-2015. // 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) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : tests singleton dataset // *************************************************************************** // Boost.Test #include <boost/test/unit_test.hpp> #include <boost/test/data/test_case.hpp> #include <boost/test/data/monomorphic.hpp> namespace data=boost::unit_test::data; #include "datasets-test.hpp" //____________________________________________________________________________// int samples1[] = {1,2,3}; int index1 = 0; BOOST_DATA_TEST_CASE( test_case_interface_01, data::make({1,2,3}) ) { BOOST_TEST( sample == samples1[index1++] ); } //____________________________________________________________________________// std::vector<std::string> samples2 = {"qwerty","asdfg"}; int index2 = 0; BOOST_DATA_TEST_CASE( test_case_interface_02, samples2, str ) { BOOST_TEST( str == samples2[index2++] ); } //____________________________________________________________________________// int samples3[] = {7,9}; int index3 = 0; BOOST_DATA_TEST_CASE( test_case_interface_03, data::make({1,2,3}) + samples3, val ) { if( index3 < 3 ) BOOST_TEST( val == samples1[index3] ); else BOOST_TEST( val == samples3[index3-3] ); ++index3; } //____________________________________________________________________________// int index4 = 0; BOOST_DATA_TEST_CASE( test_case_interface_04, samples2 ^ data::make({7,9}), str, intval ) { BOOST_TEST( str == samples2[index4] ); BOOST_TEST( intval == samples3[index4] ); ++index4; } //____________________________________________________________________________// int index5 = 0; BOOST_DATA_TEST_CASE( test_case_interface_05, samples1 * samples2, sample0, sample1 ) { BOOST_TEST( sample0 == samples1[index5/2] ); BOOST_TEST( sample1 == samples2[index5%2] ); ++index5; } //____________________________________________________________________________// int index6 = 0; BOOST_DATA_TEST_CASE( test_case_interface_06, samples1 * samples2 * samples3, intval, str, val2 ) { BOOST_TEST( intval == samples1[index6/4] ); BOOST_TEST( str == samples2[(index6/2)%2] ); BOOST_TEST( val2 == samples3[index6%2] ); ++index6; } // EOF
work in progress
work in progress
C++
mit
nihildeb/hme,nihildeb/hme,nihildeb/hme,nihildeb/hme,nihildeb/hme,nihildeb/hme
38fcf786f958ca694f438543815e6b519b2ca16b
cli/Session.cpp
cli/Session.cpp
#include <cli/Session.h> #include <cli/CommandLine.h> #include <cli/PosixStreams.h> #include <cli/Tokenizer.h> #include <mtp/make_function.h> #include <stdio.h> namespace cli { Session::Session(const mtp::DevicePtr &device): _device(device), _session(_device->OpenSession(1)), _gdi(_session->GetDeviceInfo()), _cd(mtp::Session::Root), _running(true) { using namespace mtp; using namespace std::placeholders; printf("%s\n", _gdi.VendorExtensionDesc.c_str()); printf("%s ", _gdi.Manufacturer.c_str()); printf("%s ", _gdi.Model.c_str()); printf("%s ", _gdi.DeviceVersion.c_str()); //printf("%s", _gdi.SerialNumber.c_str()); printf("\n"); printf("supported op codes: "); for(OperationCode code : _gdi.OperationsSupported) { printf("%04x ", (unsigned)code); } printf("\n"); printf("supported properties: "); for(u16 code : _gdi.DevicePropertiesSupported) { printf("%04x ", (unsigned)code); } printf("\n"); AddCommand("help", make_function([this]() -> void { Help(); })); AddCommand("ls", make_function([this]() -> void { List(); })); AddCommand("list", make_function([this]() -> void { List(); })); AddCommand("list", make_function([this](mtp::u32 parent) -> void { List(parent); })); AddCommand("quit", make_function([this]() -> void { Quit(); })); AddCommand("exit", make_function([this]() -> void { Quit(); })); AddCommand("cd", make_function([this](const Path &path) -> void { ChangeDirectory(path); })); AddCommand("rm", make_function([this](const LocalPath &path) -> void { Delete(path); })); AddCommand("get", make_function([this](const LocalPath &path) -> void { Get(path); })); AddCommand("storages", make_function([this]() -> void { ListStorages(); })); AddCommand("device-properties", make_function([this]() -> void { ListDeviceProperties(); })); } char ** Session::CompletionCallback(const char *text, int start, int end) { if (start == 0) { char **comp = static_cast<char **>(calloc(sizeof(char *), _commands.size() + 1)); auto it = _commands.begin(); size_t i = 0, n = _commands.size(); for(; n--; ++it) { if (end != 0 && it->first.compare(0, end, text) != 0) continue; comp[i++] = strdup(it->first.c_str()); } if (i == 0) //readline silently dereference matches[0] { free(comp); comp = NULL; }; return comp; } return NULL; } void Session::InteractiveInput() { using namespace mtp; std::string prompt(_gdi.Manufacturer + " " + _gdi.Model + "> "), input; cli::CommandLine::Get().SetCallback([this](const char *text, int start, int end) -> char ** { return CompletionCallback(text, start, end); }); while (cli::CommandLine::Get().ReadLine(prompt, input)) { try { Tokens tokens; Tokenizer(input, tokens); if (tokens.empty()) continue; std::string cmdName = tokens.front(); tokens.pop_front(); auto cmd = _commands.find(cmdName); if (cmd == _commands.end()) throw std::runtime_error("invalid command " + cmdName); cmd->second->Execute(tokens); if (!_running) //do not put newline return; } catch(const std::exception &ex) { printf("error: %s\n", ex.what()); } } printf("\n"); } mtp::u32 Session::Resolve(const Path &path) { mtp::u32 id = _cd; for(size_t p = 0; p < path.size(); ) { size_t next = path.find('/', p); if (next == path.npos) next = path.size(); std::string entity(path.substr(p, next - p)); auto objectList = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, id); bool found = false; for(auto object : objectList.ObjectHandles) { std::string name = _session->GetObjectStringProperty(object, mtp::ObjectProperty::ObjectFilename); if (name == entity) { id = object; found = true; break; } } if (!found) throw std::runtime_error("could not find " + entity + " in path " + path.substr(0, p)); p = next + 1; } return id; } void Session::List(mtp::u32 parent) { using namespace mtp; msg::ObjectHandles handles = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, parent); for(u32 objectId : handles.ObjectHandles) { try { msg::ObjectInfo info = _session->GetObjectInfo(objectId); printf("%-10u %04hx %s %u %ux%u, %s\n", objectId, info.ObjectFormat, info.Filename.c_str(), info.ObjectCompressedSize, info.ImagePixWidth, info.ImagePixHeight, info.CaptureDate.c_str()); } catch(const std::exception &ex) { printf("error: %s\n", ex.what()); } } } void Session::ListStorages() { using namespace mtp; msg::StorageIDs list = _session->GetStorageIDs(); for(size_t i = 0; i < list.StorageIDs.size(); ++i) { msg::StorageInfo si = _session->GetStorageInfo(list.StorageIDs[i]); printf("%08d volume: %s, description: %s\n", list.StorageIDs[i], si.VolumeLabel.c_str(), si.StorageDescription.c_str()); } } void Session::Help() { printf("Available commands are:\n"); for(auto i : _commands) { printf("\t%s\n", i.first.c_str()); } } void Session::Get(const LocalPath &dst, mtp::u32 srcId) { _session->GetObject(srcId, std::make_shared<ObjectOutputStream>(dst)); } void Session::Get(mtp::u32 srcId) { auto info = _session->GetObjectInfo(srcId); printf("filename = %s\n", info.Filename.c_str()); Get(LocalPath(info.Filename), srcId); } void Session::Put(mtp::u32 parentId, const LocalPath &src) { using namespace mtp; msg::ObjectInfo oi; oi.Filename = src; oi.ObjectFormat = ObjectFormatFromFilename(src); std::shared_ptr<ObjectInputStream> objectInput(new ObjectInputStream(src)); oi.SetSize(objectInput->GetSize()); auto noi = _session->SendObjectInfo(oi, 0, parentId); printf("new object id = %u\n", noi.ObjectId); _session->SendObject(objectInput); printf("done\n"); } void Session::MakeDirectory(mtp::u32 parentId, const std::string & name) { using namespace mtp; msg::ObjectInfo oi; oi.Filename = name; oi.ObjectFormat = ObjectFormat::Association; _session->SendObjectInfo(oi, 0, parentId); } void Session::Delete(mtp::u32 id) { _session->DeleteObject(id); } void Session::ListProperties(mtp::u32 id) { auto ops = _session->GetObjectPropsSupported(id); printf("properties supported: "); for(mtp::u16 prop: ops.ObjectPropCodes) { printf("%02x ", prop); } printf("\n"); } void Session::ListDeviceProperties() { using namespace mtp; for(u16 code : _gdi.DevicePropertiesSupported) { if ((code & 0xff00) != 0x5000 ) continue; printf("property code: %04x\n", (unsigned)code); ByteArray data = _session->GetDeviceProperty((mtp::DeviceProperty)code); HexDump("value", data); } } }
#include <cli/Session.h> #include <cli/CommandLine.h> #include <cli/PosixStreams.h> #include <cli/Tokenizer.h> #include <mtp/make_function.h> #include <stdio.h> namespace cli { Session::Session(const mtp::DevicePtr &device): _device(device), _session(_device->OpenSession(1)), _gdi(_session->GetDeviceInfo()), _cd(mtp::Session::Root), _running(true) { using namespace mtp; using namespace std::placeholders; printf("%s\n", _gdi.VendorExtensionDesc.c_str()); printf("%s ", _gdi.Manufacturer.c_str()); printf("%s ", _gdi.Model.c_str()); printf("%s ", _gdi.DeviceVersion.c_str()); //printf("%s", _gdi.SerialNumber.c_str()); printf("\n"); printf("supported op codes: "); for(OperationCode code : _gdi.OperationsSupported) { printf("%04x ", (unsigned)code); } printf("\n"); printf("supported properties: "); for(u16 code : _gdi.DevicePropertiesSupported) { printf("%04x ", (unsigned)code); } printf("\n"); AddCommand("help", make_function([this]() -> void { Help(); })); AddCommand("ls", make_function([this]() -> void { List(); })); AddCommand("list", make_function([this]() -> void { List(); })); AddCommand("list", make_function([this](mtp::u32 parent) -> void { List(parent); })); AddCommand("quit", make_function([this]() -> void { Quit(); })); AddCommand("exit", make_function([this]() -> void { Quit(); })); AddCommand("cd", make_function([this](const Path &path) -> void { ChangeDirectory(path); })); AddCommand("rm", make_function([this](const LocalPath &path) -> void { Delete(path); })); AddCommand("get", make_function([this](const LocalPath &path) -> void { Get(path); })); AddCommand("storages", make_function([this]() -> void { ListStorages(); })); AddCommand("device-properties", make_function([this]() -> void { ListDeviceProperties(); })); } char ** Session::CompletionCallback(const char *text, int start, int end) { if (start == 0) { char **comp = static_cast<char **>(calloc(sizeof(char *), _commands.size() + 1)); auto it = _commands.begin(); size_t i = 0, n = _commands.size(); for(; n--; ++it) { if (end != 0 && it->first.compare(0, end, text) != 0) continue; comp[i++] = strdup(it->first.c_str()); } if (i == 0) //readline silently dereference matches[0] { free(comp); comp = NULL; }; return comp; } return NULL; } void Session::InteractiveInput() { using namespace mtp; std::string prompt(_gdi.Manufacturer + " " + _gdi.Model + "> "), input; cli::CommandLine::Get().SetCallback([this](const char *text, int start, int end) -> char ** { return CompletionCallback(text, start, end); }); while (cli::CommandLine::Get().ReadLine(prompt, input)) { try { Tokens tokens; Tokenizer(input, tokens); if (tokens.empty()) continue; std::string cmdName = tokens.front(); tokens.pop_front(); auto cmd = _commands.find(cmdName); if (cmd == _commands.end()) throw std::runtime_error("invalid command " + cmdName); cmd->second->Execute(tokens); if (!_running) //do not put newline return; } catch(const std::exception &ex) { printf("error: %s\n", ex.what()); } } printf("\n"); } mtp::u32 Session::Resolve(const Path &path) { mtp::u32 id = _cd; for(size_t p = 0; p < path.size(); ) { size_t next = path.find('/', p); if (next == path.npos) next = path.size(); std::string entity(path.substr(p, next - p)); auto objectList = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, id); bool found = false; for(auto object : objectList.ObjectHandles) { std::string name = _session->GetObjectStringProperty(object, mtp::ObjectProperty::ObjectFilename); if (name == entity) { id = object; found = true; break; } } if (!found) throw std::runtime_error("could not find " + entity + " in path " + path.substr(0, p)); p = next + 1; } return id; } void Session::List(mtp::u32 parent) { using namespace mtp; msg::ObjectHandles handles = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, parent); for(u32 objectId : handles.ObjectHandles) { try { msg::ObjectInfo info = _session->GetObjectInfo(objectId); printf("%-10u %04hx %10u %s %ux%u, %s\n", objectId, info.ObjectFormat, info.ObjectCompressedSize, info.Filename.c_str(), info.ImagePixWidth, info.ImagePixHeight, info.CaptureDate.c_str()); } catch(const std::exception &ex) { printf("error: %s\n", ex.what()); } } } void Session::ListStorages() { using namespace mtp; msg::StorageIDs list = _session->GetStorageIDs(); for(size_t i = 0; i < list.StorageIDs.size(); ++i) { msg::StorageInfo si = _session->GetStorageInfo(list.StorageIDs[i]); printf("%08d volume: %s, description: %s\n", list.StorageIDs[i], si.VolumeLabel.c_str(), si.StorageDescription.c_str()); } } void Session::Help() { printf("Available commands are:\n"); for(auto i : _commands) { printf("\t%s\n", i.first.c_str()); } } void Session::Get(const LocalPath &dst, mtp::u32 srcId) { _session->GetObject(srcId, std::make_shared<ObjectOutputStream>(dst)); } void Session::Get(mtp::u32 srcId) { auto info = _session->GetObjectInfo(srcId); printf("filename = %s\n", info.Filename.c_str()); Get(LocalPath(info.Filename), srcId); } void Session::Put(mtp::u32 parentId, const LocalPath &src) { using namespace mtp; msg::ObjectInfo oi; oi.Filename = src; oi.ObjectFormat = ObjectFormatFromFilename(src); std::shared_ptr<ObjectInputStream> objectInput(new ObjectInputStream(src)); oi.SetSize(objectInput->GetSize()); auto noi = _session->SendObjectInfo(oi, 0, parentId); printf("new object id = %u\n", noi.ObjectId); _session->SendObject(objectInput); printf("done\n"); } void Session::MakeDirectory(mtp::u32 parentId, const std::string & name) { using namespace mtp; msg::ObjectInfo oi; oi.Filename = name; oi.ObjectFormat = ObjectFormat::Association; _session->SendObjectInfo(oi, 0, parentId); } void Session::Delete(mtp::u32 id) { _session->DeleteObject(id); } void Session::ListProperties(mtp::u32 id) { auto ops = _session->GetObjectPropsSupported(id); printf("properties supported: "); for(mtp::u16 prop: ops.ObjectPropCodes) { printf("%02x ", prop); } printf("\n"); } void Session::ListDeviceProperties() { using namespace mtp; for(u16 code : _gdi.DevicePropertiesSupported) { if ((code & 0xff00) != 0x5000 ) continue; printf("property code: %04x\n", (unsigned)code); ByteArray data = _session->GetDeviceProperty((mtp::DeviceProperty)code); HexDump("value", data); } } }
put size before filename in listing
put size before filename in listing
C++
lgpl-2.1
whoozle/android-file-transfer-linux,whoozle/android-file-transfer-linux,whoozle/android-file-transfer-linux,whoozle/android-file-transfer-linux
d407c176f751f2ca46a9669cc30bd6401ec0f4e6
chrome/browser/net/dns_host_info.cc
chrome/browser/net/dns_host_info.cc
// Copyright (c) 2006-2008 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. // See header file for description of class #include "chrome/browser/net/dns_host_info.h" #include <math.h> #include <algorithm> #include <string> #include "base/histogram.h" #include "base/logging.h" #include "base/string_util.h" using base::Time; using base::TimeDelta; using base::TimeTicks; namespace chrome_browser_net { static bool detailed_logging_enabled = false; // Use command line switch to enable detailed logging. void EnableDnsDetailedLog(bool enable) { detailed_logging_enabled = enable; } // static int DnsHostInfo::sequence_counter = 1; bool DnsHostInfo::NeedsDnsUpdate(const std::string& hostname) { DCHECK(hostname == hostname_); switch (state_) { case PENDING: // Just now created info. return true; case QUEUED: // In queue. case ASSIGNED: // Slave is working on it. case ASSIGNED_BUT_MARKED: // Slave is working on it. return false; // We're already working on it case NO_SUCH_NAME: // Lookup failed. case FOUND: // Lookup succeeded. return !IsStillCached(); // See if DNS cache expired. default: DCHECK(false); return false; } } const TimeDelta DnsHostInfo::kNullDuration(TimeDelta::FromMilliseconds(-1)); TimeDelta DnsHostInfo::kCacheExpirationDuration(TimeDelta::FromMinutes(5)); const TimeDelta DnsHostInfo::kMaxNonNetworkDnsLookupDuration( TimeDelta::FromMilliseconds(15)); void DnsHostInfo::set_cache_expiration(TimeDelta time) { kCacheExpirationDuration = time; } void DnsHostInfo::SetQueuedState() { DCHECK(PENDING == state_ || FOUND == state_ || NO_SUCH_NAME == state_); state_ = QUEUED; queue_duration_ = resolve_duration_ = kNullDuration; GetDuration(); // Set time_ DLogResultsStats("DNS Prefetch in queue"); } void DnsHostInfo::SetAssignedState() { DCHECK(QUEUED == state_); state_ = ASSIGNED; queue_duration_ = GetDuration(); DLogResultsStats("DNS Prefetch assigned"); DHISTOGRAM_TIMES(L"DNS.PrefetchQueue", queue_duration_); } void DnsHostInfo::SetPendingDeleteState() { DCHECK(ASSIGNED == state_ || ASSIGNED_BUT_MARKED == state_); state_ = ASSIGNED_BUT_MARKED; } void DnsHostInfo::SetFoundState() { DCHECK(ASSIGNED == state_); state_ = FOUND; resolve_duration_ = GetDuration(); if (kMaxNonNetworkDnsLookupDuration <= resolve_duration_) { UMA_HISTOGRAM_LONG_TIMES(L"DNS.PrefetchFoundNameL", resolve_duration_); // Record potential beneficial time, and maybe we'll get a cache hit. // We keep the maximum, as the warming we did earlier may still be // helping with a cache upstream in DNS resolution. benefits_remaining_ = std::max(resolve_duration_, benefits_remaining_); } sequence_number_ = sequence_counter++; DLogResultsStats("DNS PrefetchFound"); } void DnsHostInfo::SetNoSuchNameState() { DCHECK(ASSIGNED == state_); state_ = NO_SUCH_NAME; resolve_duration_ = GetDuration(); if (kMaxNonNetworkDnsLookupDuration <= resolve_duration_) { DHISTOGRAM_TIMES(L"DNS.PrefetchNotFoundName", resolve_duration_); // Record potential beneficial time, and maybe we'll get a cache hit. benefits_remaining_ = std::max(resolve_duration_, benefits_remaining_); } sequence_number_ = sequence_counter++; DLogResultsStats("DNS PrefetchNotFound"); } void DnsHostInfo::SetStartedState() { DCHECK(PENDING == state_); state_ = STARTED; queue_duration_ = resolve_duration_ = TimeDelta(); // 0ms. GetDuration(); // Set time. } void DnsHostInfo::SetFinishedState(bool was_resolved) { DCHECK(STARTED == state_); state_ = was_resolved ? FINISHED : FINISHED_UNRESOLVED; resolve_duration_ = GetDuration(); // TODO(jar): Sequence number should be incremented in prefetched HostInfo. DLogResultsStats("DNS HTTP Finished"); } // IsStillCached() guesses if the DNS cache still has IP data, // or at least remembers results about "not finding host." bool DnsHostInfo::IsStillCached() const { DCHECK(FOUND == state_ || NO_SUCH_NAME == state_); // Default MS OS does not cache failures. Hence we could return false almost // all the time for that case. However, we'd never try again to prefetch // the value if we returned false that way. Hence we'll just let the lookup // time out the same way as FOUND case. if (sequence_counter - sequence_number_ > kMaxGuaranteedCacheSize) return false; TimeDelta time_since_resolution = TimeTicks::Now() - time_; if (FOUND == state_ && resolve_duration_ < kMaxNonNetworkDnsLookupDuration) { // Since cache was warm (no apparent network activity during resolution), // we assume it was "really" found (via network activity) twice as long // ago as when we got our FOUND result. time_since_resolution *= 2; } return time_since_resolution < kCacheExpirationDuration; } // Compare the later results, to the previously prefetched info. DnsBenefit DnsHostInfo::AcruePrefetchBenefits(DnsHostInfo* later_host_info) { DCHECK(FINISHED == later_host_info->state_ || FINISHED_UNRESOLVED == later_host_info->state_); DCHECK(0 == later_host_info->hostname_.compare(hostname_.data())); if ((0 == benefits_remaining_.InMilliseconds()) || (FOUND != state_ && NO_SUCH_NAME != state_)) { return PREFETCH_NO_BENEFIT; } TimeDelta benefit = benefits_remaining_ - later_host_info->resolve_duration_; later_host_info->benefits_remaining_ = benefits_remaining_; benefits_remaining_ = TimeDelta(); // zero ms. if (later_host_info->resolve_duration_ > kMaxNonNetworkDnsLookupDuration) { // Our precache effort didn't help since HTTP stack hit the network. DHISTOGRAM_TIMES(L"DNS.PrefetchCacheEviction", resolve_duration_); DLogResultsStats("DNS PrefetchCacheEviction"); return PREFETCH_CACHE_EVICTION; } if (NO_SUCH_NAME == state_) { UMA_HISTOGRAM_LONG_TIMES(L"DNS.PrefetchNegativeHitL", benefit); DLogResultsStats("DNS PrefetchNegativeHit"); return PREFETCH_NAME_NONEXISTANT; } DCHECK_EQ(FOUND, state_); UMA_HISTOGRAM_LONG_TIMES(L"DNS.PrefetchPositiveHitL", benefit); DLogResultsStats("DNS PrefetchPositiveHit"); return PREFETCH_NAME_FOUND; } void DnsHostInfo::DLogResultsStats(const char* message) const { if (!detailed_logging_enabled) return; DLOG(INFO) << "\t" << message << "\tq=" << queue_duration().InMilliseconds() << "ms,\tr=" << resolve_duration().InMilliseconds() << "ms\tp=" << benefits_remaining_.InMilliseconds() << "ms\tseq=" << sequence_number_ << "\t" << hostname_; } //------------------------------------------------------------------------------ // This last section supports HTML output, such as seen in about:dns. //------------------------------------------------------------------------------ // Preclude any possibility of Java Script or markup in the text, by only // allowing alphanumerics, ".", and whitespace. static std::string RemoveJs(const std::string& text) { std::string output(text); size_t length = output.length(); for (size_t i = 0; i < length; i++) { char next = output[i]; if (isalnum(next) || isspace(next) || '.' == next) continue; output[i] = '?'; } return output; } class MinMaxAverage { public: MinMaxAverage() : sum_(0), square_sum_(0), count_(0), minimum_(kint64max), maximum_(kint64min) { } // Return values for use in printf formatted as "%d" int sample(int64 value) { sum_ += value; square_sum_ += value * value; count_++; minimum_ = std::min(minimum_, value); maximum_ = std::max(maximum_, value); return static_cast<int>(value); } int minimum() const { return static_cast<int>(minimum_); } int maximum() const { return static_cast<int>(maximum_); } int average() const { return static_cast<int>(sum_/count_); } int sum() const { return static_cast<int>(sum_); } int standard_deviation() const { double average = static_cast<float>(sum_) / count_; double variance = static_cast<float>(square_sum_)/count_ - average * average; return static_cast<int>(floor(sqrt(variance) + .5)); } private: int64 sum_; int64 square_sum_; int count_; int64 minimum_; int64 maximum_; // DISALLOW_COPY_AND_ASSIGN(MinMaxAverage); }; static std::string HoursMinutesSeconds(int seconds) { std::string result; int print_seconds = seconds % 60; int minutes = seconds / 60; int print_minutes = minutes % 60; int print_hours = minutes/60; if (print_hours) StringAppendF(&result, "%.2d:", print_hours); if (print_hours || print_minutes) StringAppendF(&result, "%2.2d:", print_minutes); StringAppendF(&result, "%2.2d", print_seconds); return result; } // static void DnsHostInfo::GetHtmlTable(const DnsInfoTable host_infos, const char* description, const bool brief, std::string* output) { if (0 == host_infos.size()) return; output->append(description); StringAppendF(output, "%d %s", host_infos.size(), (1 == host_infos.size()) ? "hostname" : "hostnames"); if (brief) { output->append("<br><br>"); return; } const char* row_format = "<tr align=right><td>%s</td>" "<td>%d</td><td>%d</td><td>%s</td></tr>"; output->append("<br><table border=1>"); StringAppendF(output, "<tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th></tr>", "Host name", "Applicable Prefetch<br>Time (ms)", "Recent Resolution<br>Time(ms)", "How long ago<br>(HH:MM:SS)"); // Print bulk of table, and gather stats at same time. MinMaxAverage queue, resolve, preresolve, when; TimeTicks current_time = TimeTicks::Now(); for (DnsInfoTable::const_iterator it(host_infos.begin()); it != host_infos.end(); it++) { queue.sample((it->queue_duration_.InMilliseconds())); StringAppendF(output, row_format, RemoveJs(it->hostname_).c_str(), preresolve.sample((it->benefits_remaining_.InMilliseconds())), resolve.sample((it->resolve_duration_.InMilliseconds())), HoursMinutesSeconds(when.sample( (current_time - it->time_).InSeconds())).c_str()); } // Write min, max, and average summary lines. if (host_infos.size() > 2) { output->append("<B>"); StringAppendF(output, row_format, "<b>---minimum---</b>", preresolve.minimum(), resolve.minimum(), HoursMinutesSeconds(when.minimum()).c_str()); StringAppendF(output, row_format, "<b>---average---</b>", preresolve.average(), resolve.average(), HoursMinutesSeconds(when.average()).c_str()); StringAppendF(output, row_format, "<b>standard deviation</b>", preresolve.standard_deviation(), resolve.standard_deviation(), "n/a"); StringAppendF(output, row_format, "<b>---maximum---</b>", preresolve.maximum(), resolve.maximum(), HoursMinutesSeconds(when.maximum()).c_str()); StringAppendF(output, row_format, "<b>-----SUM-----</b>", preresolve.sum(), resolve.sum(), "n/a"); } output->append("</table>"); #ifdef DEBUG StringAppendF(output, "Prefetch Queue Durations: min=%d, avg=%d, max=%d<br><br>", queue.minimum(), queue.average(), queue.maximum()); #endif output->append("<br>"); } } // namespace chrome_browser_net
// Copyright (c) 2006-2008 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. // See header file for description of class #include "chrome/browser/net/dns_host_info.h" #include <math.h> #include <algorithm> #include <string> #include "base/histogram.h" #include "base/logging.h" #include "base/string_util.h" using base::Time; using base::TimeDelta; using base::TimeTicks; namespace chrome_browser_net { static bool detailed_logging_enabled = false; // Use command line switch to enable detailed logging. void EnableDnsDetailedLog(bool enable) { detailed_logging_enabled = enable; } // static int DnsHostInfo::sequence_counter = 1; bool DnsHostInfo::NeedsDnsUpdate(const std::string& hostname) { DCHECK(hostname == hostname_); switch (state_) { case PENDING: // Just now created info. return true; case QUEUED: // In queue. case ASSIGNED: // Slave is working on it. case ASSIGNED_BUT_MARKED: // Slave is working on it. return false; // We're already working on it case NO_SUCH_NAME: // Lookup failed. case FOUND: // Lookup succeeded. return !IsStillCached(); // See if DNS cache expired. default: DCHECK(false); return false; } } const TimeDelta DnsHostInfo::kNullDuration(TimeDelta::FromMilliseconds(-1)); TimeDelta DnsHostInfo::kCacheExpirationDuration(TimeDelta::FromMinutes(5)); const TimeDelta DnsHostInfo::kMaxNonNetworkDnsLookupDuration( TimeDelta::FromMilliseconds(15)); void DnsHostInfo::set_cache_expiration(TimeDelta time) { kCacheExpirationDuration = time; } void DnsHostInfo::SetQueuedState() { DCHECK(PENDING == state_ || FOUND == state_ || NO_SUCH_NAME == state_); state_ = QUEUED; queue_duration_ = resolve_duration_ = kNullDuration; GetDuration(); // Set time_ DLogResultsStats("DNS Prefetch in queue"); } void DnsHostInfo::SetAssignedState() { DCHECK(QUEUED == state_); state_ = ASSIGNED; queue_duration_ = GetDuration(); DLogResultsStats("DNS Prefetch assigned"); UMA_HISTOGRAM_TIMES(L"DNS.PrefetchQueue", queue_duration_); } void DnsHostInfo::SetPendingDeleteState() { DCHECK(ASSIGNED == state_ || ASSIGNED_BUT_MARKED == state_); state_ = ASSIGNED_BUT_MARKED; } void DnsHostInfo::SetFoundState() { DCHECK(ASSIGNED == state_); state_ = FOUND; resolve_duration_ = GetDuration(); if (kMaxNonNetworkDnsLookupDuration <= resolve_duration_) { UMA_HISTOGRAM_LONG_TIMES(L"DNS.PrefetchFoundNameL", resolve_duration_); // Record potential beneficial time, and maybe we'll get a cache hit. // We keep the maximum, as the warming we did earlier may still be // helping with a cache upstream in DNS resolution. benefits_remaining_ = std::max(resolve_duration_, benefits_remaining_); } sequence_number_ = sequence_counter++; DLogResultsStats("DNS PrefetchFound"); } void DnsHostInfo::SetNoSuchNameState() { DCHECK(ASSIGNED == state_); state_ = NO_SUCH_NAME; resolve_duration_ = GetDuration(); if (kMaxNonNetworkDnsLookupDuration <= resolve_duration_) { DHISTOGRAM_TIMES(L"DNS.PrefetchNotFoundName", resolve_duration_); // Record potential beneficial time, and maybe we'll get a cache hit. benefits_remaining_ = std::max(resolve_duration_, benefits_remaining_); } sequence_number_ = sequence_counter++; DLogResultsStats("DNS PrefetchNotFound"); } void DnsHostInfo::SetStartedState() { DCHECK(PENDING == state_); state_ = STARTED; queue_duration_ = resolve_duration_ = TimeDelta(); // 0ms. GetDuration(); // Set time. } void DnsHostInfo::SetFinishedState(bool was_resolved) { DCHECK(STARTED == state_); state_ = was_resolved ? FINISHED : FINISHED_UNRESOLVED; resolve_duration_ = GetDuration(); // TODO(jar): Sequence number should be incremented in prefetched HostInfo. DLogResultsStats("DNS HTTP Finished"); } // IsStillCached() guesses if the DNS cache still has IP data, // or at least remembers results about "not finding host." bool DnsHostInfo::IsStillCached() const { DCHECK(FOUND == state_ || NO_SUCH_NAME == state_); // Default MS OS does not cache failures. Hence we could return false almost // all the time for that case. However, we'd never try again to prefetch // the value if we returned false that way. Hence we'll just let the lookup // time out the same way as FOUND case. if (sequence_counter - sequence_number_ > kMaxGuaranteedCacheSize) return false; TimeDelta time_since_resolution = TimeTicks::Now() - time_; if (FOUND == state_ && resolve_duration_ < kMaxNonNetworkDnsLookupDuration) { // Since cache was warm (no apparent network activity during resolution), // we assume it was "really" found (via network activity) twice as long // ago as when we got our FOUND result. time_since_resolution *= 2; } return time_since_resolution < kCacheExpirationDuration; } // Compare the later results, to the previously prefetched info. DnsBenefit DnsHostInfo::AcruePrefetchBenefits(DnsHostInfo* later_host_info) { DCHECK(FINISHED == later_host_info->state_ || FINISHED_UNRESOLVED == later_host_info->state_); DCHECK(0 == later_host_info->hostname_.compare(hostname_.data())); if ((0 == benefits_remaining_.InMilliseconds()) || (FOUND != state_ && NO_SUCH_NAME != state_)) { return PREFETCH_NO_BENEFIT; } TimeDelta benefit = benefits_remaining_ - later_host_info->resolve_duration_; later_host_info->benefits_remaining_ = benefits_remaining_; benefits_remaining_ = TimeDelta(); // zero ms. if (later_host_info->resolve_duration_ > kMaxNonNetworkDnsLookupDuration) { // Our precache effort didn't help since HTTP stack hit the network. UMA_HISTOGRAM_TIMES(L"DNS.PrefetchCacheEviction", resolve_duration_); DLogResultsStats("DNS PrefetchCacheEviction"); return PREFETCH_CACHE_EVICTION; } if (NO_SUCH_NAME == state_) { UMA_HISTOGRAM_LONG_TIMES(L"DNS.PrefetchNegativeHitL", benefit); DLogResultsStats("DNS PrefetchNegativeHit"); return PREFETCH_NAME_NONEXISTANT; } DCHECK_EQ(FOUND, state_); UMA_HISTOGRAM_LONG_TIMES(L"DNS.PrefetchPositiveHitL", benefit); DLogResultsStats("DNS PrefetchPositiveHit"); return PREFETCH_NAME_FOUND; } void DnsHostInfo::DLogResultsStats(const char* message) const { if (!detailed_logging_enabled) return; DLOG(INFO) << "\t" << message << "\tq=" << queue_duration().InMilliseconds() << "ms,\tr=" << resolve_duration().InMilliseconds() << "ms\tp=" << benefits_remaining_.InMilliseconds() << "ms\tseq=" << sequence_number_ << "\t" << hostname_; } //------------------------------------------------------------------------------ // This last section supports HTML output, such as seen in about:dns. //------------------------------------------------------------------------------ // Preclude any possibility of Java Script or markup in the text, by only // allowing alphanumerics, ".", and whitespace. static std::string RemoveJs(const std::string& text) { std::string output(text); size_t length = output.length(); for (size_t i = 0; i < length; i++) { char next = output[i]; if (isalnum(next) || isspace(next) || '.' == next) continue; output[i] = '?'; } return output; } class MinMaxAverage { public: MinMaxAverage() : sum_(0), square_sum_(0), count_(0), minimum_(kint64max), maximum_(kint64min) { } // Return values for use in printf formatted as "%d" int sample(int64 value) { sum_ += value; square_sum_ += value * value; count_++; minimum_ = std::min(minimum_, value); maximum_ = std::max(maximum_, value); return static_cast<int>(value); } int minimum() const { return static_cast<int>(minimum_); } int maximum() const { return static_cast<int>(maximum_); } int average() const { return static_cast<int>(sum_/count_); } int sum() const { return static_cast<int>(sum_); } int standard_deviation() const { double average = static_cast<float>(sum_) / count_; double variance = static_cast<float>(square_sum_)/count_ - average * average; return static_cast<int>(floor(sqrt(variance) + .5)); } private: int64 sum_; int64 square_sum_; int count_; int64 minimum_; int64 maximum_; // DISALLOW_COPY_AND_ASSIGN(MinMaxAverage); }; static std::string HoursMinutesSeconds(int seconds) { std::string result; int print_seconds = seconds % 60; int minutes = seconds / 60; int print_minutes = minutes % 60; int print_hours = minutes/60; if (print_hours) StringAppendF(&result, "%.2d:", print_hours); if (print_hours || print_minutes) StringAppendF(&result, "%2.2d:", print_minutes); StringAppendF(&result, "%2.2d", print_seconds); return result; } // static void DnsHostInfo::GetHtmlTable(const DnsInfoTable host_infos, const char* description, const bool brief, std::string* output) { if (0 == host_infos.size()) return; output->append(description); StringAppendF(output, "%d %s", host_infos.size(), (1 == host_infos.size()) ? "hostname" : "hostnames"); if (brief) { output->append("<br><br>"); return; } const char* row_format = "<tr align=right><td>%s</td>" "<td>%d</td><td>%d</td><td>%s</td></tr>"; output->append("<br><table border=1>"); StringAppendF(output, "<tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th></tr>", "Host name", "Applicable Prefetch<br>Time (ms)", "Recent Resolution<br>Time(ms)", "How long ago<br>(HH:MM:SS)"); // Print bulk of table, and gather stats at same time. MinMaxAverage queue, resolve, preresolve, when; TimeTicks current_time = TimeTicks::Now(); for (DnsInfoTable::const_iterator it(host_infos.begin()); it != host_infos.end(); it++) { queue.sample((it->queue_duration_.InMilliseconds())); StringAppendF(output, row_format, RemoveJs(it->hostname_).c_str(), preresolve.sample((it->benefits_remaining_.InMilliseconds())), resolve.sample((it->resolve_duration_.InMilliseconds())), HoursMinutesSeconds(when.sample( (current_time - it->time_).InSeconds())).c_str()); } // Write min, max, and average summary lines. if (host_infos.size() > 2) { output->append("<B>"); StringAppendF(output, row_format, "<b>---minimum---</b>", preresolve.minimum(), resolve.minimum(), HoursMinutesSeconds(when.minimum()).c_str()); StringAppendF(output, row_format, "<b>---average---</b>", preresolve.average(), resolve.average(), HoursMinutesSeconds(when.average()).c_str()); StringAppendF(output, row_format, "<b>standard deviation</b>", preresolve.standard_deviation(), resolve.standard_deviation(), "n/a"); StringAppendF(output, row_format, "<b>---maximum---</b>", preresolve.maximum(), resolve.maximum(), HoursMinutesSeconds(when.maximum()).c_str()); StringAppendF(output, row_format, "<b>-----SUM-----</b>", preresolve.sum(), resolve.sum(), "n/a"); } output->append("</table>"); #ifdef DEBUG StringAppendF(output, "Prefetch Queue Durations: min=%d, avg=%d, max=%d<br><br>", queue.minimum(), queue.average(), queue.maximum()); #endif output->append("<br>"); } } // namespace chrome_browser_net
Add two UMA histograms for DNS prefetching
Add two UMA histograms for DNS prefetching I have a more complex change list, and wanted to be able to carefully constrast the before-and-after impact. r=mbelshe Review URL: http://codereview.chromium.org/9166 git-svn-id: http://src.chromium.org/svn/trunk/src@4833 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 0424e11a51d9bc75693c701f4616b38260bdc8e4
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
58a9789dafb7696ca18978edab0f4dbea1b5511f
chrome/browser/views/info_bubble.cc
chrome/browser/views/info_bubble.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/info_bubble.h" #include "base/keyboard_codes.h" #include "chrome/browser/window_sizer.h" #include "chrome/common/notification_service.h" #include "gfx/canvas.h" #include "gfx/color_utils.h" #include "gfx/path.h" #include "third_party/skia/include/core/SkPaint.h" #include "views/fill_layout.h" #include "views/widget/root_view.h" #include "views/widget/widget.h" #include "views/window/client_view.h" #include "views/window/window.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/wm_ipc.h" #include "third_party/cros/chromeos_wm_ipc_enums.h" #endif // Background color of the bubble. #if defined(OS_WIN) const SkColor InfoBubble::kBackgroundColor = color_utils::GetSysSkColor(COLOR_WINDOW); #else // TODO(beng): source from theme provider. const SkColor InfoBubble::kBackgroundColor = SK_ColorWHITE; #endif void BorderContents::Init() { DCHECK(!bubble_border_); bubble_border_ = new BubbleBorder(BubbleBorder::TOP_LEFT); set_border(bubble_border_); bubble_border_->set_background_color(InfoBubble::kBackgroundColor); } void BorderContents::SizeAndGetBounds( const gfx::Rect& position_relative_to, BubbleBorder::ArrowLocation arrow_location, bool allow_bubble_offscreen, const gfx::Size& contents_size, gfx::Rect* contents_bounds, gfx::Rect* window_bounds) { if (base::i18n::IsRTL()) arrow_location = BubbleBorder::rtl_mirror(arrow_location); bubble_border_->set_arrow_location(arrow_location); // Set the border. set_border(bubble_border_); bubble_border_->set_background_color(InfoBubble::kBackgroundColor); // Give the contents a margin. gfx::Size local_contents_size(contents_size); local_contents_size.Enlarge(kLeftMargin + kRightMargin, kTopMargin + kBottomMargin); // Try putting the arrow in its initial location, and calculating the bounds. *window_bounds = bubble_border_->GetBounds(position_relative_to, local_contents_size); if (!allow_bubble_offscreen) { // See if those bounds will fit on the monitor. scoped_ptr<WindowSizer::MonitorInfoProvider> monitor_provider( WindowSizer::CreateDefaultMonitorInfoProvider()); gfx::Rect monitor_bounds( monitor_provider->GetMonitorWorkAreaMatching(position_relative_to)); if (!monitor_bounds.IsEmpty() && !monitor_bounds.Contains(*window_bounds)) { // The bounds don't fit. Move the arrow to try and improve things. if (window_bounds->bottom() > monitor_bounds.bottom()) arrow_location = BubbleBorder::horizontal_mirror(arrow_location); else if (BubbleBorder::is_arrow_on_left(arrow_location) ? (window_bounds->right() > monitor_bounds.right()) : (window_bounds->x() < monitor_bounds.x())) { arrow_location = BubbleBorder::rtl_mirror(arrow_location); } bubble_border_->set_arrow_location(arrow_location); // Now get the recalculated bounds. *window_bounds = bubble_border_->GetBounds(position_relative_to, local_contents_size); } } // Calculate the bounds of the contained contents (in window coordinates) by // subtracting the border dimensions and margin amounts. *contents_bounds = gfx::Rect(gfx::Point(), window_bounds->size()); gfx::Insets insets; bubble_border_->GetInsets(&insets); contents_bounds->Inset(insets.left() + kLeftMargin, insets.top() + kTopMargin, insets.right() + kRightMargin, insets.bottom() + kBottomMargin); } void BorderContents::Paint(gfx::Canvas* canvas) { // The border of this view creates an anti-aliased round-rect region for the // contents, which we need to fill with the background color. // NOTE: This doesn't handle an arrow location of "NONE", which has square top // corners. SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kFill_Style); paint.setColor(InfoBubble::kBackgroundColor); gfx::Path path; gfx::Rect bounds(GetLocalBounds(false)); SkRect rect; rect.set(SkIntToScalar(bounds.x()), SkIntToScalar(bounds.y()), SkIntToScalar(bounds.right()), SkIntToScalar(bounds.bottom())); SkScalar radius = SkIntToScalar(BubbleBorder::GetCornerRadius()); path.addRoundRect(rect, radius, radius); canvas->drawPath(path, paint); // Now we paint the border, so it will be alpha-blended atop the contents. // This looks slightly better in the corners than drawing the contents atop // the border. PaintBorder(canvas); } #if defined(OS_WIN) // BorderWidget --------------------------------------------------------------- BorderWidget::BorderWidget() : border_contents_(NULL) { set_delete_on_destroy(false); // Our owner will free us manually. set_window_style(WS_POPUP); set_window_ex_style(WS_EX_TOOLWINDOW | WS_EX_LAYERED); } void BorderWidget::Init(HWND owner) { DCHECK(!border_contents_); border_contents_ = CreateBorderContents(); border_contents_->Init(); WidgetWin::Init(GetAncestor(owner, GA_ROOT), gfx::Rect()); SetContentsView(border_contents_); SetWindowPos(owner, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOREDRAW); } gfx::Rect BorderWidget::SizeAndGetBounds( const gfx::Rect& position_relative_to, BubbleBorder::ArrowLocation arrow_location, const gfx::Size& contents_size) { // Ask the border view to calculate our bounds (and our contents'). gfx::Rect contents_bounds; gfx::Rect window_bounds; border_contents_->SizeAndGetBounds(position_relative_to, arrow_location, false, contents_size, &contents_bounds, &window_bounds); SetBounds(window_bounds); // Chop a hole out of our region to show the contents through. // CreateRectRgn() expects (left, top, right, bottom) in window coordinates. HRGN contents_region = CreateRectRgn(contents_bounds.x(), contents_bounds.y(), contents_bounds.right(), contents_bounds.bottom()); HRGN window_region = CreateRectRgn(0, 0, window_bounds.width(), window_bounds.height()); CombineRgn(window_region, window_region, contents_region, RGN_XOR); DeleteObject(contents_region); SetWindowRgn(window_region, true); // Return |contents_bounds| in screen coordinates. contents_bounds.Offset(window_bounds.origin()); return contents_bounds; } BorderContents* BorderWidget::CreateBorderContents() { return new BorderContents(); } LRESULT BorderWidget::OnMouseActivate(HWND window, UINT hit_test, UINT mouse_message) { // Never activate. return MA_NOACTIVATE; } #endif // InfoBubble ----------------------------------------------------------------- // static InfoBubble* InfoBubble::Show(views::Widget* parent, const gfx::Rect& position_relative_to, BubbleBorder::ArrowLocation arrow_location, views::View* contents, InfoBubbleDelegate* delegate) { InfoBubble* window = new InfoBubble; window->Init(parent, position_relative_to, arrow_location, contents, delegate); return window; } void InfoBubble::Close() { Close(false); } InfoBubble::InfoBubble() : #if defined(OS_LINUX) WidgetGtk(TYPE_WINDOW), border_contents_(NULL), #endif delegate_(NULL), closed_(false) { } void InfoBubble::Init(views::Widget* parent, const gfx::Rect& position_relative_to, BubbleBorder::ArrowLocation arrow_location, views::View* contents, InfoBubbleDelegate* delegate) { delegate_ = delegate; position_relative_to_ = position_relative_to; arrow_location_ = arrow_location; contents_ = contents; // Create the main window. #if defined(OS_WIN) views::Window* parent_window = parent->GetWindow(); if (parent_window) parent_window->DisableInactiveRendering(); set_window_style(WS_POPUP | WS_CLIPCHILDREN); set_window_ex_style(WS_EX_TOOLWINDOW); WidgetWin::Init(parent->GetNativeView(), gfx::Rect()); #elif defined(OS_LINUX) MakeTransparent(); make_transient_to_parent(); WidgetGtk::Init( GTK_WIDGET(static_cast<WidgetGtk*>(parent)->GetNativeView()), gfx::Rect()); #if defined(OS_CHROMEOS) chromeos::WmIpc::instance()->SetWindowType( GetNativeView(), chromeos::WM_IPC_WINDOW_CHROME_INFO_BUBBLE, NULL); #endif #endif // Create a View to hold the contents of the main window. views::View* contents_view = new views::View; // We add |contents_view| to ourselves before the AddChildView() call below so // that when |contents| gets added, it will already have a widget, and thus // any NativeButtons it creates in ViewHierarchyChanged() will be functional // (e.g. calling SetChecked() on checkboxes is safe). SetContentsView(contents_view); // Adding |contents| as a child has to be done before we call // contents->GetPreferredSize() below, since some supplied views don't // actually initialize themselves until they're added to a hierarchy. contents_view->AddChildView(contents); // Calculate and set the bounds for all windows and views. gfx::Rect window_bounds; #if defined(OS_WIN) DCHECK(!border_.get()); border_.reset(CreateBorderWidget()); border_->Init(GetNativeView()); // Initialize and position the border window. window_bounds = border_->SizeAndGetBounds(position_relative_to, arrow_location, contents->GetPreferredSize()); // Make |contents| take up the entire contents view. contents_view->SetLayoutManager(new views::FillLayout); // Paint the background color behind the contents. contents_view->set_background( views::Background::CreateSolidBackground(kBackgroundColor)); #else // Create a view to paint the border and background. border_contents_ = new BorderContents; border_contents_->Init(); gfx::Rect contents_bounds; border_contents_->SizeAndGetBounds(position_relative_to, arrow_location, false, contents->GetPreferredSize(), &contents_bounds, &window_bounds); // This new view must be added before |contents| so it will paint under it. contents_view->AddChildView(0, border_contents_); // |contents_view| has no layout manager, so we have to explicitly position // its children. border_contents_->SetBounds(gfx::Rect(gfx::Point(), window_bounds.size())); contents->SetBounds(contents_bounds); #endif SetBounds(window_bounds); // Register the Escape accelerator for closing. GetFocusManager()->RegisterAccelerator( views::Accelerator(base::VKEY_ESCAPE, false, false, false), this); // Done creating the bubble. NotificationService::current()->Notify(NotificationType::INFO_BUBBLE_CREATED, Source<InfoBubble>(this), NotificationService::NoDetails()); // Show the window. #if defined(OS_WIN) border_->ShowWindow(SW_SHOW); ShowWindow(SW_SHOW); #elif defined(OS_LINUX) views::WidgetGtk::Show(); #endif } #if defined(OS_WIN) BorderWidget* InfoBubble::CreateBorderWidget() { return new BorderWidget; } #endif void InfoBubble::SizeToContents() { gfx::Rect window_bounds; #if defined(OS_WIN) // Initialize and position the border window. window_bounds = border_->SizeAndGetBounds(position_relative_to_, arrow_location_, contents_->GetPreferredSize()); #else gfx::Rect contents_bounds; border_contents_->SizeAndGetBounds(position_relative_to_, arrow_location_, false, contents_->GetPreferredSize(), &contents_bounds, &window_bounds); // |contents_view| has no layout manager, so we have to explicitly position // its children. border_contents_->SetBounds(gfx::Rect(gfx::Point(), window_bounds.size())); contents_->SetBounds(contents_bounds); #endif SetBounds(window_bounds); } #if defined(OS_WIN) void InfoBubble::OnActivate(UINT action, BOOL minimized, HWND window) { // The popup should close when it is deactivated. if (action == WA_INACTIVE && !closed_) { Close(); } else if (action == WA_ACTIVE) { DCHECK(GetRootView()->GetChildViewCount() > 0); GetRootView()->GetChildViewAt(0)->RequestFocus(); } } #elif defined(OS_LINUX) void InfoBubble::IsActiveChanged() { if (!IsActive()) Close(); } #endif void InfoBubble::Close(bool closed_by_escape) { if (closed_) return; if (delegate_) delegate_->InfoBubbleClosing(this, closed_by_escape); closed_ = true; #if defined(OS_WIN) border_->Close(); WidgetWin::Close(); #elif defined(OS_LINUX) WidgetGtk::Close(); #endif } bool InfoBubble::AcceleratorPressed(const views::Accelerator& accelerator) { if (!delegate_ || delegate_->CloseOnEscape()) { Close(true); return true; } return false; }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/info_bubble.h" #include "base/keyboard_codes.h" #include "chrome/browser/window_sizer.h" #include "chrome/common/notification_service.h" #include "gfx/canvas.h" #include "gfx/color_utils.h" #include "gfx/path.h" #include "third_party/skia/include/core/SkPaint.h" #include "views/fill_layout.h" #include "views/widget/root_view.h" #include "views/widget/widget.h" #include "views/window/client_view.h" #include "views/window/window.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/wm_ipc.h" #include "third_party/cros/chromeos_wm_ipc_enums.h" #endif // Background color of the bubble. #if defined(OS_WIN) const SkColor InfoBubble::kBackgroundColor = color_utils::GetSysSkColor(COLOR_WINDOW); #else // TODO(beng): source from theme provider. const SkColor InfoBubble::kBackgroundColor = SK_ColorWHITE; #endif void BorderContents::Init() { // Default arrow location. BubbleBorder::ArrowLocation arrow_location = BubbleBorder::TOP_LEFT; if (base::i18n::IsRTL()) arrow_location = BubbleBorder::rtl_mirror(arrow_location); DCHECK(!bubble_border_); bubble_border_ = new BubbleBorder(arrow_location); set_border(bubble_border_); bubble_border_->set_background_color(InfoBubble::kBackgroundColor); } void BorderContents::SizeAndGetBounds( const gfx::Rect& position_relative_to, BubbleBorder::ArrowLocation arrow_location, bool allow_bubble_offscreen, const gfx::Size& contents_size, gfx::Rect* contents_bounds, gfx::Rect* window_bounds) { if (base::i18n::IsRTL()) arrow_location = BubbleBorder::rtl_mirror(arrow_location); bubble_border_->set_arrow_location(arrow_location); // Set the border. set_border(bubble_border_); bubble_border_->set_background_color(InfoBubble::kBackgroundColor); // Give the contents a margin. gfx::Size local_contents_size(contents_size); local_contents_size.Enlarge(kLeftMargin + kRightMargin, kTopMargin + kBottomMargin); // Try putting the arrow in its initial location, and calculating the bounds. *window_bounds = bubble_border_->GetBounds(position_relative_to, local_contents_size); if (!allow_bubble_offscreen) { // See if those bounds will fit on the monitor. scoped_ptr<WindowSizer::MonitorInfoProvider> monitor_provider( WindowSizer::CreateDefaultMonitorInfoProvider()); gfx::Rect monitor_bounds( monitor_provider->GetMonitorWorkAreaMatching(position_relative_to)); if (!monitor_bounds.IsEmpty() && !monitor_bounds.Contains(*window_bounds)) { // The bounds don't fit. Move the arrow to try and improve things. if (window_bounds->bottom() > monitor_bounds.bottom()) arrow_location = BubbleBorder::horizontal_mirror(arrow_location); else if (BubbleBorder::is_arrow_on_left(arrow_location) ? (window_bounds->right() > monitor_bounds.right()) : (window_bounds->x() < monitor_bounds.x())) { arrow_location = BubbleBorder::rtl_mirror(arrow_location); } bubble_border_->set_arrow_location(arrow_location); // Now get the recalculated bounds. *window_bounds = bubble_border_->GetBounds(position_relative_to, local_contents_size); } } // Calculate the bounds of the contained contents (in window coordinates) by // subtracting the border dimensions and margin amounts. *contents_bounds = gfx::Rect(gfx::Point(), window_bounds->size()); gfx::Insets insets; bubble_border_->GetInsets(&insets); contents_bounds->Inset(insets.left() + kLeftMargin, insets.top() + kTopMargin, insets.right() + kRightMargin, insets.bottom() + kBottomMargin); } void BorderContents::Paint(gfx::Canvas* canvas) { // The border of this view creates an anti-aliased round-rect region for the // contents, which we need to fill with the background color. // NOTE: This doesn't handle an arrow location of "NONE", which has square top // corners. SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kFill_Style); paint.setColor(InfoBubble::kBackgroundColor); gfx::Path path; gfx::Rect bounds(GetLocalBounds(false)); SkRect rect; rect.set(SkIntToScalar(bounds.x()), SkIntToScalar(bounds.y()), SkIntToScalar(bounds.right()), SkIntToScalar(bounds.bottom())); SkScalar radius = SkIntToScalar(BubbleBorder::GetCornerRadius()); path.addRoundRect(rect, radius, radius); canvas->drawPath(path, paint); // Now we paint the border, so it will be alpha-blended atop the contents. // This looks slightly better in the corners than drawing the contents atop // the border. PaintBorder(canvas); } #if defined(OS_WIN) // BorderWidget --------------------------------------------------------------- BorderWidget::BorderWidget() : border_contents_(NULL) { set_delete_on_destroy(false); // Our owner will free us manually. set_window_style(WS_POPUP); set_window_ex_style(WS_EX_TOOLWINDOW | WS_EX_LAYERED); } void BorderWidget::Init(HWND owner) { DCHECK(!border_contents_); border_contents_ = CreateBorderContents(); border_contents_->Init(); WidgetWin::Init(GetAncestor(owner, GA_ROOT), gfx::Rect()); SetContentsView(border_contents_); SetWindowPos(owner, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOREDRAW); } gfx::Rect BorderWidget::SizeAndGetBounds( const gfx::Rect& position_relative_to, BubbleBorder::ArrowLocation arrow_location, const gfx::Size& contents_size) { // Ask the border view to calculate our bounds (and our contents'). gfx::Rect contents_bounds; gfx::Rect window_bounds; border_contents_->SizeAndGetBounds(position_relative_to, arrow_location, false, contents_size, &contents_bounds, &window_bounds); SetBounds(window_bounds); // Chop a hole out of our region to show the contents through. // CreateRectRgn() expects (left, top, right, bottom) in window coordinates. HRGN contents_region = CreateRectRgn(contents_bounds.x(), contents_bounds.y(), contents_bounds.right(), contents_bounds.bottom()); HRGN window_region = CreateRectRgn(0, 0, window_bounds.width(), window_bounds.height()); CombineRgn(window_region, window_region, contents_region, RGN_XOR); DeleteObject(contents_region); SetWindowRgn(window_region, true); // Return |contents_bounds| in screen coordinates. contents_bounds.Offset(window_bounds.origin()); return contents_bounds; } BorderContents* BorderWidget::CreateBorderContents() { return new BorderContents(); } LRESULT BorderWidget::OnMouseActivate(HWND window, UINT hit_test, UINT mouse_message) { // Never activate. return MA_NOACTIVATE; } #endif // InfoBubble ----------------------------------------------------------------- // static InfoBubble* InfoBubble::Show(views::Widget* parent, const gfx::Rect& position_relative_to, BubbleBorder::ArrowLocation arrow_location, views::View* contents, InfoBubbleDelegate* delegate) { InfoBubble* window = new InfoBubble; window->Init(parent, position_relative_to, arrow_location, contents, delegate); return window; } void InfoBubble::Close() { Close(false); } InfoBubble::InfoBubble() : #if defined(OS_LINUX) WidgetGtk(TYPE_WINDOW), border_contents_(NULL), #endif delegate_(NULL), closed_(false) { } void InfoBubble::Init(views::Widget* parent, const gfx::Rect& position_relative_to, BubbleBorder::ArrowLocation arrow_location, views::View* contents, InfoBubbleDelegate* delegate) { delegate_ = delegate; position_relative_to_ = position_relative_to; arrow_location_ = arrow_location; contents_ = contents; // Create the main window. #if defined(OS_WIN) views::Window* parent_window = parent->GetWindow(); if (parent_window) parent_window->DisableInactiveRendering(); set_window_style(WS_POPUP | WS_CLIPCHILDREN); set_window_ex_style(WS_EX_TOOLWINDOW); WidgetWin::Init(parent->GetNativeView(), gfx::Rect()); #elif defined(OS_LINUX) MakeTransparent(); make_transient_to_parent(); WidgetGtk::Init( GTK_WIDGET(static_cast<WidgetGtk*>(parent)->GetNativeView()), gfx::Rect()); #if defined(OS_CHROMEOS) chromeos::WmIpc::instance()->SetWindowType( GetNativeView(), chromeos::WM_IPC_WINDOW_CHROME_INFO_BUBBLE, NULL); #endif #endif // Create a View to hold the contents of the main window. views::View* contents_view = new views::View; // We add |contents_view| to ourselves before the AddChildView() call below so // that when |contents| gets added, it will already have a widget, and thus // any NativeButtons it creates in ViewHierarchyChanged() will be functional // (e.g. calling SetChecked() on checkboxes is safe). SetContentsView(contents_view); // Adding |contents| as a child has to be done before we call // contents->GetPreferredSize() below, since some supplied views don't // actually initialize themselves until they're added to a hierarchy. contents_view->AddChildView(contents); // Calculate and set the bounds for all windows and views. gfx::Rect window_bounds; #if defined(OS_WIN) DCHECK(!border_.get()); border_.reset(CreateBorderWidget()); border_->Init(GetNativeView()); // Initialize and position the border window. window_bounds = border_->SizeAndGetBounds(position_relative_to, arrow_location, contents->GetPreferredSize()); // Make |contents| take up the entire contents view. contents_view->SetLayoutManager(new views::FillLayout); // Paint the background color behind the contents. contents_view->set_background( views::Background::CreateSolidBackground(kBackgroundColor)); #else // Create a view to paint the border and background. border_contents_ = new BorderContents; border_contents_->Init(); gfx::Rect contents_bounds; border_contents_->SizeAndGetBounds(position_relative_to, arrow_location, false, contents->GetPreferredSize(), &contents_bounds, &window_bounds); // This new view must be added before |contents| so it will paint under it. contents_view->AddChildView(0, border_contents_); // |contents_view| has no layout manager, so we have to explicitly position // its children. border_contents_->SetBounds(gfx::Rect(gfx::Point(), window_bounds.size())); contents->SetBounds(contents_bounds); #endif SetBounds(window_bounds); // Register the Escape accelerator for closing. GetFocusManager()->RegisterAccelerator( views::Accelerator(base::VKEY_ESCAPE, false, false, false), this); // Done creating the bubble. NotificationService::current()->Notify(NotificationType::INFO_BUBBLE_CREATED, Source<InfoBubble>(this), NotificationService::NoDetails()); // Show the window. #if defined(OS_WIN) border_->ShowWindow(SW_SHOW); ShowWindow(SW_SHOW); #elif defined(OS_LINUX) views::WidgetGtk::Show(); #endif } #if defined(OS_WIN) BorderWidget* InfoBubble::CreateBorderWidget() { return new BorderWidget; } #endif void InfoBubble::SizeToContents() { gfx::Rect window_bounds; #if defined(OS_WIN) // Initialize and position the border window. window_bounds = border_->SizeAndGetBounds(position_relative_to_, arrow_location_, contents_->GetPreferredSize()); #else gfx::Rect contents_bounds; border_contents_->SizeAndGetBounds(position_relative_to_, arrow_location_, false, contents_->GetPreferredSize(), &contents_bounds, &window_bounds); // |contents_view| has no layout manager, so we have to explicitly position // its children. border_contents_->SetBounds(gfx::Rect(gfx::Point(), window_bounds.size())); contents_->SetBounds(contents_bounds); #endif SetBounds(window_bounds); } #if defined(OS_WIN) void InfoBubble::OnActivate(UINT action, BOOL minimized, HWND window) { // The popup should close when it is deactivated. if (action == WA_INACTIVE && !closed_) { Close(); } else if (action == WA_ACTIVE) { DCHECK(GetRootView()->GetChildViewCount() > 0); GetRootView()->GetChildViewAt(0)->RequestFocus(); } } #elif defined(OS_LINUX) void InfoBubble::IsActiveChanged() { if (!IsActive()) Close(); } #endif void InfoBubble::Close(bool closed_by_escape) { if (closed_) return; if (delegate_) delegate_->InfoBubbleClosing(this, closed_by_escape); closed_ = true; #if defined(OS_WIN) border_->Close(); WidgetWin::Close(); #elif defined(OS_LINUX) WidgetGtk::Close(); #endif } bool InfoBubble::AcceleratorPressed(const views::Accelerator& accelerator) { if (!delegate_ || delegate_->CloseOnEscape()) { Close(true); return true; } return false; }
Fix default info_bubble arrow location for RTL.
Fix default info_bubble arrow location for RTL. Review URL: http://codereview.chromium.org/2008011 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@46944 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
axinging/chromium-crosswalk,Jonekee/chromium.src,robclark/chromium,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,hujiajie/pa-chromium,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,dednal/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,anirudhSK/chromium,markYoungH/chromium.src,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,keishi/chromium,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,nacl-webkit/chrome_deps,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,patrickm/chromium.src,markYoungH/chromium.src,hujiajie/pa-chromium,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,keishi/chromium,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,dushu1203/chromium.src,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,M4sse/chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,robclark/chromium,anirudhSK/chromium,markYoungH/chromium.src,rogerwang/chromium,ltilve/chromium,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,robclark/chromium,Chilledheart/chromium,dednal/chromium.src,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,robclark/chromium,M4sse/chromium.src,Just-D/chromium-1,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,patrickm/chromium.src,keishi/chromium,rogerwang/chromium,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,keishi/chromium,dushu1203/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,robclark/chromium,markYoungH/chromium.src,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,M4sse/chromium.src,anirudhSK/chromium,ltilve/chromium,mogoweb/chromium-crosswalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,dushu1203/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,anirudhSK/chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,Chilledheart/chromium,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,patrickm/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,Just-D/chromium-1,rogerwang/chromium,PeterWangIntel/chromium-crosswalk,keishi/chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,zcbenz/cefode-chromium,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,rogerwang/chromium,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,keishi/chromium,zcbenz/cefode-chromium,rogerwang/chromium,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,robclark/chromium,ltilve/chromium,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,markYoungH/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,hujiajie/pa-chromium,littlstar/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,ltilve/chromium,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,M4sse/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,ltilve/chromium,Chilledheart/chromium,dushu1203/chromium.src,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,robclark/chromium,axinging/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,rogerwang/chromium,dushu1203/chromium.src,littlstar/chromium.src,hujiajie/pa-chromium,rogerwang/chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,robclark/chromium,timopulkkinen/BubbleFish,patrickm/chromium.src,dednal/chromium.src,Just-D/chromium-1,anirudhSK/chromium,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,mogoweb/chromium-crosswalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,robclark/chromium,Just-D/chromium-1,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,rogerwang/chromium,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,zcbenz/cefode-chromium,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,littlstar/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,timopulkkinen/BubbleFish,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,keishi/chromium,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,mogoweb/chromium-crosswalk,rogerwang/chromium,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,patrickm/chromium.src,patrickm/chromium.src,hujiajie/pa-chromium,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,rogerwang/chromium,zcbenz/cefode-chromium,robclark/chromium,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,keishi/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,nacl-webkit/chrome_deps,dednal/chromium.src,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,keishi/chromium
ebb4e6dcc6503bca9034cd59cf48da36984862a6
test/cpp/interop/client.cc
test/cpp/interop/client.cc
/* * * Copyright 2014, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <chrono> #include <memory> #include <string> #include <thread> #include <grpc/grpc.h> #include <grpc/support/log.h> #include <google/gflags.h> #include <grpc++/channel_arguments.h> #include <grpc++/channel_interface.h> #include <grpc++/client_context.h> #include <grpc++/create_channel.h> #include <grpc++/status.h> #include <grpc++/stream.h> #include "test/cpp/util/create_test_channel.h" #include "test/cpp/interop/test.pb.h" #include "test/cpp/interop/empty.pb.h" #include "test/cpp/interop/messages.pb.h" DEFINE_bool(enable_ssl, false, "Whether to use ssl/tls."); DEFINE_int32(server_port, 0, "Server port."); DEFINE_string(server_host, "127.0.0.1", "Server host."); DEFINE_string(test_case, "large_unary", "Configure different test cases. Valid options are: " "empty_unary : empty (zero bytes) request and response; " "large_unary : single request and (large) response; " "client_streaming : request streaming with single response; " "server_streaming : single request with response streaming; " "slow_consumer : single request with response" " streaming with slow client consumer; " "half_duplex : half-duplex streaming;" "ping_pong : full-duplex streaming;" "all : all of above."); using grpc::ChannelInterface; using grpc::ClientContext; using grpc::CreateTestChannel; using grpc::testing::ResponseParameters; using grpc::testing::SimpleRequest; using grpc::testing::SimpleResponse; using grpc::testing::StreamingInputCallRequest; using grpc::testing::StreamingInputCallResponse; using grpc::testing::StreamingOutputCallRequest; using grpc::testing::StreamingOutputCallResponse; using grpc::testing::TestService; namespace { // The same value is defined by the Java client. const std::vector<int> request_stream_sizes = {27182, 8, 1828, 45904}; const std::vector<int> response_stream_sizes = {31415, 9, 2653, 58979}; const int kNumResponseMessages = 2000; const int kResponseMessageSize = 1030; const int kReceiveDelayMilliSeconds = 20; } // namespace void DoEmpty(std::shared_ptr<ChannelInterface> channel) { gpr_log(GPR_INFO, "Sending an empty rpc..."); std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel)); grpc::testing::Empty request = grpc::testing::Empty::default_instance(); grpc::testing::Empty response = grpc::testing::Empty::default_instance(); ClientContext context; grpc::Status s = stub->EmptyCall(&context, request, &response); GPR_ASSERT(s.IsOk()); gpr_log(GPR_INFO, "Empty rpc done."); } void DoLargeUnary(std::shared_ptr<ChannelInterface> channel) { gpr_log(GPR_INFO, "Sending a large unary rpc..."); std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel)); SimpleRequest request; SimpleResponse response; ClientContext context; request.set_response_type(grpc::testing::PayloadType::COMPRESSABLE); request.set_response_size(314159); grpc::string payload(271828, '\0'); request.mutable_payload()->set_body(payload.c_str(), 271828); grpc::Status s = stub->UnaryCall(&context, request, &response); GPR_ASSERT(s.IsOk()); GPR_ASSERT(response.payload().type() == grpc::testing::PayloadType::COMPRESSABLE); GPR_ASSERT(response.payload().body() == grpc::string(314159, '\0')); gpr_log(GPR_INFO, "Large unary done."); } int main(int argc, char** argv) { grpc_init(); google::ParseCommandLineFlags(&argc, &argv, true); GPR_ASSERT(FLAGS_server_port); const int host_port_buf_size = 1024; char host_port[host_port_buf_size]; snprintf(host_port, host_port_buf_size, "%s:%d", FLAGS_server_host.c_str(), FLAGS_server_port); if (FLAGS_test_case == "empty_unary") { DoEmpty(CreateTestChannel(host_port, FLAGS_enable_ssl)); } else if (FLAGS_test_case == "large_unary") { DoLargeUnary(CreateTestChannel(host_port, FLAGS_enable_ssl)); } else { gpr_log( GPR_ERROR, "Unsupported test case %s. Valid options are all|empty_unary|" "large_unary|client_streaming|server_streaming|half_duplex|ping_pong", FLAGS_test_case.c_str()); } grpc_shutdown(); return 0; }
/* * * Copyright 2014, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <chrono> #include <memory> #include <string> #include <thread> #include <grpc/grpc.h> #include <grpc/support/log.h> #include <google/gflags.h> #include <grpc++/channel_arguments.h> #include <grpc++/channel_interface.h> #include <grpc++/client_context.h> #include <grpc++/create_channel.h> #include <grpc++/status.h> #include <grpc++/stream.h> #include "test/cpp/util/create_test_channel.h" #include "test/cpp/interop/test.pb.h" #include "test/cpp/interop/empty.pb.h" #include "test/cpp/interop/messages.pb.h" DEFINE_bool(enable_ssl, false, "Whether to use ssl/tls."); DEFINE_bool(use_prod_roots, false, "True to use SSL roots for production GFE"); DEFINE_int32(server_port, 0, "Server port."); DEFINE_string(server_host, "127.0.0.1", "Server host to connect to"); DEFINE_string(server_host_override, "foo.test.google.com", "Override the server host which is sent in HTTP header"); DEFINE_string(test_case, "large_unary", "Configure different test cases. Valid options are: " "empty_unary : empty (zero bytes) request and response; " "large_unary : single request and (large) response; " "client_streaming : request streaming with single response; " "server_streaming : single request with response streaming; " "slow_consumer : single request with response" " streaming with slow client consumer; " "half_duplex : half-duplex streaming;" "ping_pong : full-duplex streaming;" "all : all of above."); using grpc::ChannelInterface; using grpc::ClientContext; using grpc::CreateTestChannel; using grpc::testing::ResponseParameters; using grpc::testing::SimpleRequest; using grpc::testing::SimpleResponse; using grpc::testing::StreamingInputCallRequest; using grpc::testing::StreamingInputCallResponse; using grpc::testing::StreamingOutputCallRequest; using grpc::testing::StreamingOutputCallResponse; using grpc::testing::TestService; namespace { // The same value is defined by the Java client. const std::vector<int> request_stream_sizes = {27182, 8, 1828, 45904}; const std::vector<int> response_stream_sizes = {31415, 9, 2653, 58979}; const int kNumResponseMessages = 2000; const int kResponseMessageSize = 1030; const int kReceiveDelayMilliSeconds = 20; const int kLargeRequestSize = 314159; const int kLargeResponseSize = 271812; } // namespace void DoEmpty(std::shared_ptr<ChannelInterface> channel) { gpr_log(GPR_INFO, "Sending an empty rpc..."); std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel)); grpc::testing::Empty request = grpc::testing::Empty::default_instance(); grpc::testing::Empty response = grpc::testing::Empty::default_instance(); ClientContext context; grpc::Status s = stub->EmptyCall(&context, request, &response); GPR_ASSERT(s.IsOk()); gpr_log(GPR_INFO, "Empty rpc done."); } void DoLargeUnary(std::shared_ptr<ChannelInterface> channel) { gpr_log(GPR_INFO, "Sending a large unary rpc..."); std::unique_ptr<TestService::Stub> stub(TestService::NewStub(channel)); SimpleRequest request; SimpleResponse response; ClientContext context; request.set_response_type(grpc::testing::PayloadType::COMPRESSABLE); request.set_response_size(kLargeResponseSize); grpc::string payload(kLargeRequestSize, '\0'); request.mutable_payload()->set_body(payload.c_str(), kLargeRequestSize); grpc::Status s = stub->UnaryCall(&context, request, &response); GPR_ASSERT(s.IsOk()); GPR_ASSERT(response.payload().type() == grpc::testing::PayloadType::COMPRESSABLE); GPR_ASSERT(response.payload().body() == grpc::string(kLargeResponseSize, '\0')); gpr_log(GPR_INFO, "Large unary done."); } int main(int argc, char** argv) { grpc_init(); google::ParseCommandLineFlags(&argc, &argv, true); GPR_ASSERT(FLAGS_server_port); const int host_port_buf_size = 1024; char host_port[host_port_buf_size]; snprintf(host_port, host_port_buf_size, "%s:%d", FLAGS_server_host.c_str(), FLAGS_server_port); std::shared_ptr<ChannelInterface> channel( CreateTestChannel(host_port, FLAGS_server_host_override, FLAGS_enable_ssl, FLAGS_use_prod_roots)); if (FLAGS_test_case == "empty_unary") { DoEmpty(channel); } else if (FLAGS_test_case == "large_unary") { DoLargeUnary(channel); } else { gpr_log( GPR_ERROR, "Unsupported test case %s. Valid options are all|empty_unary|" "large_unary|client_streaming|server_streaming|half_duplex|ping_pong", FLAGS_test_case.c_str()); } channel.reset(); grpc_shutdown(); return 0; }
Add Flags to override host and enable prod ssl root. Change on 2014/12/22 by chenw <[email protected]> ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=82679415
Add Flags to override host and enable prod ssl root. Change on 2014/12/22 by chenw <[email protected]> ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=82679415
C++
apache-2.0
ncteisen/grpc,ksophocleous/grpc,goldenbull/grpc,yinsu/grpc,firebase/grpc,ppietrasa/grpc,chenbaihu/grpc,yangjae/grpc,perumaalgoog/grpc,pszemus/grpc,soltanmm/grpc,kriswuollett/grpc,kpayson64/grpc,dgquintas/grpc,matt-kwong/grpc,a11r/grpc,a11r/grpc,ejona86/grpc,royalharsh/grpc,a11r/grpc,bogdandrutu/grpc,gpndata/grpc,carl-mastrangelo/grpc,a11r/grpc,firebase/grpc,makdharma/grpc,a-veitch/grpc,madongfly/grpc,donnadionne/grpc,murgatroid99/grpc,tatsuhiro-t/grpc,jboeuf/grpc,dklempner/grpc,andrewpollock/grpc,crast/grpc,w4-sjcho/grpc,sreecha/grpc,miselin/grpc,wangyikai/grpc,surround-io/grpc,jtattermusch/grpc,ctiller/grpc,deepaklukose/grpc,ejona86/grpc,dgquintas/grpc,Juzley/grpc,jboeuf/grpc,kskalski/grpc,tengyifei/grpc,madongfly/grpc,geffzhang/grpc,firebase/grpc,simonkuang/grpc,greasypizza/grpc,pmarks-net/grpc,yang-g/grpc,Crevil/grpc,wcevans/grpc,baylabs/grpc,7anner/grpc,wkubiak/grpc,Juzley/grpc,miselin/grpc,jboeuf/grpc,firebase/grpc,philcleveland/grpc,greasypizza/grpc,leifurhauks/grpc,nicolasnoble/grpc,Vizerai/grpc,mway08/grpc,apolcyn/grpc,geffzhang/grpc,ncteisen/grpc,quizlet/grpc,yang-g/grpc,makdharma/grpc,kpayson64/grpc,matt-kwong/grpc,dgquintas/grpc,greasypizza/grpc,nmittler/grpc,rjshade/grpc,malexzx/grpc,jcanizales/grpc,ejona86/grpc,ejona86/grpc,w4-sjcho/grpc,yongni/grpc,murgatroid99/grpc,JoeWoo/grpc,mway08/grpc,fuchsia-mirror/third_party-grpc,deepaklukose/grpc,greasypizza/grpc,chrisdunelm/grpc,geffzhang/grpc,zhimingxie/grpc,ctiller/grpc,ipylypiv/grpc,hstefan/grpc,ncteisen/grpc,kumaralokgithub/grpc,mway08/grpc,infinit/grpc,bjori/grpc,podsvirov/grpc,ncteisen/grpc,yugui/grpc,murgatroid99/grpc,meisterpeeps/grpc,arkmaxim/grpc,kumaralokgithub/grpc,greasypizza/grpc,baylabs/grpc,dklempner/grpc,nicolasnoble/grpc,maxwell-demon/grpc,pmarks-net/grpc,dklempner/grpc,PeterFaiman/ruby-grpc-minimal,apolcyn/grpc,yongni/grpc,7anner/grpc,philcleveland/grpc,gpndata/grpc,grani/grpc,y-zeng/grpc,MakMukhi/grpc,grpc/grpc,LuminateWireless/grpc,7anner/grpc,meisterpeeps/grpc,doubi-workshop/grpc,tamihiro/grpc,murgatroid99/grpc,pszemus/grpc,pmarks-net/grpc,ananthonline/grpc,xtopsoft/grpc,7anner/grpc,Vizerai/grpc,wcevans/grpc,makdharma/grpc,stanley-cheung/grpc,zeliard/grpc,stanley-cheung/grpc,muxi/grpc,bjori/grpc,sidrakesh93/grpc,infinit/grpc,iMilind/grpc,yangjae/grpc,carl-mastrangelo/grpc,jboeuf/grpc,gpndata/grpc,iMilind/grpc,iMilind/grpc,carl-mastrangelo/grpc,simonkuang/grpc,LuminateWireless/grpc,adelez/grpc,JoeWoo/grpc,y-zeng/grpc,wcevans/grpc,tengyifei/grpc,hstefan/grpc,royalharsh/grpc,grani/grpc,ipylypiv/grpc,jtattermusch/grpc,kpayson64/grpc,sreecha/grpc,dgquintas/grpc,perumaalgoog/grpc,surround-io/grpc,ctiller/grpc,meisterpeeps/grpc,meisterpeeps/grpc,ppietrasa/grpc,donnadionne/grpc,LuminateWireless/grpc,ksophocleous/grpc,pmarks-net/grpc,vjpai/grpc,tengyifei/grpc,w4-sjcho/grpc,tamihiro/grpc,nicolasnoble/grpc,jcanizales/grpc,makdharma/grpc,rjshade/grpc,maxwell-demon/grpc,carl-mastrangelo/grpc,vjpai/grpc,dklempner/grpc,ksophocleous/grpc,murgatroid99/grpc,baylabs/grpc,mehrdada/grpc,wangyikai/grpc,firebase/grpc,maxwell-demon/grpc,cgvarela/grpc,makdharma/grpc,adelez/grpc,adelez/grpc,yinsu/grpc,grpc/grpc,yang-g/grpc,grpc/grpc,PeterFaiman/ruby-grpc-minimal,nmittler/grpc,kumaralokgithub/grpc,sreecha/grpc,tamihiro/grpc,stanley-cheung/grpc,miselin/grpc,stanley-cheung/grpc,donnadionne/grpc,ksophocleous/grpc,iMilind/grpc,chenbaihu/grpc,ofrobots/grpc,iMilind/grpc,wangyikai/grpc,LuminateWireless/grpc,rjshade/grpc,ananthonline/grpc,apolcyn/grpc,chrisdunelm/grpc,vsco/grpc,kumaralokgithub/grpc,mzhaom/grpc,kskalski/grpc,rjshade/grpc,tamihiro/grpc,arkmaxim/grpc,muxi/grpc,pmarks-net/grpc,thunderboltsid/grpc,larsonmpdx/grpc,ctiller/grpc,iMilind/grpc,zhimingxie/grpc,kpayson64/grpc,ipylypiv/grpc,goldenbull/grpc,goldenbull/grpc,muxi/grpc,ipylypiv/grpc,thunderboltsid/grpc,stanley-cheung/grpc,mehrdada/grpc,thinkerou/grpc,doubi-workshop/grpc,soltanmm-google/grpc,soltanmm/grpc,mehrdada/grpc,yang-g/grpc,Vizerai/grpc,jtattermusch/grpc,ipylypiv/grpc,xtopsoft/grpc,perumaalgoog/grpc,royalharsh/grpc,kskalski/grpc,yangjae/grpc,jboeuf/grpc,quizlet/grpc,thinkerou/grpc,malexzx/grpc,larsonmpdx/grpc,yangjae/grpc,jboeuf/grpc,vsco/grpc,iMilind/grpc,bogdandrutu/grpc,yinsu/grpc,arkmaxim/grpc,pmarks-net/grpc,thinkerou/grpc,daniel-j-born/grpc,vjpai/grpc,wcevans/grpc,philcleveland/grpc,kriswuollett/grpc,wcevans/grpc,fuchsia-mirror/third_party-grpc,LuminateWireless/grpc,simonkuang/grpc,vsco/grpc,sidrakesh93/grpc,carl-mastrangelo/grpc,wkubiak/grpc,apolcyn/grpc,wcevans/grpc,kpayson64/grpc,doubi-workshop/grpc,thinkerou/grpc,fichter/grpc,yongni/grpc,murgatroid99/grpc,nicolasnoble/grpc,bjori/grpc,kumaralokgithub/grpc,madongfly/grpc,matt-kwong/grpc,crast/grpc,apolcyn/grpc,apolcyn/grpc,wkubiak/grpc,muxi/grpc,grpc/grpc,grpc/grpc,chenbaihu/grpc,ejona86/grpc,bogdandrutu/grpc,dklempner/grpc,ppietrasa/grpc,nmittler/grpc,donnadionne/grpc,rjshade/grpc,arkmaxim/grpc,daniel-j-born/grpc,chrisdunelm/grpc,daniel-j-born/grpc,larsonmpdx/grpc,fichter/grpc,yangjae/grpc,meisterpeeps/grpc,jcanizales/grpc,ofrobots/grpc,stanley-cheung/grpc,thinkerou/grpc,sreecha/grpc,grani/grpc,kriswuollett/grpc,simonkuang/grpc,maxwell-demon/grpc,Vizerai/grpc,jboeuf/grpc,msmania/grpc,jtattermusch/grpc,meisterpeeps/grpc,ctiller/grpc,LuminateWireless/grpc,Vizerai/grpc,geffzhang/grpc,zhimingxie/grpc,nmittler/grpc,VcamX/grpc,greasypizza/grpc,jtattermusch/grpc,surround-io/grpc,ejona86/grpc,Vizerai/grpc,jtattermusch/grpc,thunderboltsid/grpc,yonglehou/grpc,fuchsia-mirror/third_party-grpc,xtopsoft/grpc,bogdandrutu/grpc,tempbottle/grpc,JoeWoo/grpc,makdharma/grpc,soltanmm-google/grpc,apolcyn/grpc,kriswuollett/grpc,vjpai/grpc,philcleveland/grpc,soltanmm/grpc,kpayson64/grpc,yugui/grpc,y-zeng/grpc,msiedlarek/grpc,yangjae/grpc,kpayson64/grpc,7anner/grpc,leifurhauks/grpc,matt-kwong/grpc,mehrdada/grpc,kpayson64/grpc,mehrdada/grpc,mway08/grpc,ppietrasa/grpc,jcanizales/grpc,miselin/grpc,sreecha/grpc,matt-kwong/grpc,msiedlarek/grpc,soltanmm-google/grpc,zeliard/grpc,LuminateWireless/grpc,msiedlarek/grpc,grani/grpc,firebase/grpc,a11r/grpc,JoeWoo/grpc,ejona86/grpc,makdharma/grpc,deepaklukose/grpc,geffzhang/grpc,thinkerou/grpc,larsonmpdx/grpc,philcleveland/grpc,ofrobots/grpc,maxwell-demon/grpc,ananthonline/grpc,tempbottle/grpc,jboeuf/grpc,xtopsoft/grpc,matt-kwong/grpc,mway08/grpc,zeliard/grpc,thinkerou/grpc,msiedlarek/grpc,tengyifei/grpc,ncteisen/grpc,dklempner/grpc,msiedlarek/grpc,leifurhauks/grpc,infinit/grpc,mehrdada/grpc,sidrakesh93/grpc,perumaalgoog/grpc,surround-io/grpc,hstefan/grpc,cgvarela/grpc,leifurhauks/grpc,wangyikai/grpc,fichter/grpc,yonglehou/grpc,philcleveland/grpc,makdharma/grpc,grani/grpc,firebase/grpc,mehrdada/grpc,nathanielmanistaatgoogle/grpc,quizlet/grpc,kskalski/grpc,ananthonline/grpc,Crevil/grpc,miselin/grpc,donnadionne/grpc,podsvirov/grpc,thinkerou/grpc,goldenbull/grpc,Juzley/grpc,grpc/grpc,chenbaihu/grpc,chrisdunelm/grpc,cgvarela/grpc,zhimingxie/grpc,ejona86/grpc,sreecha/grpc,PeterFaiman/ruby-grpc-minimal,cgvarela/grpc,vsco/grpc,gpndata/grpc,perumaalgoog/grpc,leifurhauks/grpc,tengyifei/grpc,fichter/grpc,cgvarela/grpc,madongfly/grpc,gpndata/grpc,sreecha/grpc,PeterFaiman/ruby-grpc-minimal,yangjae/grpc,kriswuollett/grpc,thunderboltsid/grpc,zeliard/grpc,donnadionne/grpc,Crevil/grpc,tatsuhiro-t/grpc,ncteisen/grpc,yonglehou/grpc,carl-mastrangelo/grpc,andrewpollock/grpc,hstefan/grpc,a-veitch/grpc,apolcyn/grpc,ipylypiv/grpc,hstefan/grpc,ncteisen/grpc,podsvirov/grpc,pszemus/grpc,tatsuhiro-t/grpc,chrisdunelm/grpc,msmania/grpc,andrewpollock/grpc,Vizerai/grpc,carl-mastrangelo/grpc,ppietrasa/grpc,soltanmm-google/grpc,PeterFaiman/ruby-grpc-minimal,VcamX/grpc,philcleveland/grpc,VcamX/grpc,nicolasnoble/grpc,larsonmpdx/grpc,arkmaxim/grpc,doubi-workshop/grpc,nathanielmanistaatgoogle/grpc,pszemus/grpc,a-veitch/grpc,ananthonline/grpc,kriswuollett/grpc,adelez/grpc,daniel-j-born/grpc,crast/grpc,donnadionne/grpc,grpc/grpc,JoeWoo/grpc,w4-sjcho/grpc,wkubiak/grpc,yinsu/grpc,chrisdunelm/grpc,xtopsoft/grpc,podsvirov/grpc,tengyifei/grpc,stanley-cheung/grpc,mway08/grpc,tamihiro/grpc,kumaralokgithub/grpc,perumaalgoog/grpc,quizlet/grpc,simonkuang/grpc,pszemus/grpc,ctiller/grpc,Crevil/grpc,y-zeng/grpc,mehrdada/grpc,ipylypiv/grpc,ejona86/grpc,chenbaihu/grpc,chrisdunelm/grpc,malexzx/grpc,thunderboltsid/grpc,MakMukhi/grpc,rjshade/grpc,MakMukhi/grpc,wcevans/grpc,tempbottle/grpc,yongni/grpc,pszemus/grpc,andrewpollock/grpc,yonglehou/grpc,vsco/grpc,vjpai/grpc,yonglehou/grpc,nicolasnoble/grpc,goldenbull/grpc,mehrdada/grpc,msmania/grpc,ctiller/grpc,grani/grpc,wkubiak/grpc,xtopsoft/grpc,deepaklukose/grpc,bjori/grpc,vsco/grpc,bjori/grpc,ejona86/grpc,malexzx/grpc,deepaklukose/grpc,jtattermusch/grpc,VcamX/grpc,Crevil/grpc,ctiller/grpc,bogdandrutu/grpc,ipylypiv/grpc,w4-sjcho/grpc,dklempner/grpc,tamihiro/grpc,dgquintas/grpc,grani/grpc,nicolasnoble/grpc,kskalski/grpc,muxi/grpc,nmittler/grpc,royalharsh/grpc,leifurhauks/grpc,pmarks-net/grpc,msmania/grpc,muxi/grpc,ananthonline/grpc,wangyikai/grpc,philcleveland/grpc,jtattermusch/grpc,doubi-workshop/grpc,wangyikai/grpc,kpayson64/grpc,VcamX/grpc,crast/grpc,goldenbull/grpc,tatsuhiro-t/grpc,carl-mastrangelo/grpc,larsonmpdx/grpc,LuminateWireless/grpc,ncteisen/grpc,dgquintas/grpc,firebase/grpc,adelez/grpc,adelez/grpc,hstefan/grpc,mway08/grpc,matt-kwong/grpc,tempbottle/grpc,nicolasnoble/grpc,vjpai/grpc,ksophocleous/grpc,baylabs/grpc,MakMukhi/grpc,thunderboltsid/grpc,yongni/grpc,podsvirov/grpc,maxwell-demon/grpc,yugui/grpc,nathanielmanistaatgoogle/grpc,soltanmm/grpc,Crevil/grpc,ananthonline/grpc,VcamX/grpc,a-veitch/grpc,goldenbull/grpc,JoeWoo/grpc,perumaalgoog/grpc,thinkerou/grpc,andrewpollock/grpc,yangjae/grpc,firebase/grpc,kskalski/grpc,chenbaihu/grpc,VcamX/grpc,grani/grpc,fichter/grpc,crast/grpc,nathanielmanistaatgoogle/grpc,yongni/grpc,royalharsh/grpc,ctiller/grpc,fuchsia-mirror/third_party-grpc,perumaalgoog/grpc,dklempner/grpc,wangyikai/grpc,ncteisen/grpc,zeliard/grpc,kumaralokgithub/grpc,ncteisen/grpc,a-veitch/grpc,msmania/grpc,jcanizales/grpc,gpndata/grpc,msmania/grpc,Juzley/grpc,yinsu/grpc,carl-mastrangelo/grpc,kskalski/grpc,zeliard/grpc,jcanizales/grpc,muxi/grpc,madongfly/grpc,mzhaom/grpc,y-zeng/grpc,a-veitch/grpc,baylabs/grpc,grpc/grpc,leifurhauks/grpc,msiedlarek/grpc,chrisdunelm/grpc,gpndata/grpc,nathanielmanistaatgoogle/grpc,simonkuang/grpc,royalharsh/grpc,bjori/grpc,7anner/grpc,tempbottle/grpc,ejona86/grpc,stanley-cheung/grpc,Vizerai/grpc,zhimingxie/grpc,firebase/grpc,tatsuhiro-t/grpc,adelez/grpc,thunderboltsid/grpc,sidrakesh93/grpc,fuchsia-mirror/third_party-grpc,murgatroid99/grpc,grpc/grpc,simonkuang/grpc,kriswuollett/grpc,7anner/grpc,deepaklukose/grpc,chrisdunelm/grpc,deepaklukose/grpc,jtattermusch/grpc,Crevil/grpc,meisterpeeps/grpc,firebase/grpc,geffzhang/grpc,murgatroid99/grpc,kriswuollett/grpc,donnadionne/grpc,ctiller/grpc,thinkerou/grpc,pszemus/grpc,greasypizza/grpc,maxwell-demon/grpc,msiedlarek/grpc,sidrakesh93/grpc,soltanmm/grpc,ofrobots/grpc,soltanmm-google/grpc,deepaklukose/grpc,hstefan/grpc,MakMukhi/grpc,MakMukhi/grpc,infinit/grpc,msmania/grpc,yinsu/grpc,yongni/grpc,madongfly/grpc,Crevil/grpc,carl-mastrangelo/grpc,arkmaxim/grpc,daniel-j-born/grpc,ofrobots/grpc,sreecha/grpc,Juzley/grpc,sidrakesh93/grpc,yugui/grpc,miselin/grpc,y-zeng/grpc,VcamX/grpc,fuchsia-mirror/third_party-grpc,goldenbull/grpc,Vizerai/grpc,nicolasnoble/grpc,kskalski/grpc,ppietrasa/grpc,iMilind/grpc,mway08/grpc,grpc/grpc,soltanmm-google/grpc,infinit/grpc,ppietrasa/grpc,ksophocleous/grpc,mehrdada/grpc,stanley-cheung/grpc,pszemus/grpc,ipylypiv/grpc,ofrobots/grpc,wkubiak/grpc,mehrdada/grpc,infinit/grpc,msiedlarek/grpc,simonkuang/grpc,wcevans/grpc,makdharma/grpc,yongni/grpc,fichter/grpc,soltanmm/grpc,miselin/grpc,mzhaom/grpc,vjpai/grpc,muxi/grpc,mzhaom/grpc,yang-g/grpc,w4-sjcho/grpc,soltanmm-google/grpc,dgquintas/grpc,kriswuollett/grpc,jboeuf/grpc,soltanmm-google/grpc,pszemus/grpc,zhimingxie/grpc,jcanizales/grpc,dgquintas/grpc,carl-mastrangelo/grpc,tamihiro/grpc,yugui/grpc,nathanielmanistaatgoogle/grpc,soltanmm/grpc,crast/grpc,quizlet/grpc,PeterFaiman/ruby-grpc-minimal,geffzhang/grpc,muxi/grpc,soltanmm/grpc,w4-sjcho/grpc,ctiller/grpc,yonglehou/grpc,royalharsh/grpc,tengyifei/grpc,andrewpollock/grpc,baylabs/grpc,rjshade/grpc,a11r/grpc,PeterFaiman/ruby-grpc-minimal,ofrobots/grpc,vjpai/grpc,pszemus/grpc,malexzx/grpc,kpayson64/grpc,grpc/grpc,yang-g/grpc,xtopsoft/grpc,vjpai/grpc,yongni/grpc,nicolasnoble/grpc,fuchsia-mirror/third_party-grpc,stanley-cheung/grpc,yugui/grpc,xtopsoft/grpc,jtattermusch/grpc,mzhaom/grpc,Juzley/grpc,matt-kwong/grpc,VcamX/grpc,surround-io/grpc,PeterFaiman/ruby-grpc-minimal,podsvirov/grpc,tamihiro/grpc,vjpai/grpc,soltanmm-google/grpc,tatsuhiro-t/grpc,andrewpollock/grpc,jboeuf/grpc,nmittler/grpc,crast/grpc,baylabs/grpc,madongfly/grpc,andrewpollock/grpc,maxwell-demon/grpc,perumaalgoog/grpc,sreecha/grpc,chenbaihu/grpc,chrisdunelm/grpc,surround-io/grpc,sreecha/grpc,y-zeng/grpc,yang-g/grpc,w4-sjcho/grpc,a11r/grpc,sidrakesh93/grpc,vjpai/grpc,zeliard/grpc,donnadionne/grpc,malexzx/grpc,arkmaxim/grpc,daniel-j-born/grpc,malexzx/grpc,matt-kwong/grpc,royalharsh/grpc,adelez/grpc,iMilind/grpc,MakMukhi/grpc,surround-io/grpc,tatsuhiro-t/grpc,ofrobots/grpc,donnadionne/grpc,grani/grpc,bogdandrutu/grpc,fichter/grpc,leifurhauks/grpc,infinit/grpc,cgvarela/grpc,tempbottle/grpc,dklempner/grpc,nathanielmanistaatgoogle/grpc,leifurhauks/grpc,nicolasnoble/grpc,bogdandrutu/grpc,kskalski/grpc,doubi-workshop/grpc,baylabs/grpc,vsco/grpc,wcevans/grpc,vjpai/grpc,carl-mastrangelo/grpc,msiedlarek/grpc,dgquintas/grpc,fuchsia-mirror/third_party-grpc,sidrakesh93/grpc,chrisdunelm/grpc,sreecha/grpc,firebase/grpc,nicolasnoble/grpc,goldenbull/grpc,ofrobots/grpc,yonglehou/grpc,podsvirov/grpc,quizlet/grpc,bjori/grpc,fichter/grpc,tengyifei/grpc,Crevil/grpc,Vizerai/grpc,yugui/grpc,JoeWoo/grpc,rjshade/grpc,arkmaxim/grpc,dgquintas/grpc,nathanielmanistaatgoogle/grpc,donnadionne/grpc,daniel-j-born/grpc,malexzx/grpc,wangyikai/grpc,kpayson64/grpc,murgatroid99/grpc,JoeWoo/grpc,tamihiro/grpc,tengyifei/grpc,sreecha/grpc,geffzhang/grpc,cgvarela/grpc,vsco/grpc,infinit/grpc,7anner/grpc,bogdandrutu/grpc,wkubiak/grpc,LuminateWireless/grpc,jcanizales/grpc,larsonmpdx/grpc,grpc/grpc,kumaralokgithub/grpc,mzhaom/grpc,podsvirov/grpc,jtattermusch/grpc,mzhaom/grpc,ejona86/grpc,msmania/grpc,yinsu/grpc,quizlet/grpc,bogdandrutu/grpc,PeterFaiman/ruby-grpc-minimal,doubi-workshop/grpc,kumaralokgithub/grpc,thinkerou/grpc,muxi/grpc,muxi/grpc,doubi-workshop/grpc,thunderboltsid/grpc,larsonmpdx/grpc,greasypizza/grpc,wkubiak/grpc,yinsu/grpc,a11r/grpc,msmania/grpc,yinsu/grpc,yugui/grpc,ananthonline/grpc,malexzx/grpc,ppietrasa/grpc,zhimingxie/grpc,Juzley/grpc,miselin/grpc,rjshade/grpc,JoeWoo/grpc,podsvirov/grpc,stanley-cheung/grpc,gpndata/grpc,yugui/grpc,ananthonline/grpc,wangyikai/grpc,PeterFaiman/ruby-grpc-minimal,bjori/grpc,mehrdada/grpc,jboeuf/grpc,pmarks-net/grpc,nmittler/grpc,miselin/grpc,tatsuhiro-t/grpc,crast/grpc,tempbottle/grpc,daniel-j-born/grpc,bjori/grpc,ksophocleous/grpc,dgquintas/grpc,tempbottle/grpc,murgatroid99/grpc,ctiller/grpc,cgvarela/grpc,apolcyn/grpc,surround-io/grpc,yonglehou/grpc,ppietrasa/grpc,doubi-workshop/grpc,yang-g/grpc,jtattermusch/grpc,Vizerai/grpc,quizlet/grpc,pmarks-net/grpc,infinit/grpc,arkmaxim/grpc,fuchsia-mirror/third_party-grpc,madongfly/grpc,Juzley/grpc,mzhaom/grpc,y-zeng/grpc,jcanizales/grpc,ncteisen/grpc,thinkerou/grpc,7anner/grpc,nmittler/grpc,a-veitch/grpc,maxwell-demon/grpc,madongfly/grpc,jboeuf/grpc,muxi/grpc,greasypizza/grpc,ksophocleous/grpc,MakMukhi/grpc,chenbaihu/grpc,w4-sjcho/grpc,vsco/grpc,andrewpollock/grpc,zhimingxie/grpc,adelez/grpc,a-veitch/grpc,MakMukhi/grpc,ncteisen/grpc,thunderboltsid/grpc,zeliard/grpc,philcleveland/grpc,geffzhang/grpc,simonkuang/grpc,soltanmm/grpc,larsonmpdx/grpc,fuchsia-mirror/third_party-grpc,y-zeng/grpc,daniel-j-born/grpc,royalharsh/grpc,pszemus/grpc,quizlet/grpc,a-veitch/grpc,donnadionne/grpc,deepaklukose/grpc,hstefan/grpc,meisterpeeps/grpc,a11r/grpc,hstefan/grpc,zhimingxie/grpc,baylabs/grpc,stanley-cheung/grpc,yang-g/grpc,pszemus/grpc