<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite 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 Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QtGui>

//TESTED_CLASS=
//TESTED_FILES=

class tst_QBoxLayout : public QObject
{
    Q_OBJECT

public:
    tst_QBoxLayout();
    virtual ~tst_QBoxLayout();

public slots:
    void initTestCase();
    void cleanupTestCase();
    void init();
    void cleanup();

private slots:
    void insertSpacerItem();
    void sizeHint();
    void sizeConstraints();
    void setGeometry();
    void setStyleShouldChangeSpacing();
};

class CustomLayoutStyle : public QWindowsStyle
{
    Q_OBJECT
public:
    CustomLayoutStyle() : QWindowsStyle()
    {
        hspacing = 5;
        vspacing = 10;
    }

    virtual int pixelMetric(PixelMetric metric, const QStyleOption * option = 0,
                            const QWidget * widget = 0 ) const;

    int hspacing;
    int vspacing;
};

int CustomLayoutStyle::pixelMetric(PixelMetric metric, const QStyleOption * option /*= 0*/,
                                   const QWidget * widget /*= 0*/ ) const
{
    switch (metric) {
        case PM_LayoutLeftMargin:
            return 0;
        break;
        case PM_LayoutTopMargin:
            return 3;
        break;
        case PM_LayoutRightMargin:
            return 6;
        break;
        case PM_LayoutBottomMargin:
            return 9;
        break;
        case PM_LayoutHorizontalSpacing:
            return hspacing;
        case PM_LayoutVerticalSpacing:
            return vspacing;
        break;
        default:
            break;
    }
    return QWindowsStyle::pixelMetric(metric, option, widget);
}

tst_QBoxLayout::tst_QBoxLayout()
{
}

tst_QBoxLayout::~tst_QBoxLayout()
{
}

void tst_QBoxLayout::initTestCase()
{
}

void tst_QBoxLayout::cleanupTestCase()
{
}

void tst_QBoxLayout::init()
{
}

void tst_QBoxLayout::cleanup()
{
}

void tst_QBoxLayout::insertSpacerItem()
{
    QWidget *window = new QWidget;

    QSpacerItem *spacer1 = new QSpacerItem(20, 10, QSizePolicy::Expanding, QSizePolicy::Expanding);
    QSpacerItem *spacer2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Expanding);

    QBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(new QLineEdit("Foooooooooooooooooooooooooo"));
    layout->addSpacerItem(spacer1);
    layout->addWidget(new QLineEdit("Baaaaaaaaaaaaaaaaaaaaaaaaar"));
    layout->insertSpacerItem(0, spacer2);
    window->setLayout(layout);

    QVERIFY(layout->itemAt(0) == spacer2);
    QVERIFY(layout->itemAt(2) == spacer1);

    window->show();
}

void tst_QBoxLayout::sizeHint()
{
    QWidget *window = new QWidget;
    QHBoxLayout *lay1 = new QHBoxLayout;
    QHBoxLayout *lay2 = new QHBoxLayout;
    QLabel *label = new QLabel("widget twooooooooooooooooooooooooooooooooooooooooooooooooooooooo");
    lay2->addWidget(label);
    lay1->addLayout(lay2);
    window->setLayout(lay1);
    window->show();
    label->setText("foooooooo baaaaaaar");
    QSize sh = lay1->sizeHint();
    QApplication::processEvents();
    // Note that this is not strictly required behaviour - actually
    // the preferred behaviour would be that sizeHint returns
    // the same value regardless of what's lying in the event queue.
    // (i.e. we would check for equality here instead)
    QVERIFY(lay1->sizeHint() != sh);
}

void tst_QBoxLayout::sizeConstraints()
{
    QWidget *window = new QWidget;
    QHBoxLayout *lay = new QHBoxLayout;
    lay->addWidget(new QLabel("foooooooooooooooooooooooooooooooooooo"));
    lay->addWidget(new QLabel("baaaaaaaaaaaaaaaaaaaaaaaaaaaaaar"));
    lay->setSizeConstraint(QLayout::SetFixedSize);
    window->setLayout(lay);
    window->show();
    QApplication::processEvents();
    QSize sh = window->sizeHint();
    lay->takeAt(1);
    QVERIFY(sh.width() >= window->sizeHint().width() &&
            sh.height() >= window->sizeHint().height());

}

void tst_QBoxLayout::setGeometry()
{
    QWidget w;
    QVBoxLayout *lay = new QVBoxLayout;
    lay->setMargin(0);
    lay->setSpacing(0);
    QHBoxLayout *lay2 = new QHBoxLayout;
    QDial *dial = new QDial;
    lay2->addWidget(dial);
    lay2->setAlignment(Qt::AlignTop);
    lay2->setAlignment(Qt::AlignRight);
    lay->addLayout(lay2);
    w.setLayout(lay);
    w.show();

    QRect newGeom(0, 0, 70, 70);
    lay2->setGeometry(newGeom);
    QApplication::processEvents();
    QVERIFY2(newGeom.contains(dial->geometry()), "dial->geometry() should be smaller and within newGeom");
}

void tst_QBoxLayout::setStyleShouldChangeSpacing()
{

    QWidget *window = new QWidget;
    QHBoxLayout *hbox = new QHBoxLayout(window);
    QPushButton *pb1 = new QPushButton(tr("The spacing between this"));
    QPushButton *pb2 = new QPushButton(tr("and this button should depend on the style of the parent widget"));;
    pb1->setAttribute(Qt::WA_LayoutUsesWidgetRect);
    pb2->setAttribute(Qt::WA_LayoutUsesWidgetRect);
    hbox->addWidget(pb1);
    hbox->addWidget(pb2);
    CustomLayoutStyle *style1 = new CustomLayoutStyle;
    style1->hspacing = 6;
    window->setStyle(style1);
    window->show();

    QTest::qWait(100);
    int spacing = pb2->geometry().left() - pb1->geometry().right() - 1;
    QCOMPARE(spacing, 6);

    CustomLayoutStyle *style2 = new CustomLayoutStyle();
    style2->hspacing = 10;
    window->setStyle(style2);
    QTest::qWait(100);
    spacing = pb2->geometry().left() - pb1->geometry().right() - 1;
    QCOMPARE(spacing, 10);

    delete window;
    delete style1;
    delete style2;
}

QTEST_MAIN(tst_QBoxLayout)
#include "tst_qboxlayout.moc"
<commit_msg>Fix tst_QBoxLayout::setGeometry failure on S60 3.x<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite 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 Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QtGui>

//TESTED_CLASS=
//TESTED_FILES=

class tst_QBoxLayout : public QObject
{
    Q_OBJECT

public:
    tst_QBoxLayout();
    virtual ~tst_QBoxLayout();

public slots:
    void initTestCase();
    void cleanupTestCase();
    void init();
    void cleanup();

private slots:
    void insertSpacerItem();
    void sizeHint();
    void sizeConstraints();
    void setGeometry();
    void setStyleShouldChangeSpacing();
};

class CustomLayoutStyle : public QWindowsStyle
{
    Q_OBJECT
public:
    CustomLayoutStyle() : QWindowsStyle()
    {
        hspacing = 5;
        vspacing = 10;
    }

    virtual int pixelMetric(PixelMetric metric, const QStyleOption * option = 0,
                            const QWidget * widget = 0 ) const;

    int hspacing;
    int vspacing;
};

int CustomLayoutStyle::pixelMetric(PixelMetric metric, const QStyleOption * option /*= 0*/,
                                   const QWidget * widget /*= 0*/ ) const
{
    switch (metric) {
        case PM_LayoutLeftMargin:
            return 0;
        break;
        case PM_LayoutTopMargin:
            return 3;
        break;
        case PM_LayoutRightMargin:
            return 6;
        break;
        case PM_LayoutBottomMargin:
            return 9;
        break;
        case PM_LayoutHorizontalSpacing:
            return hspacing;
        case PM_LayoutVerticalSpacing:
            return vspacing;
        break;
        default:
            break;
    }
    return QWindowsStyle::pixelMetric(metric, option, widget);
}

tst_QBoxLayout::tst_QBoxLayout()
{
}

tst_QBoxLayout::~tst_QBoxLayout()
{
}

void tst_QBoxLayout::initTestCase()
{
}

void tst_QBoxLayout::cleanupTestCase()
{
}

void tst_QBoxLayout::init()
{
}

void tst_QBoxLayout::cleanup()
{
}

void tst_QBoxLayout::insertSpacerItem()
{
    QWidget *window = new QWidget;

    QSpacerItem *spacer1 = new QSpacerItem(20, 10, QSizePolicy::Expanding, QSizePolicy::Expanding);
    QSpacerItem *spacer2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Expanding);

    QBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(new QLineEdit("Foooooooooooooooooooooooooo"));
    layout->addSpacerItem(spacer1);
    layout->addWidget(new QLineEdit("Baaaaaaaaaaaaaaaaaaaaaaaaar"));
    layout->insertSpacerItem(0, spacer2);
    window->setLayout(layout);

    QVERIFY(layout->itemAt(0) == spacer2);
    QVERIFY(layout->itemAt(2) == spacer1);

    window->show();
}

void tst_QBoxLayout::sizeHint()
{
    QWidget *window = new QWidget;
    QHBoxLayout *lay1 = new QHBoxLayout;
    QHBoxLayout *lay2 = new QHBoxLayout;
    QLabel *label = new QLabel("widget twooooooooooooooooooooooooooooooooooooooooooooooooooooooo");
    lay2->addWidget(label);
    lay1->addLayout(lay2);
    window->setLayout(lay1);
    window->show();
    label->setText("foooooooo baaaaaaar");
    QSize sh = lay1->sizeHint();
    QApplication::processEvents();
    // Note that this is not strictly required behaviour - actually
    // the preferred behaviour would be that sizeHint returns
    // the same value regardless of what's lying in the event queue.
    // (i.e. we would check for equality here instead)
    QVERIFY(lay1->sizeHint() != sh);
}

void tst_QBoxLayout::sizeConstraints()
{
    QWidget *window = new QWidget;
    QHBoxLayout *lay = new QHBoxLayout;
    lay->addWidget(new QLabel("foooooooooooooooooooooooooooooooooooo"));
    lay->addWidget(new QLabel("baaaaaaaaaaaaaaaaaaaaaaaaaaaaaar"));
    lay->setSizeConstraint(QLayout::SetFixedSize);
    window->setLayout(lay);
    window->show();
    QApplication::processEvents();
    QSize sh = window->sizeHint();
    lay->takeAt(1);
    QVERIFY(sh.width() >= window->sizeHint().width() &&
            sh.height() >= window->sizeHint().height());

}

void tst_QBoxLayout::setGeometry()
{
    QWidget w;
    QVBoxLayout *lay = new QVBoxLayout;
    lay->setMargin(0);
    lay->setSpacing(0);
    QHBoxLayout *lay2 = new QHBoxLayout;
    QDial *dial = new QDial;
    lay2->addWidget(dial);
    lay2->setAlignment(Qt::AlignTop);
    lay2->setAlignment(Qt::AlignRight);
    lay->addLayout(lay2);
    w.setLayout(lay);
    w.show();

    QRect newGeom(0, 0, 70, 70);
    lay2->setGeometry(newGeom);
    QVERIFY2(newGeom.contains(dial->geometry()), "dial->geometry() should be smaller and within newGeom");
}

void tst_QBoxLayout::setStyleShouldChangeSpacing()
{

    QWidget *window = new QWidget;
    QHBoxLayout *hbox = new QHBoxLayout(window);
    QPushButton *pb1 = new QPushButton(tr("The spacing between this"));
    QPushButton *pb2 = new QPushButton(tr("and this button should depend on the style of the parent widget"));;
    pb1->setAttribute(Qt::WA_LayoutUsesWidgetRect);
    pb2->setAttribute(Qt::WA_LayoutUsesWidgetRect);
    hbox->addWidget(pb1);
    hbox->addWidget(pb2);
    CustomLayoutStyle *style1 = new CustomLayoutStyle;
    style1->hspacing = 6;
    window->setStyle(style1);
    window->show();

    QTest::qWait(100);
    int spacing = pb2->geometry().left() - pb1->geometry().right() - 1;
    QCOMPARE(spacing, 6);

    CustomLayoutStyle *style2 = new CustomLayoutStyle();
    style2->hspacing = 10;
    window->setStyle(style2);
    QTest::qWait(100);
    spacing = pb2->geometry().left() - pb1->geometry().right() - 1;
    QCOMPARE(spacing, 10);

    delete window;
    delete style1;
    delete style2;
}

QTEST_MAIN(tst_QBoxLayout)
#include "tst_qboxlayout.moc"
<|endoftext|>


<commit_before>// Copyright (c) 2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#include <iostream>
#include <string_view>
#include <vector>

#include "test.hpp"

#include <tao/pegtl/contrib/state_control.hpp>

namespace TAO_PEGTL_NAMESPACE
{
   struct test_entry
   {
      std::string_view rule;
      std::string_view func;
      std::size_t b;
   };

   inline bool operator==( const test_entry& l, const test_entry& r ) noexcept
   {
      return ( l.rule == r.rule ) && ( l.func == r.func ) && ( l.b == r.b );
   }

   template< bool E >
   struct test_state
   {
      std::vector< test_entry > trace;

      template< typename Rule > static constexpr bool enable = E;

      template< typename Rule, typename Input, typename... States >
      void start( const Input& /*unused*/, const int a, std::size_t& b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }

      template< typename Rule, typename Input, typename... States >
      void success( const Input& /*unused*/, const int a, std::size_t& b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }

      template< typename Rule, typename Input, typename... States >
      void failure( const Input& /*unused*/, const int a, std::size_t& b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }

      template< typename Rule, typename Input, typename... States >
      void raise( const Input& /*unused*/, const int a, std::size_t& b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }

      template< typename Rule, typename Input, typename... States >
      void unwind( const Input& /*unused*/, const int a, std::size_t& b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }

      template< typename Rule, typename Input, typename... States >
      void apply( const Input& /*unused*/, const int a, std::size_t& b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }

      template< typename Rule, typename Input, typename... States >
      void apply0( const Input& /*unused*/, const int a, std::size_t& b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }
   };

   struct test_grammar : must< sor< one< 'a' >, try_catch< seq< one< 'b' >, must< one< 'c' > > > >, two< 'b' > >, eof > {};

   template< typename Rule >
   struct test_action
      : nothing< Rule >
   {};

   bool test_action_one = false;

   template<>
   struct test_action< one< 'b' > >
   {
      static void apply0( const int a, const std::size_t b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         if( test_action_one ) {
            TAO_PEGTL_TEST_ASSERT( b == 0 );
            test_action_one = false;
         }
         else {
            TAO_PEGTL_TEST_ASSERT( b == 9 );
            test_action_one = true;
         }
      }
   };

   bool test_action_two = false;

   template<>
   struct test_action< two< 'b' > >
   {
      template< typename ActionInput >
      static void apply( const ActionInput& /*unused*/, const int a, const std::size_t b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         if( test_action_two ) {
            TAO_PEGTL_TEST_ASSERT( b == 0 );
            test_action_two = false;
         }
         else {
            TAO_PEGTL_TEST_ASSERT( b == 19 );
            test_action_two = true;
         }
      }
   };

   void unit_test()
   {
      {
         test_state< true > st;
         memory_input in( "bb", __FUNCTION__ );
         std::size_t b = 0;
         const bool result = parse< test_grammar, test_action, state_control< normal >::type >( in, -1, b, st );
         TAO_PEGTL_TEST_ASSERT( result );
         TAO_PEGTL_TEST_ASSERT( test_action_one );
         TAO_PEGTL_TEST_ASSERT( test_action_two );
         TAO_PEGTL_TEST_ASSERT( b == st.trace.size() );
         b = 0;
         std::size_t i = 0;
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< test_grammar >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< internal::must< sor< one< 'a' >, try_catch< seq< one< 'b' >, must< one< 'c' > > > >, two< 'b' > > > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< sor< one< 'a' >, try_catch< seq< one< 'b' >, must< one< 'c' > > > >, two< 'b' > > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'a' > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'a' > >(), "failure", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< try_catch< seq< one< 'b' >, must< one< 'c' > > > > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< seq< one< 'b' >, must< one< 'c' > > > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'b' > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'b' > >(), "apply0", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'b' > >(), "success", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< must< one< 'c' > > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'c' > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'c' > >(), "failure", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'c' > >(), "raise", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< must< one< 'c' > > >(), "unwind", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< seq< one< 'b' >, must< one< 'c' > > > >(), "unwind", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< try_catch< seq< one< 'b' >, must< one< 'c' > > > > >(), "failure", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< two< 'b' > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< two< 'b' > >(), "apply", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< two< 'b' > >(), "success", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< sor< one< 'a' >, try_catch< seq< one< 'b' >, must< one< 'c' > > > >, two< 'b' > > >(), "success", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< internal::must< sor< one< 'a' >, try_catch< seq< one< 'b' >, must< one< 'c' > > > >, two< 'b' > > > >(), "success", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< internal::must< eof > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< eof >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< eof >(), "success", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< internal::must< eof > >(), "success", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< test_grammar >(), "success", ++b } );

         TAO_PEGTL_TEST_ASSERT( i == st.trace.size() );
         TAO_PEGTL_TEST_ASSERT( b == st.trace.size() );
      }
      {
         test_state< false > st;
         memory_input in( "bb", __FUNCTION__ );
         std::size_t b = 0;
         const bool result = parse< test_grammar, test_action, state_control< normal >::type >( in, -1, b, st );
         TAO_PEGTL_TEST_ASSERT( result );
         TAO_PEGTL_TEST_ASSERT( !test_action_one );
         TAO_PEGTL_TEST_ASSERT( !test_action_two );
         TAO_PEGTL_TEST_ASSERT( st.trace.empty() );
         TAO_PEGTL_TEST_ASSERT( b == 0 );
      }
   }

}  // namespace TAO_PEGTL_NAMESPACE

#include "main.hpp"
<commit_msg>Debug in progress.<commit_after>// Copyright (c) 2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#include <iostream>
#include <string_view>
#include <vector>

#include "test.hpp"

#include <tao/pegtl/contrib/state_control.hpp>

namespace TAO_PEGTL_NAMESPACE
{
   struct test_entry
   {
      std::string_view rule;
      std::string_view func;
      std::size_t b;
   };

   inline bool operator==( const test_entry& l, const test_entry& r ) noexcept
   {
      return ( l.rule == r.rule ) && ( l.func == r.func ) && ( l.b == r.b );
   }

   template< bool E >
   struct test_state
   {
      std::vector< test_entry > trace;

      template< typename Rule > static constexpr bool enable = E;

      template< typename Rule, typename Input, typename... States >
      void start( const Input& /*unused*/, const int a, std::size_t& b )
      {
         std::cerr << "***" << std::endl;
         std::cerr << __FUNCTION__ << std::endl;
         std::cerr << demangle< Rule >() << std::endl;

         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }

      template< typename Rule, typename Input, typename... States >
      void success( const Input& /*unused*/, const int a, std::size_t& b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }

      template< typename Rule, typename Input, typename... States >
      void failure( const Input& /*unused*/, const int a, std::size_t& b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }

      template< typename Rule, typename Input, typename... States >
      void raise( const Input& /*unused*/, const int a, std::size_t& b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }

      template< typename Rule, typename Input, typename... States >
      void unwind( const Input& /*unused*/, const int a, std::size_t& b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }

      template< typename Rule, typename Input, typename... States >
      void apply( const Input& /*unused*/, const int a, std::size_t& b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }

      template< typename Rule, typename Input, typename... States >
      void apply0( const Input& /*unused*/, const int a, std::size_t& b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         trace.push_back( { demangle< Rule >(), __FUNCTION__, ++b } );
      }
   };

   struct test_grammar : must< sor< one< 'a' >, try_catch< seq< one< 'b' >, must< one< 'c' > > > >, two< 'b' > >, eof > {};

   template< typename Rule >
   struct test_action
      : nothing< Rule >
   {};

   bool test_action_one = false;

   template<>
   struct test_action< one< 'b' > >
   {
      static void apply0( const int a, const std::size_t b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         if( test_action_one ) {
            TAO_PEGTL_TEST_ASSERT( b == 0 );
            test_action_one = false;
         }
         else {
            TAO_PEGTL_TEST_ASSERT( b == 9 );
            test_action_one = true;
         }
      }
   };

   bool test_action_two = false;

   template<>
   struct test_action< two< 'b' > >
   {
      template< typename ActionInput >
      static void apply( const ActionInput& /*unused*/, const int a, const std::size_t b )
      {
         TAO_PEGTL_TEST_ASSERT( a == -1 );
         if( test_action_two ) {
            TAO_PEGTL_TEST_ASSERT( b == 0 );
            test_action_two = false;
         }
         else {
            TAO_PEGTL_TEST_ASSERT( b == 19 );
            test_action_two = true;
         }
      }
   };

   void unit_test()
   {
      {
         test_state< true > st;
         memory_input in( "bb", __FUNCTION__ );
         std::size_t b = 0;
         const bool result = parse< test_grammar, test_action, state_control< normal >::type >( in, -1, b, st );
         TAO_PEGTL_TEST_ASSERT( result );
         TAO_PEGTL_TEST_ASSERT( test_action_one );
         TAO_PEGTL_TEST_ASSERT( test_action_two );
         TAO_PEGTL_TEST_ASSERT( b == st.trace.size() );
         b = 0;
         std::size_t i = 0;

         std::cerr << "+++" << std::endl;
         std::cerr << st.trace[ 0 ].func << std::endl;
         std::cerr << st.trace[ 0 ].rule << std::endl;
         std::cerr << st.trace[ 0 ].b << std::endl;

         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< test_grammar >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< internal::must< sor< one< 'a' >, try_catch< seq< one< 'b' >, must< one< 'c' > > > >, two< 'b' > > > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< sor< one< 'a' >, try_catch< seq< one< 'b' >, must< one< 'c' > > > >, two< 'b' > > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'a' > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'a' > >(), "failure", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< try_catch< seq< one< 'b' >, must< one< 'c' > > > > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< seq< one< 'b' >, must< one< 'c' > > > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'b' > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'b' > >(), "apply0", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'b' > >(), "success", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< must< one< 'c' > > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'c' > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'c' > >(), "failure", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< one< 'c' > >(), "raise", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< must< one< 'c' > > >(), "unwind", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< seq< one< 'b' >, must< one< 'c' > > > >(), "unwind", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< try_catch< seq< one< 'b' >, must< one< 'c' > > > > >(), "failure", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< two< 'b' > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< two< 'b' > >(), "apply", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< two< 'b' > >(), "success", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< sor< one< 'a' >, try_catch< seq< one< 'b' >, must< one< 'c' > > > >, two< 'b' > > >(), "success", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< internal::must< sor< one< 'a' >, try_catch< seq< one< 'b' >, must< one< 'c' > > > >, two< 'b' > > > >(), "success", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< internal::must< eof > >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< eof >(), "start", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< eof >(), "success", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< internal::must< eof > >(), "success", ++b } );
         TAO_PEGTL_TEST_ASSERT( st.trace[ i++ ] == test_entry{ demangle< test_grammar >(), "success", ++b } );

         TAO_PEGTL_TEST_ASSERT( i == st.trace.size() );
         TAO_PEGTL_TEST_ASSERT( b == st.trace.size() );
      }
      {
         test_state< false > st;
         memory_input in( "bb", __FUNCTION__ );
         std::size_t b = 0;
         const bool result = parse< test_grammar, test_action, state_control< normal >::type >( in, -1, b, st );
         TAO_PEGTL_TEST_ASSERT( result );
         TAO_PEGTL_TEST_ASSERT( !test_action_one );
         TAO_PEGTL_TEST_ASSERT( !test_action_two );
         TAO_PEGTL_TEST_ASSERT( st.trace.empty() );
         TAO_PEGTL_TEST_ASSERT( b == 0 );
      }
   }

}  // namespace TAO_PEGTL_NAMESPACE

#include "main.hpp"
<|endoftext|>


<commit_before>/**
 * @file getTextSize.cpp
 * @brief mex interface for getTextSize
 * @author Kota Yamaguchi
 * @date 2012
 */
#include "mexopencv.hpp"
using namespace std;
using namespace cv;

/**
 * Main entry called from Matlab
 * @param nlhs number of left-hand-side arguments
 * @param plhs pointers to mxArrays in the left-hand-side
 * @param nrhs number of right-hand-side arguments
 * @param prhs pointers to mxArrays in the right-hand-side
 */
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
    // Check the number of arguments
    if (nrhs<1 || (nrhs%2)!=1 || nlhs>2)
        mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");

    // Argument vector
    vector<MxArray> rhs(prhs,prhs+nrhs);

    // Option processing
    const string text(rhs[0].toString());
    int fontFace=FONT_HERSHEY_SIMPLEX;
    double fontScale=1.0;
    int thickness=1;
    int fontStyle=0;
    for (int i=1; i<nrhs; i+=2) {
        string key = rhs[i].toString();
        if (key=="FontFace")
            fontFace = FontFace[rhs[i+1].toString()];
        else if (key=="FontScale")
            fontScale = rhs[i+1].toDouble();
        else if (key=="Thickness")
            thickness = rhs[i+1].toInt();
        else if (key=="FontStyle")
            fontStyle = FontStyle[rhs[i+1].toString()];
        else
            mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option");
    }

    // Execute function
    vector<int> baseLine;
    Size s = getTextSize(text, fontFace | fontStyle, fontScale, thickness,
        &baseLine[0]);
    plhs[0] = MxArray(s);
    if (nlhs>1)
        plhs[1] = MxArray(baseLine);
}
<commit_msg>fix accessing empty vector data<commit_after>/**
 * @file getTextSize.cpp
 * @brief mex interface for getTextSize
 * @author Kota Yamaguchi
 * @date 2012
 */
#include "mexopencv.hpp"
using namespace std;
using namespace cv;

/**
 * Main entry called from Matlab
 * @param nlhs number of left-hand-side arguments
 * @param plhs pointers to mxArrays in the left-hand-side
 * @param nrhs number of right-hand-side arguments
 * @param prhs pointers to mxArrays in the right-hand-side
 */
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
    // Check the number of arguments
    if (nrhs<1 || (nrhs%2)!=1 || nlhs>2)
        mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");

    // Argument vector
    vector<MxArray> rhs(prhs,prhs+nrhs);

    // Option processing
    const string text(rhs[0].toString());
    int fontFace=FONT_HERSHEY_SIMPLEX;
    double fontScale=1.0;
    int thickness=1;
    int fontStyle=0;
    for (int i=1; i<nrhs; i+=2) {
        string key = rhs[i].toString();
        if (key=="FontFace")
            fontFace = FontFace[rhs[i+1].toString()];
        else if (key=="FontScale")
            fontScale = rhs[i+1].toDouble();
        else if (key=="Thickness")
            thickness = rhs[i+1].toInt();
        else if (key=="FontStyle")
            fontStyle = FontStyle[rhs[i+1].toString()];
        else
            mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option");
    }

    // Execute function
    int baseLine = 0;
    Size s = getTextSize(text, fontFace | fontStyle, fontScale, thickness,
        &baseLine);
    plhs[0] = MxArray(s);
    if (nlhs>1)
        plhs[1] = MxArray(baseLine);
}
<|endoftext|>


<commit_before><commit_msg>remove duplicated code<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: processfactory.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 09:33:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_
#define _UNOTOOLS_PROCESSFACTORY_HXX_

#ifndef INCLUDED_UNOTOOLSDLLAPI_H
#include "unotools/unotoolsdllapi.h"
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif

namespace com { namespace sun { namespace star { namespace lang {
    class XMultiServiceFactory;
} } } }

namespace utl
{

/**
 * This function set the process service factory.
 *
 * @author Juergen Schmidt
 */
UNOTOOLS_DLLPUBLIC void setProcessServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSMgr);

/**
 * This function get the process service factory. If no service factory is set the function returns
 * a null interface.
 *
 * @author Juergen Schmidt
 */
UNOTOOLS_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getProcessServiceFactory();

}

#endif // _UNOTOOLS_PROCESSFACTORY_HXX_

<commit_msg>INTEGRATION: CWS changefileheader (1.4.140); FILE MERGED 2008/04/01 16:03:27 thb 1.4.140.3: #i85898# Stripping all external header guards 2008/04/01 12:59:39 thb 1.4.140.2: #i85898# Stripping all external header guards 2008/03/31 13:03:35 rt 1.4.140.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: processfactory.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_
#define _UNOTOOLS_PROCESSFACTORY_HXX_

#include "unotools/unotoolsdllapi.h"
#include <comphelper/processfactory.hxx>
#include <com/sun/star/uno/Reference.hxx>

namespace com { namespace sun { namespace star { namespace lang {
    class XMultiServiceFactory;
} } } }

namespace utl
{

/**
 * This function set the process service factory.
 *
 * @author Juergen Schmidt
 */
UNOTOOLS_DLLPUBLIC void setProcessServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSMgr);

/**
 * This function get the process service factory. If no service factory is set the function returns
 * a null interface.
 *
 * @author Juergen Schmidt
 */
UNOTOOLS_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getProcessServiceFactory();

}

#endif // _UNOTOOLS_PROCESSFACTORY_HXX_

<|endoftext|>


<commit_before><commit_msg>Fix non unique keys in map RDL nodes<commit_after><|endoftext|>


<commit_before>#include "painter.h"

#include <QPainter>

Painter::Painter(MainWindow *window)
{
    mainWindow = window;
}
<commit_msg>Explain why the Painter class exists.<commit_after>#include "painter.h"

#include <QPainter>

//Currently, this is a useless class. As part of the refactoring,
//I will make this a custom widget and set it as part of the layout
//in the main window. This means that I can set the paint event for
//the painter to match the paint event of the main window. Then, I
//will be able to set this widget as the widget of a scroll area,
//which should allow me to implement scrolling.

Painter::Painter(MainWindow *window)
{
    mainWindow = window;
}
<|endoftext|>


<commit_before>/*
 * passwordManager.cpp
 * Created on 2017/03/27 14:38:22
 * Copyright (C) 2017 zhai <holmesfems@gmail.com>
 *
 * Distributed under terms of the MIT license.
 */

#include "passwordManager.h"
#include <boost/filesystem.hpp>
#include <sstream>
#include "stringTool.h"

namespace PasswordManager
{
    PasswordManager::PasswordManager() { _conn = NULL; }
    int PasswordManager::_initDB()
    {
        char *errMsg = NULL;
        int err = 0;
        err = sqlite3_exec(_conn, R"(CREATE TABLE IF NOT EXISTS table1
            (index INTEGER PRIMARY KEY AUTOINCREMENT,domain TEXT NOT NULL,pwdoutput TEXT NOT NULL))",
                           NULL, NULL, &errMsg);
        if (err != SQLITE_OK) {
            (*_os) << errMsg << std::endl;
            sqlite3_free(errMsg);
            errMsg = NULL;
            return err;
        }
        (*_os) << "Open table 'table1'" << std::endl;
        return 0;
    }

    char **PasswordManager::_getQuery(const char *sqlRequest, int *pnRow, int *pnCol)
    {
        char **query = NULL;
        char *errMsg = NULL;
        int err;
        err = sqlite3_get_table(_conn, sqlRequest, &query, pnRow, pnCol, &errMsg);
        if (err != SQLITE_OK) {
            (*_os) << errMsg << std::endl;
            sqlite3_free(errMsg);
            errMsg = NULL;
            return NULL;
        }
        return query;
    }

    int PasswordManager::openDB(const std::string &filename)
    {
        int err = sqlite3_open_v2(filename.c_str(), &_conn,
                                  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
        if (err != SQLITE_OK) {
            (*_os) << "An error occured while open database file:" << filename << std::endl;
            return err;
        }
        _initDB();
        //_checkDB();
        return 0;
    }

    int PasswordManager::showIndexByDomain(const std::string &domain)
    {
        int pnRow, pnCol;
        std::ostringstream sql;
        sql << R"(SELECT index,domain FROM table1 WHERE domain LIKE '%)" << domain << R"(%')";
        char **query = _getQuery(sql.str().c_str(), &pnRow, &pnCol);
        if (query == NULL) {
            (*_os) << "An error occured while searching domain: " << domain << std::endl;
            return -1;
        }
        if (pnRow == 0) {
            (*_os) << "No one is hit" << std::endl;
        } else {
            (*_os) << "Hit " << pnRow << " Results:" << std::endl;
            int i, j;
            for (i = 0; i <= pnRow; i++) {
                for (j = 0; j < pnCol; j++) {
                    if (j > 0) (*_os) << '\t';
                    (*_os) << query[i * pnCol + j];
                }
                (*_os) << std::endl;
            }
        }
        sqlite3_free_table(query);
        query=NULL;
        return 0;
    } //showIndexByDomain()

    std::string PasswordManager::searchByIndex(int index)
    {
        int pnRow,pnCol;
        std::ostringstream sql;
        sql << R"(SELECT index,domain,pwdoutput FROM table1 WHERE index=)" << index;
        char **query = _getQuery(sql.str().c_str(),&pnRow,&pnCol);
        if(query == NULL){
            (*_os) << "An error occured while searching index: " << index << std::endl;
             return "";
        }
        std::string ret="";
        if(pnRow == 0){
            (*_os) << "No one is hit" << std::endl;
        }else{
            (*_os) << "Hit " << pnRow << " Results:" << std::endl;
            int i,j;
            for(i=0;i<=pnRow;i++)
            {
                for(j=0;j<pnCol;j++)
                {
                    if(j==2) continue;
                    if(j>0) (*_os) << '\t';
                    (*_os) << query[i*pnCol+j];
                }
                (*_os) << std::endl;
            }
            ret = std::string(query[5]);
        }
        sqlite3_free_table(query);
        query=NULL;
        return ret;
    }

    int PasswordManager::addPasswd(const std::string &passwdStr,const std::string &domain)
    {
        int pnRow,pnCol;
        std::ostringstream sql;
        sql << R"(SELECT index,domain FROM table1 WHERE domain = ')" << domain << R"(')";
        char **query = _getQuery(sql.str().c_str(),&pnRow,&pnCol);
        if(query == NULL){
            (*_os) << "An error occured while searching domain: " << domain << std::endl;
             return -1;
        }
        if(pnRow == 0){
            sql.str("");
            sql << R"(BEGIN TRANSACTION;)";
            sql << R"(INSERT INTO table1 (domain,pwdoutput) VALUES(')" << domain << R"(',')"
                << passwdStr << R"(');)";
            sql << R"(COMMIT TRANSACTION;)";
            char *errMsg=NULL;
            int err=sqlite3_exec(_conn,sql.str().c_str(),NULL,NULL,&errMsg);
            if(err!=SQLITE_OK)
            {
                (*_os) << errMsg << std::endl;
                return -1;
            }

        }else{
            (*_os) << "Hit " << pnRow << " Results:" << std::endl;
            int i,j;
            for(i=0;i<=pnRow;i++)
            {
                for(j=0;j<pnCol;j++)
                {
                    if(j>0) (*_os) << '\t';
                    (*_os) << query[i*pnCol+j];
                }
                (*_os) << std::endl;
            }
        }
        sqlite3_free_table(query);
        query=NULL;
        return 0;

    }

}
<commit_msg>formatted<commit_after>/*
 * passwordManager.cpp
 * Created on 2017/03/27 14:38:22
 * Copyright (C) 2017 zhai <holmesfems@gmail.com>
 *
 * Distributed under terms of the MIT license.
 */

#include "passwordManager.h"
#include <boost/filesystem.hpp>
#include <sstream>
#include "stringTool.h"

namespace PasswordManager
{
    PasswordManager::PasswordManager() { _conn = NULL; }
    int PasswordManager::_initDB()
    {
        char *errMsg = NULL;
        int err = 0;
        err = sqlite3_exec(_conn, R"(CREATE TABLE IF NOT EXISTS table1
            (index INTEGER PRIMARY KEY AUTOINCREMENT,domain TEXT NOT NULL,pwdoutput TEXT NOT NULL))",
                           NULL, NULL, &errMsg);
        if (err != SQLITE_OK) {
            (*_os) << errMsg << std::endl;
            sqlite3_free(errMsg);
            errMsg = NULL;
            return err;
        }
        (*_os) << "Open table 'table1'" << std::endl;
        return 0;
    }

    char **PasswordManager::_getQuery(const char *sqlRequest, int *pnRow, int *pnCol)
    {
        char **query = NULL;
        char *errMsg = NULL;
        int err;
        err = sqlite3_get_table(_conn, sqlRequest, &query, pnRow, pnCol, &errMsg);
        if (err != SQLITE_OK) {
            (*_os) << errMsg << std::endl;
            sqlite3_free(errMsg);
            errMsg = NULL;
            return NULL;
        }
        return query;
    }

    int PasswordManager::openDB(const std::string &filename)
    {
        int err = sqlite3_open_v2(filename.c_str(), &_conn,
                                  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
        if (err != SQLITE_OK) {
            (*_os) << "An error occured while open database file:" << filename << std::endl;
            return err;
        }
        _initDB();
        //_checkDB();
        return 0;
    }

    int PasswordManager::showIndexByDomain(const std::string &domain)
    {
        int pnRow, pnCol;
        std::ostringstream sql;
        sql << R"(SELECT index,domain FROM table1 WHERE domain LIKE '%)" << domain << R"(%')";
        char **query = _getQuery(sql.str().c_str(), &pnRow, &pnCol);
        if (query == NULL) {
            (*_os) << "An error occured while searching domain: " << domain << std::endl;
            return -1;
        }
        if (pnRow == 0) {
            (*_os) << "No one is hit" << std::endl;
        } else {
            (*_os) << "Hit " << pnRow << " Results:" << std::endl;
            int i, j;
            for (i = 0; i <= pnRow; i++) {
                for (j = 0; j < pnCol; j++) {
                    if (j > 0) (*_os) << '\t';
                    (*_os) << query[i * pnCol + j];
                }
                (*_os) << std::endl;
            }
        }
        sqlite3_free_table(query);
        query = NULL;
        return 0;
    }  // showIndexByDomain()

    std::string PasswordManager::searchByIndex(int index)
    {
        int pnRow, pnCol;
        std::ostringstream sql;
        sql << R"(SELECT index,domain,pwdoutput FROM table1 WHERE index=)" << index;
        char **query = _getQuery(sql.str().c_str(), &pnRow, &pnCol);
        if (query == NULL) {
            (*_os) << "An error occured while searching index: " << index << std::endl;
            return "";
        }
        std::string ret = "";
        if (pnRow == 0) {
            (*_os) << "No one is hit" << std::endl;
        } else {
            (*_os) << "Hit " << pnRow << " Results:" << std::endl;
            int i, j;
            for (i = 0; i <= pnRow; i++) {
                for (j = 0; j < pnCol; j++) {
                    if (j == 2) continue;
                    if (j > 0) (*_os) << '\t';
                    (*_os) << query[i * pnCol + j];
                }
                (*_os) << std::endl;
            }
            ret = std::string(query[5]);
        }
        sqlite3_free_table(query);
        query = NULL;
        return ret;
    }

    int PasswordManager::addPasswd(const std::string &passwdStr, const std::string &domain)
    {
        int pnRow, pnCol;
        std::ostringstream sql;
        sql << R"(SELECT index,domain FROM table1 WHERE domain = ')" << domain << R"(')";
        char **query = _getQuery(sql.str().c_str(), &pnRow, &pnCol);
        if (query == NULL) {
            (*_os) << "An error occured while searching domain: " << domain << std::endl;
            return -1;
        }
        if (pnRow == 0) {
            sql.str("");
            sql << R"(BEGIN TRANSACTION;)";
            sql << R"(INSERT INTO table1 (domain,pwdoutput) VALUES(')" << domain << R"(',')"
                << passwdStr << R"(');)";
            sql << R"(COMMIT TRANSACTION;)";
            char *errMsg = NULL;
            int err = sqlite3_exec(_conn, sql.str().c_str(), NULL, NULL, &errMsg);
            if (err != SQLITE_OK) {
                (*_os) << errMsg << std::endl;
                return -1;
            }

        } else {
            (*_os) << "Hit " << pnRow << " Results:" << std::endl;
            int i, j;
            for (i = 0; i <= pnRow; i++) {
                for (j = 0; j < pnCol; j++) {
                    if (j > 0) (*_os) << '\t';
                    (*_os) << query[i * pnCol + j];
                }
                (*_os) << std::endl;
            }
        }
        sqlite3_free_table(query);
        query = NULL;
        return 0;
    }
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

/// @file
///     @brief This class mimics QTemporaryFile. We have our own implementation due to the fact that
///				QTemporaryFile implemenation differs cross platform making it unusable for our use-case.
///				Look for bug reports on QTemporaryFile keeping the file locked for details.
///
///     @author Don Gagne <don@thegagnes.com>

#include "QGCTemporaryFile.h"

#include <QDir>
#include <QStandardPaths>

QGCTemporaryFile::QGCTemporaryFile(const QString& fileTemplate, QObject* parent) :
    QFile(parent),
    _template(fileTemplate)
{

}

bool QGCTemporaryFile::open(QFile::OpenMode openMode)
{
    QDir tempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));

    // Generate unique, non-existing filename

    static const char rgDigits[] = "0123456789";

    QString tempFilename;

    do {
        QString uniqueStr;
        for (int i=0; i<6; i++) {
            uniqueStr += rgDigits[qrand() % 10];
        }

        if (_template.contains("XXXXXX")) {
            tempFilename = _template.replace("XXXXXX", uniqueStr, Qt::CaseSensitive);
        } else {
            tempFilename = _template + uniqueStr;
        }
    } while (tempDir.exists(tempFilename));

    setFileName(tempDir.filePath(tempFilename));

    return QFile::open(openMode);
}
<commit_msg>QGCTemporaryFile: Remove deprecated qrand<commit_after>/****************************************************************************
 *
 * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

/// @file
///     @brief This class mimics QTemporaryFile. We have our own implementation due to the fact that
///				QTemporaryFile implemenation differs cross platform making it unusable for our use-case.
///				Look for bug reports on QTemporaryFile keeping the file locked for details.
///
///     @author Don Gagne <don@thegagnes.com>

#include "QGCTemporaryFile.h"

#include <QDir>
#include <QRandomGenerator>
#include <QStandardPaths>

QGCTemporaryFile::QGCTemporaryFile(const QString& fileTemplate, QObject* parent) :
    QFile(parent),
    _template(fileTemplate)
{

}

bool QGCTemporaryFile::open(QFile::OpenMode openMode)
{
    QDir tempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));

    // Generate unique, non-existing filename

    static const char rgDigits[] = "0123456789";

    QString tempFilename;

    do {
        QString uniqueStr;
        for (int i=0; i<6; i++) {
            uniqueStr += rgDigits[QRandomGenerator::global()->generate() % 10];
        }

        if (_template.contains("XXXXXX")) {
            tempFilename = _template.replace("XXXXXX", uniqueStr, Qt::CaseSensitive);
        } else {
            tempFilename = _template + uniqueStr;
        }
    } while (tempDir.exists(tempFilename));

    setFileName(tempDir.filePath(tempFilename));

    return QFile::open(openMode);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 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 <boost/test/unit_test.hpp>
#include "flat_mutation_reader.hh"

// Intended to be called in a seastar thread
class flat_reader_assertions {
    flat_mutation_reader _reader;
private:
    mutation_fragment_opt read_next() {
        return _reader().get0();
    }
public:
    flat_reader_assertions(flat_mutation_reader reader)
        : _reader(std::move(reader))
    { }

    flat_reader_assertions& produces_partition_start(const dht::decorated_key& dk) {
        BOOST_TEST_MESSAGE(sprint("Expecting partition start with key %s", dk));
        auto mfopt = read_next();
        if (!mfopt) {
            BOOST_FAIL(sprint("Expected: partition start with key %s, got end of stream", dk));
        }
        if (!mfopt->is_partition_start()) {
            BOOST_FAIL(sprint("Expected: partition start with key %s, got: %s", dk, *mfopt));
        }
        if (!mfopt->as_partition_start().key().equal(*_reader.schema(), dk)) {
            BOOST_FAIL(sprint("Expected: partition start with key %s, got: %s", dk, *mfopt));
        }
        return *this;
    }

    flat_reader_assertions& produces_static_row() {
        BOOST_TEST_MESSAGE(sprint("Expecting static row"));
        auto mfopt = read_next();
        if (!mfopt) {
            BOOST_FAIL("Expected static row, got end of stream");
        }
        if (!mfopt->is_static_row()) {
            BOOST_FAIL(sprint("Expected static row, got: %s", *mfopt));
        }
        return *this;
    }

    flat_reader_assertions& produces_row_with_key(const clustering_key& ck) {
        BOOST_TEST_MESSAGE(sprint("Expect %s", ck));
        auto mfopt = read_next();
        if (!mfopt) {
            BOOST_FAIL(sprint("Expected row with key %s, but got end of stream", ck));
        }
        if (!mfopt->is_clustering_row()) {
            BOOST_FAIL(sprint("Expected row with key %s, but got %s", ck, *mfopt));
        }
        auto& actual = mfopt->as_clustering_row().key();
        if (!actual.equal(*_reader.schema(), ck)) {
            BOOST_FAIL(sprint("Expected row with key %s, but key is %s", ck, actual));
        }
        return *this;
    }

    flat_reader_assertions& produces_partition_end() {
        BOOST_TEST_MESSAGE("Expecting partition end");
        auto mfopt = read_next();
        if (!mfopt) {
            BOOST_FAIL(sprint("Expected partition end but got end of stream"));
        }
        if (!mfopt->is_end_of_partition()) {
            BOOST_FAIL(sprint("Expected partition end but got %s", *mfopt));
        }
        return *this;
    }

    flat_reader_assertions& produces_end_of_stream() {
        BOOST_TEST_MESSAGE("Expecting end of stream");
        auto mfopt = read_next();
        if (bool(mfopt)) {
            BOOST_FAIL(sprint("Expected end of stream, got %s", *mfopt));
        }
        return *this;
    }

    flat_reader_assertions& fast_forward_to(const dht::partition_range& pr) {
        _reader.fast_forward_to(pr);
        return *this;
    }

    flat_reader_assertions& next_partition() {
        _reader.next_partition();
        return *this;
    }
};

inline
flat_reader_assertions assert_that(flat_mutation_reader r) {
    return { std::move(r) };
}
<commit_msg>flat_mutation_reader_assertions: add fast_forward_to(position_range)<commit_after>/*
 * Copyright (C) 2017 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 <boost/test/unit_test.hpp>
#include "flat_mutation_reader.hh"

// Intended to be called in a seastar thread
class flat_reader_assertions {
    flat_mutation_reader _reader;
private:
    mutation_fragment_opt read_next() {
        return _reader().get0();
    }
public:
    flat_reader_assertions(flat_mutation_reader reader)
        : _reader(std::move(reader))
    { }

    flat_reader_assertions& produces_partition_start(const dht::decorated_key& dk) {
        BOOST_TEST_MESSAGE(sprint("Expecting partition start with key %s", dk));
        auto mfopt = read_next();
        if (!mfopt) {
            BOOST_FAIL(sprint("Expected: partition start with key %s, got end of stream", dk));
        }
        if (!mfopt->is_partition_start()) {
            BOOST_FAIL(sprint("Expected: partition start with key %s, got: %s", dk, *mfopt));
        }
        if (!mfopt->as_partition_start().key().equal(*_reader.schema(), dk)) {
            BOOST_FAIL(sprint("Expected: partition start with key %s, got: %s", dk, *mfopt));
        }
        return *this;
    }

    flat_reader_assertions& produces_static_row() {
        BOOST_TEST_MESSAGE(sprint("Expecting static row"));
        auto mfopt = read_next();
        if (!mfopt) {
            BOOST_FAIL("Expected static row, got end of stream");
        }
        if (!mfopt->is_static_row()) {
            BOOST_FAIL(sprint("Expected static row, got: %s", *mfopt));
        }
        return *this;
    }

    flat_reader_assertions& produces_row_with_key(const clustering_key& ck) {
        BOOST_TEST_MESSAGE(sprint("Expect %s", ck));
        auto mfopt = read_next();
        if (!mfopt) {
            BOOST_FAIL(sprint("Expected row with key %s, but got end of stream", ck));
        }
        if (!mfopt->is_clustering_row()) {
            BOOST_FAIL(sprint("Expected row with key %s, but got %s", ck, *mfopt));
        }
        auto& actual = mfopt->as_clustering_row().key();
        if (!actual.equal(*_reader.schema(), ck)) {
            BOOST_FAIL(sprint("Expected row with key %s, but key is %s", ck, actual));
        }
        return *this;
    }

    flat_reader_assertions& produces_partition_end() {
        BOOST_TEST_MESSAGE("Expecting partition end");
        auto mfopt = read_next();
        if (!mfopt) {
            BOOST_FAIL(sprint("Expected partition end but got end of stream"));
        }
        if (!mfopt->is_end_of_partition()) {
            BOOST_FAIL(sprint("Expected partition end but got %s", *mfopt));
        }
        return *this;
    }

    flat_reader_assertions& produces_end_of_stream() {
        BOOST_TEST_MESSAGE("Expecting end of stream");
        auto mfopt = read_next();
        if (bool(mfopt)) {
            BOOST_FAIL(sprint("Expected end of stream, got %s", *mfopt));
        }
        return *this;
    }

    flat_reader_assertions& fast_forward_to(const dht::partition_range& pr) {
        _reader.fast_forward_to(pr);
        return *this;
    }

    flat_reader_assertions& next_partition() {
        _reader.next_partition();
        return *this;
    }

    flat_reader_assertions& fast_forward_to(position_range pr) {
        _reader.fast_forward_to(std::move(pr));
        return *this;
    }
};

inline
flat_reader_assertions assert_that(flat_mutation_reader r) {
    return { std::move(r) };
}
<|endoftext|>


<commit_before>#include "ros/ros.h"
#include <gtest/gtest.h>
#include "sensor_msgs/Imu.h"
#include "sensor_msgs/FluidPressure.h"
#include "nav_msgs/Odometry.h"

// Pub imu/pressure and imu/data
// Sub state_estimate
// only msg.pose.pose.orientation and pose.pose.position.z are set
// all others should be zero

class EstimatorTest : public ::testing::Test
{
public:
  EstimatorTest()
  {
    imuPub = nh.advertise<sensor_msgs::Imu>("imu/data", 10);
    pressurePub = nh.advertise<sensor_msgs::FluidPressure>("imu/pressure", 10);
    sub = nh.subscribe("state_estimate", 10, &EstimatorTest::Callback, this);
    message_received = false;
  }

  void SetUp()
  {
    while (!IsNodeReady())
      ros::spinOnce();
  }

  void PublishOrientation(double w, double x, double y, double z)
  {
    sensor_msgs::Imu msg;
    msg.orientation.w = w;
    msg.orientation.x = x;
    msg.orientation.y = y;
    msg.orientation.z = z;
    imuPub.publish(msg);
  }

  void PublishPressure(double p)
  {
    sensor_msgs::FluidPressure msg;
    msg.fluid_pressure = p;
    pressurePub.publish(msg);
  }

  void WaitForMessage()
  {
    while (!message_received)
      ros::spinOnce();
  }

  // Orientation quaternion
  double q_w;
  double q_x;
  double q_y;
  double q_z;

  double depth;

  const double MAX_ERROR = 1e-4;

 private:
  ros::NodeHandle nh;
  ros::Publisher  imuPub;
  ros::Publisher  pressurePub;
  ros::Subscriber sub;
  bool message_received;

  void Callback(const nav_msgs::Odometry& msg)
  {
    q_w   = msg.pose.pose.orientation.w;
    q_x   = msg.pose.pose.orientation.x;
    q_y   = msg.pose.pose.orientation.y;
    q_z   = msg.pose.pose.orientation.z;
    depth = msg.pose.pose.position.z;
    message_received = true;
  }

  bool IsNodeReady()
  {
    return (imuPub.getNumSubscribers() > 0)
      && (pressurePub.getNumSubscribers() > 0)
      && (sub.getNumPublishers() > 0);
  }
};

TEST_F(EstimatorTest, CheckResponsiveness)
{
  PublishOrientation(1, 0, 0, 0);
  PublishPressure(0);
  WaitForMessage();
}

TEST_F(EstimatorTest, OrientationCorrect)
{
  PublishOrientation(1, 2, 3, 4);
  WaitForMessage();
  EXPECT_NEAR(q_w, 1, MAX_ERROR);
  EXPECT_NEAR(q_x, 2, MAX_ERROR);
  EXPECT_NEAR(q_y, 3, MAX_ERROR);
  EXPECT_NEAR(q_z, 4, MAX_ERROR);
}

TEST_F(EstimatorTest, DepthCorrect)
{
  PublishPressure(200000);
  WaitForMessage();
  EXPECT_NEAR(depth, 10.0728, MAX_ERROR);
}

int main(int argc, char **argv)
{
  testing::InitGoogleTest(&argc, argv);
  ros::init(argc, argv, "estimator_test");

  int ret = RUN_ALL_TESTS();
  ros::shutdown();
  return ret;
}
<commit_msg>Update topic names<commit_after>#include "ros/ros.h"
#include <gtest/gtest.h>
#include "sensor_msgs/Imu.h"
#include "sensor_msgs/FluidPressure.h"
#include "nav_msgs/Odometry.h"

// Pub imu/pressure and imu/data
// Sub state_estimate
// only msg.pose.pose.orientation and pose.pose.position.z are set
// all others should be zero

class EstimatorTest : public ::testing::Test
{
public:
  EstimatorTest()
  {
    imuPub = nh.advertise<sensor_msgs::Imu>("/sensors/imu/data", 10);
    pressurePub = nh.advertise<sensor_msgs::FluidPressure>("/sensors/pressure", 10);
    sub = nh.subscribe("state_estimate", 10, &EstimatorTest::Callback, this);
    message_received = false;
  }

  void SetUp()
  {
    while (!IsNodeReady())
      ros::spinOnce();
  }

  void PublishOrientation(double w, double x, double y, double z)
  {
    sensor_msgs::Imu msg;
    msg.orientation.w = w;
    msg.orientation.x = x;
    msg.orientation.y = y;
    msg.orientation.z = z;
    imuPub.publish(msg);
  }

  void PublishPressure(double p)
  {
    sensor_msgs::FluidPressure msg;
    msg.fluid_pressure = p;
    pressurePub.publish(msg);
  }

  void WaitForMessage()
  {
    while (!message_received)
      ros::spinOnce();
  }

  // Orientation quaternion
  double q_w;
  double q_x;
  double q_y;
  double q_z;

  double depth;

  const double MAX_ERROR = 1e-4;

 private:
  ros::NodeHandle nh;
  ros::Publisher  imuPub;
  ros::Publisher  pressurePub;
  ros::Subscriber sub;
  bool message_received;

  void Callback(const nav_msgs::Odometry& msg)
  {
    q_w   = msg.pose.pose.orientation.w;
    q_x   = msg.pose.pose.orientation.x;
    q_y   = msg.pose.pose.orientation.y;
    q_z   = msg.pose.pose.orientation.z;
    depth = msg.pose.pose.position.z;
    message_received = true;
  }

  bool IsNodeReady()
  {
    return (imuPub.getNumSubscribers() > 0)
      && (pressurePub.getNumSubscribers() > 0)
      && (sub.getNumPublishers() > 0);
  }
};

TEST_F(EstimatorTest, CheckResponsiveness)
{
  PublishOrientation(1, 0, 0, 0);
  PublishPressure(0);
  WaitForMessage();
}

TEST_F(EstimatorTest, OrientationCorrect)
{
  PublishOrientation(1, 2, 3, 4);
  WaitForMessage();
  EXPECT_NEAR(q_w, 1, MAX_ERROR);
  EXPECT_NEAR(q_x, 2, MAX_ERROR);
  EXPECT_NEAR(q_y, 3, MAX_ERROR);
  EXPECT_NEAR(q_z, 4, MAX_ERROR);
}

TEST_F(EstimatorTest, DepthCorrect)
{
  PublishPressure(200000);
  WaitForMessage();
  EXPECT_NEAR(depth, 10.0728, MAX_ERROR);
}

int main(int argc, char **argv)
{
  testing::InitGoogleTest(&argc, argv);
  ros::init(argc, argv, "estimator_test");

  int ret = RUN_ALL_TESTS();
  ros::shutdown();
  return ret;
}
<|endoftext|>


<commit_before><commit_msg>String: Use ABS macro in padding code<commit_after><|endoftext|>


<commit_before>//
//  Player.cpp
//  labshooter
//
//  Created by Pawel Miniszewski on 07.12.2014.
//  Copyright (c) 2014 Pawel Miniszewski. All rights reserved.
//

#include "Player.h"

#include "Level.h"
#include "Bullet.h"
#include "ResourceCache.h"

Player::Player(int i) : Entity(), index(i), toBullet(500), rotationRate(0.5f), maxSpeed(.5)
{
}

Player::~Player()
{

}

void Player::Update(float dt)
{
    sf::Transform tr;
    tr.rotate(GetRotation());
    bool inputChanged = false;
    sf::Vector2f dir(0,0);
    float rotAngle = 0;

    if(sf::Keyboard::isKeyPressed((index == 0) ? sf::Keyboard::D : sf::Keyboard::Right))
    {
        //dir.x += 1;
        rotAngle = rotationRate;
        inputChanged = true;
    }
    if(sf::Keyboard::isKeyPressed((index == 0) ? sf::Keyboard::A : sf::Keyboard::Left))
    {
        //dir.x += -1;
        tr.rotate(0.5 * dt);
        rotAngle = -rotationRate;
        inputChanged = true;
    }
    if(sf::Keyboard::isKeyPressed((index == 0) ? sf::Keyboard::W : sf::Keyboard::Up))
    {
        dir.y += -maxSpeed;
        inputChanged = true;
    }
    if(sf::Keyboard::isKeyPressed((index == 0) ? sf::Keyboard::S : sf::Keyboard::Down))
    {
        dir.y += maxSpeed;
        inputChanged = true;
    }
    rotAngle *= dt;
    tr.rotate(rotAngle);
    dir = tr.transformPoint(dir);
    dir.x *= 0.5 * dt;
    dir.y *= 0.5 * dt;

    if (inputChanged)
    {
        Rotate(rotAngle);

        Move(sf::Vector2f(dir.x, 0));
        collider->setPosition(sprite->getPosition());
        auto c = level->getCollisions(this);
        if(c.size())
        {
            Move(sf::Vector2f((dir.x > 0 ? -1.0 : 1.0) * c[0].second.width, 0));
            collider->setPosition(sprite->getPosition());
        }

        Move(sf::Vector2f(0, dir.y));
        collider->setPosition(sprite->getPosition());
        c = level->getCollisions(this);
        if(c.size())
        {
            Move(sf::Vector2f(0, (dir.y > 0 ? -1.0 : 1.0) * c[0].second.height));
            collider->setPosition(sprite->getPosition());
        }
        //printf("Input dir: %f %f\r\n", dir.x, dir.y);

    }

    toBullet -= dt;
    if(sf::Keyboard::isKeyPressed((index == 0) ? sf::Keyboard::Space : sf::Keyboard::LControl) && toBullet <= 0)
    {
        toBullet = 500;
        Entity* b = new Bullet(sf::Vector2f(1.0, 1.0));
        b->SetTexture(ResourceCache::LoadTexture("assets/tile.png"));
        b->SetPosition(sprite->getPosition());
        level->Spawn(b);
    }
}

bool Player::CollidesWith(Entity* e, sf::FloatRect& collision)
{
    return e->GetTag() == "environment" && collider->getGlobalBounds().intersects(e->sprite->getGlobalBounds(), collision);
}

void Player::SetTexture(sf::Texture* texture)
{
    Entity::SetTexture(texture);
    collider = new sf::Sprite(*sprite);
}

std::string Player::GetTag()
{
    return "player";
}
<commit_msg>Shooting in right direction.<commit_after>//
//  Player.cpp
//  labshooter
//
//  Created by Pawel Miniszewski on 07.12.2014.
//  Copyright (c) 2014 Pawel Miniszewski. All rights reserved.
//

#include "Player.h"

#include "Level.h"
#include "Bullet.h"
#include "ResourceCache.h"

Player::Player(int i) : Entity(), index(i), toBullet(500), rotationRate(0.5f), maxSpeed(.5)
{
}

Player::~Player()
{

}

void Player::Update(float dt)
{
    sf::Transform tr;
    tr.rotate(GetRotation());
    bool inputChanged = false;
    sf::Vector2f dir(0,0);
    float rotAngle = 0;

    if(sf::Keyboard::isKeyPressed((index == 0) ? sf::Keyboard::D : sf::Keyboard::Right))
    {
        //dir.x += 1;
        rotAngle = rotationRate;
        inputChanged = true;
    }
    if(sf::Keyboard::isKeyPressed((index == 0) ? sf::Keyboard::A : sf::Keyboard::Left))
    {
        //dir.x += -1;
        tr.rotate(0.5 * dt);
        rotAngle = -rotationRate;
        inputChanged = true;
    }
    if(sf::Keyboard::isKeyPressed((index == 0) ? sf::Keyboard::W : sf::Keyboard::Up))
    {
        dir.y += -maxSpeed;
        inputChanged = true;
    }
    if(sf::Keyboard::isKeyPressed((index == 0) ? sf::Keyboard::S : sf::Keyboard::Down))
    {
        dir.y += maxSpeed;
        inputChanged = true;
    }
    rotAngle *= dt;
    tr.rotate(rotAngle);
    dir = tr.transformPoint(dir);
    dir.x *= 0.5 * dt;
    dir.y *= 0.5 * dt;

    if (inputChanged)
    {
        Rotate(rotAngle);

        Move(sf::Vector2f(dir.x, 0));
        collider->setPosition(sprite->getPosition());
        auto c = level->getCollisions(this);
        if(c.size())
        {
            Move(sf::Vector2f((dir.x > 0 ? -1.0 : 1.0) * c[0].second.width, 0));
            collider->setPosition(sprite->getPosition());
        }

        Move(sf::Vector2f(0, dir.y));
        collider->setPosition(sprite->getPosition());
        c = level->getCollisions(this);
        if(c.size())
        {
            Move(sf::Vector2f(0, (dir.y > 0 ? -1.0 : 1.0) * c[0].second.height));
            collider->setPosition(sprite->getPosition());
        }
        //printf("Input dir: %f %f\r\n", dir.x, dir.y);

    }

    toBullet -= dt;
    if(sf::Keyboard::isKeyPressed((index == 0) ? sf::Keyboard::Space : sf::Keyboard::LControl) && toBullet <= 0)
    {
        sf::Transform transform;
        transform.rotate(GetRotation());
        toBullet = 500;
        Entity* b = new Bullet(transform.transformPoint(sf::Vector2f(0.0, -1.0)));
        b->SetTexture(ResourceCache::LoadTexture("assets/tile.png"));
        b->SetPosition(sprite->getPosition());
        level->Spawn(b);
    }
}

bool Player::CollidesWith(Entity* e, sf::FloatRect& collision)
{
    return e->GetTag() == "environment" && collider->getGlobalBounds().intersects(e->sprite->getGlobalBounds(), collision);
}

void Player::SetTexture(sf::Texture* texture)
{
    Entity::SetTexture(texture);
    collider = new sf::Sprite(*sprite);
}

std::string Player::GetTag()
{
    return "player";
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include<hip/hip_runtime.h>
#include<hip/hip_runtime_api.h>
#include<iostream>

#define HIP_ASSERT(status) assert(hipSuccess == status);

#define NUM  1024
#define SIZE NUM * 8

__global__ void Alloc(hipLaunchParm lp, uint64_t *Ptr) {
    int tid = hipThreadIdx_x + hipBlockIdx_x * hipBlockDim_x;
    Ptr[tid] = (uint64_t)malloc(128);
}

__global__ void Free(hipLaunchParm lp, uint64_t *Ptr) {
    int tid = hipThreadIdx_x + hipBlockIdx_x * hipBlockDim_x;
    free((void*)Ptr[tid]);
}

int main()
{
    uint64_t *hPtr, *dPtr;
    hPtr = new uint64_t[NUM];
    for(uint32_t i=0;i<NUM;i++) {
        hPtr[i] = 1;
    }
    int devCnt;
    hipGetDeviceCount(&devCnt);
    for(uint32_t i=0;i<devCnt;i++){
        HIP_ASSERT(hipSetDevice(i));
        HIP_ASSERT(hipMalloc((void**)&dPtr, SIZE));
        HIP_ASSERT(hipMemcpy(dPtr, hPtr, SIZE, hipMemcpyHostToDevice));
        hipLaunchKernel(Alloc, dim3(1,1,1), dim3(NUM,1,1), 0, 0, dPtr);
        HIP_ASSERT(hipMemcpy(hPtr, dPtr, SIZE, hipMemcpyDeviceToHost));
        hipLaunchKernel(Free, dim3(1,1,1), dim3(NUM,1,1), 0, 0, dPtr);
        HIP_ASSERT(hipFree(dPtr));
        for(uint32_t i=1;i<NUM;i++) {
            assert(hPtr[i] == hPtr[i-1] + 4096);
        }
    }
}
<commit_msg>make sure the global variable does not give zero<commit_after>/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include<hip/hip_runtime.h>
#include<hip/hip_runtime_api.h>
#include<iostream>

#define HIP_ASSERT(status) assert(hipSuccess == status);

#define NUM  1024
#define SIZE NUM * 8

__global__ void Alloc(hipLaunchParm lp, uint64_t *Ptr) {
    int tid = hipThreadIdx_x + hipBlockIdx_x * hipBlockDim_x;
    Ptr[tid] = (uint64_t)malloc(128);
}

__global__ void Free(hipLaunchParm lp, uint64_t *Ptr) {
    int tid = hipThreadIdx_x + hipBlockIdx_x * hipBlockDim_x;
    free((void*)Ptr[tid]);
}

int main()
{
    uint64_t *hPtr, *dPtr;
    hPtr = new uint64_t[NUM];
    for(uint32_t i=0;i<NUM;i++) {
        hPtr[i] = 1;
    }
    int devCnt;
    hipGetDeviceCount(&devCnt);
    for(uint32_t i=0;i<devCnt;i++){
        HIP_ASSERT(hipSetDevice(i));
        HIP_ASSERT(hipMalloc((void**)&dPtr, SIZE));
        HIP_ASSERT(hipMemcpy(dPtr, hPtr, SIZE, hipMemcpyHostToDevice));
        hipLaunchKernel(Alloc, dim3(1,1,1), dim3(NUM,1,1), 0, 0, dPtr);
        HIP_ASSERT(hipMemcpy(hPtr, dPtr, SIZE, hipMemcpyDeviceToHost));
        assert(hPtr[0] != 0);
        hipLaunchKernel(Free, dim3(1,1,1), dim3(NUM,1,1), 0, 0, dPtr);
        HIP_ASSERT(hipFree(dPtr));
        for(uint32_t i=1;i<NUM;i++) {
            assert(hPtr[i] == hPtr[i-1] + 4096);
        }
    }
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <boost/variant/apply_visitor.hpp>

#include "FunctionContext.hpp"
#include "Variable.hpp"
#include "Utils.hpp"
#include "GetConstantValue.hpp"
#include "VisitorUtils.hpp"

using namespace eddic;

FunctionContext::FunctionContext(std::shared_ptr<Context> parent) : Context(parent), currentPosition(4), currentParameter(8), temporary(1) {}

int FunctionContext::size() const {
    return currentPosition - 4;
}

std::shared_ptr<Variable> FunctionContext::newParameter(const std::string& variable, Type type){
    Position position(PositionType::PARAMETER, currentParameter + (::size(type) - 4));

    currentParameter += ::size(type);

    return std::make_shared<Variable>(variable, type, position);
}

std::shared_ptr<Variable> FunctionContext::newVariable(const std::string& variable, Type type){
    Position position(PositionType::STACK, currentPosition);

    currentPosition += ::size(type);

    return std::make_shared<Variable>(variable, type, position);
}

std::shared_ptr<Variable> FunctionContext::addVariable(const std::string& variable, Type type){
    return variables[variable] = newVariable(variable, type);
}

std::shared_ptr<Variable> FunctionContext::addVariable(const std::string& variable, Type type, ast::Value& value){
    assert(type.isConst());

    Position position(PositionType::CONST);

    auto val = visit(GetConstantValue(), value);

    return variables[variable] = std::make_shared<Variable>(variable, type, position, val);
}

std::shared_ptr<Variable> FunctionContext::addParameter(const std::string& parameter, Type type){
    return variables[parameter] = newParameter(parameter, type);
}

std::shared_ptr<Variable> FunctionContext::newTemporary(){
    Position position(PositionType::TEMPORARY);

    std::string name = "t_" + toString(temporary++);
    Type type(BaseType::INT, false);

    return variables[name] = std::make_shared<Variable>(name, type, position);
}

void FunctionContext::storeTemporary(std::shared_ptr<Variable> temp){
    Position position(PositionType::STACK, currentPosition);

    currentPosition += ::size(temp->type());

    temp->setPosition(position);
}
<commit_msg>Use size of int instead of hard coded constant<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <boost/variant/apply_visitor.hpp>

#include "FunctionContext.hpp"
#include "Variable.hpp"
#include "Utils.hpp"
#include "GetConstantValue.hpp"
#include "VisitorUtils.hpp"

using namespace eddic;

FunctionContext::FunctionContext(std::shared_ptr<Context> parent) :
    Context(parent), currentPosition(size(BaseType::INT)), currentParameter(2 * size(BaseType::INT)), temporary(1) {}

int FunctionContext::size() const {
    return currentPosition - size(BaseType::INT);
}

std::shared_ptr<Variable> FunctionContext::newParameter(const std::string& variable, Type type){
    Position position(PositionType::PARAMETER, currentParameter + (::size(type) - size(BaseType::INT)));

    currentParameter += ::size(type);

    return std::make_shared<Variable>(variable, type, position);
}

std::shared_ptr<Variable> FunctionContext::newVariable(const std::string& variable, Type type){
    Position position(PositionType::STACK, currentPosition);

    currentPosition += ::size(type);

    return std::make_shared<Variable>(variable, type, position);
}

std::shared_ptr<Variable> FunctionContext::addVariable(const std::string& variable, Type type){
    return variables[variable] = newVariable(variable, type);
}

std::shared_ptr<Variable> FunctionContext::addVariable(const std::string& variable, Type type, ast::Value& value){
    assert(type.isConst());

    Position position(PositionType::CONST);

    auto val = visit(GetConstantValue(), value);

    return variables[variable] = std::make_shared<Variable>(variable, type, position, val);
}

std::shared_ptr<Variable> FunctionContext::addParameter(const std::string& parameter, Type type){
    return variables[parameter] = newParameter(parameter, type);
}

std::shared_ptr<Variable> FunctionContext::newTemporary(){
    Position position(PositionType::TEMPORARY);

    std::string name = "t_" + toString(temporary++);
    Type type(BaseType::INT, false);

    return variables[name] = std::make_shared<Variable>(name, type, position);
}

void FunctionContext::storeTemporary(std::shared_ptr<Variable> temp){
    Position position(PositionType::STACK, currentPosition);

    currentPosition += ::size(temp->type());

    temp->setPosition(position);
}
<|endoftext|>