<commit_before>#include <boost/shared_ptr.hpp>
#include <lcm/lcm-cpp.hpp>

#include <lcmtypes/bot_core.hpp>

#include <pointcloud_tools/pointcloud_vis.hpp>
#include <bot_frames_cpp/bot_frames_cpp.hpp>
#include <path_util/path_util.h>
#include <ConciseArgs>

#include "visualization/collections.hpp"

#include "kdl/tree.hpp"
#include <estimate/common_conversions.hpp>

using namespace std;

////////////////////////////////////////
struct CommandLineConfig
{
};

class App{
  public:
    App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_);

    ~App(){
    }
  private:
    boost::shared_ptr<lcm::LCM> lcm_;
    BotParam* botparam_;
    bot::frames* frames_cpp_;
    BotFrames* frames_;

    /////////
    void poseBDIHandler(const lcm::ReceiveBuffer* rbuf,
                           const std::string& channel, const  bot_core::pose_t* msg);

    const CommandLineConfig cl_cfg_;
    pointcloud_vis* pc_vis_;

    Eigen::Isometry3d prev_worldbdi_to_body_;
    int64_t prev_vicon_utime_;
};

App::App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_):
    lcm_(lcm_), cl_cfg_(cl_cfg_){

  //if (cl_cfg_.param_file == ""){
  //   botparam_ = bot_param_new_from_server(lcm_->getUnderlyingLCM(), 0);
  //}else{
    std::string param_file = "drc_robot_02.cfg";
    std::string param_file_full = std::string(getConfigPath()) +'/' + std::string(param_file);
    botparam_ = bot_param_new_from_file(param_file_full.c_str());
  //}
  // TODO: not sure what do do here ... what if i want the frames from the file?
  //frames_ = bot_frames_new(NULL, botparam_);
  frames_ = bot_frames_get_global(lcm_->getUnderlyingLCM(), botparam_);
  frames_cpp_ = new bot::frames(frames_);

  //  frames_cpp_ = new bot::frames( lcm_);

  lcm_->subscribe("POSE_BDI",&App::poseBDIHandler,this);

  // Vis Config:
  pc_vis_ = new pointcloud_vis( lcm_->getUnderlyingLCM());
  pc_vis_->obj_cfg_list.push_back( obj_cfg(10032,"Vicon (v)",5,1) );
  pc_vis_->obj_cfg_list.push_back( obj_cfg(10033,"Vicon at init",5,1) );
  pc_vis_->obj_cfg_list.push_back( obj_cfg(10034,"Vicon (v all)",5,0) );
  pc_vis_->pose_collection_reset(10034,"Vicon (v all)");
  // 10035 - link

  prev_vicon_utime_ =0;
}

void App::poseBDIHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  bot_core::pose_t* msg){
  Eigen::Isometry3d worldbdi_to_body;
  worldbdi_to_body.setIdentity();
  worldbdi_to_body.translation()  << msg->pos[0], msg->pos[1] , msg->pos[2];
  Eigen::Quaterniond quat = Eigen::Quaterniond(msg->orientation[0], msg->orientation[1],
                                            msg->orientation[2], msg->orientation[3]);
  worldbdi_to_body.rotate(quat);

  Eigen::Isometry3d body_to_frontplate;
  frames_cpp_->get_trans_with_utime( "frontplate_vicon" ,"body_vicon" , msg->utime, body_to_frontplate);
  Eigen::Isometry3d worldbdi_to_frontplate = worldbdi_to_body * body_to_frontplate;

  bot_core::rigid_transform_t pose_msg;
  pose_msg.utime =   msg->utime;
  pose_msg.trans[0] = worldbdi_to_frontplate.translation().x();
  pose_msg.trans[1] = worldbdi_to_frontplate.translation().y();
  pose_msg.trans[2] = worldbdi_to_frontplate.translation().z();
  Eigen::Quaterniond r_x(worldbdi_to_frontplate.rotation());
  pose_msg.quat[0] =  r_x.w();
  pose_msg.quat[1] =  r_x.x();
  pose_msg.quat[2] =  r_x.y();
  pose_msg.quat[3] =  r_x.z();
  lcm_->publish( "VICON_FRONTPLATE" , &pose_msg);

  prev_vicon_utime_ = msg->utime;
}

int main(int argc, char ** argv) {
  CommandLineConfig cl_cfg;
//  opt.parse();

  boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM);
  if(!lcm->good()){
    std::cerr <<"ERROR: lcm is not good()" <<std::endl;
  }

  App app(lcm, cl_cfg);
  cout << "Tool ready" << endl << "============================" << endl;
  while(0 == lcm->handle());
  return 0;
}<commit_msg>clean up init from bdi tool<commit_after>// A basic tool to initialize the state estimator
// by pretending to be a vicon measurement
// TODO: depreciate this and use POSE_BDI directly within mav-est
#include <boost/shared_ptr.hpp>
#include <lcm/lcm-cpp.hpp>
#include <lcmtypes/bot_core.hpp>
#include <pointcloud_tools/pointcloud_vis.hpp>
#include <bot_frames_cpp/bot_frames_cpp.hpp>
#include <path_util/path_util.h>

using namespace std;

  struct CommandLineConfig
{
};

class App{
  public:
    App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_);

    ~App(){
    }
  private:
    boost::shared_ptr<lcm::LCM> lcm_;
    BotParam* botparam_;
    bot::frames* frames_cpp_;
    BotFrames* frames_;

    void poseBDIHandler(const lcm::ReceiveBuffer* rbuf,
                           const std::string& channel, const  bot_core::pose_t* msg);

    const CommandLineConfig cl_cfg_;
    Eigen::Isometry3d prev_worldbdi_to_body_;
    int64_t prev_vicon_utime_;
};

App::App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_):
    lcm_(lcm_), cl_cfg_(cl_cfg_){

  std::string param_file = "drc_robot_02.cfg";
  std::string param_file_full = std::string(getConfigPath()) +'/' + std::string(param_file);
  botparam_ = bot_param_new_from_file(param_file_full.c_str());
  frames_ = bot_frames_get_global(lcm_->getUnderlyingLCM(), botparam_);
  frames_cpp_ = new bot::frames(frames_);

  lcm_->subscribe("POSE_BDI",&App::poseBDIHandler,this);
}

void App::poseBDIHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  bot_core::pose_t* msg){
  Eigen::Isometry3d worldbdi_to_body;
  worldbdi_to_body.setIdentity();
  worldbdi_to_body.translation()  << msg->pos[0], msg->pos[1] , msg->pos[2];
  Eigen::Quaterniond quat = Eigen::Quaterniond(msg->orientation[0], msg->orientation[1],
                                            msg->orientation[2], msg->orientation[3]);
  worldbdi_to_body.rotate(quat);

  Eigen::Isometry3d body_to_frontplate;
  frames_cpp_->get_trans_with_utime( "frontplate_vicon" ,"body_vicon" , msg->utime, body_to_frontplate);
  Eigen::Isometry3d worldbdi_to_frontplate = worldbdi_to_body * body_to_frontplate;

  bot_core::rigid_transform_t pose_msg;
  pose_msg.utime =   msg->utime;
  pose_msg.trans[0] = worldbdi_to_frontplate.translation().x();
  pose_msg.trans[1] = worldbdi_to_frontplate.translation().y();
  pose_msg.trans[2] = worldbdi_to_frontplate.translation().z();
  Eigen::Quaterniond r_x(worldbdi_to_frontplate.rotation());
  pose_msg.quat[0] =  r_x.w();
  pose_msg.quat[1] =  r_x.x();
  pose_msg.quat[2] =  r_x.y();
  pose_msg.quat[3] =  r_x.z();
  lcm_->publish( "VICON_FRONTPLATE" , &pose_msg);
}

int main(int argc, char ** argv) {
  CommandLineConfig cl_cfg;

  boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM);
  if(!lcm->good()){
    std::cerr <<"ERROR: lcm is not good()" <<std::endl;
  }

  App app(lcm, cl_cfg);
  cout << "Tool ready" << endl << "============================" << endl;
  while(0 == lcm->handle());
  return 0;
}<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "graphicsobjectnodeinstance.h"

#include "invalidnodeinstanceexception.h"
#include <QGraphicsObject>
#include "private/qgraphicsitem_p.h"
#include <QStyleOptionGraphicsItem>
#include "nodemetainfo.h"

namespace QmlDesigner {
namespace Internal {

GraphicsObjectNodeInstance::GraphicsObjectNodeInstance(QGraphicsObject *graphicsObject, bool hasContent)
   : ObjectNodeInstance(graphicsObject),
   m_hasContent(hasContent)
{
}

QGraphicsObject *GraphicsObjectNodeInstance::graphicsObject() const
{
    if (object() == 0)
        return 0;

    Q_ASSERT(qobject_cast<QGraphicsObject*>(object()));
    return static_cast<QGraphicsObject*>(object());
}

bool GraphicsObjectNodeInstance::hasContent() const
{
    return m_hasContent;
}

QPointF GraphicsObjectNodeInstance::position() const
{
    return graphicsObject()->pos();
}

QSizeF GraphicsObjectNodeInstance::size() const
{
    return graphicsObject()->boundingRect().size();
}

QTransform GraphicsObjectNodeInstance::transform() const
{
    if (graphicsObject()->parentItem())
        return graphicsObject()->itemTransform(graphicsObject()->parentItem());
    else
        return sceneTransform();
}

QTransform GraphicsObjectNodeInstance::customTransform() const
{
    return graphicsObject()->transform();
}

QTransform GraphicsObjectNodeInstance::sceneTransform() const
{
    return graphicsObject()->sceneTransform();
}

double GraphicsObjectNodeInstance::rotation() const
{
    return graphicsObject()->rotation();
}

double GraphicsObjectNodeInstance::scale() const
{
    return graphicsObject()->scale();
}

QList<QGraphicsTransform *> GraphicsObjectNodeInstance::transformations() const
{
    return graphicsObject()->transformations();
}

QPointF GraphicsObjectNodeInstance::transformOriginPoint() const
{
    return graphicsObject()->transformOriginPoint();
}

double GraphicsObjectNodeInstance::zValue() const
{
    return graphicsObject()->zValue();
}

double GraphicsObjectNodeInstance::opacity() const
{
    return graphicsObject()->opacity();
}

QObject *GraphicsObjectNodeInstance::parent() const
{
    if (!graphicsObject() || !graphicsObject()->parentItem())
        return 0;

    return graphicsObject()->parentItem()->toGraphicsObject();
}

QRectF GraphicsObjectNodeInstance::boundingRect() const
{
    return graphicsObject()->boundingRect();
}

bool GraphicsObjectNodeInstance::isTopLevel() const
{
    Q_ASSERT(graphicsObject());
    return !graphicsObject()->parentItem();
}

bool GraphicsObjectNodeInstance::isGraphicsObject() const
{
    return true;
}

void GraphicsObjectNodeInstance::setPropertyVariant(const QString &name, const QVariant &value)
{
    ObjectNodeInstance::setPropertyVariant(name, value);
}

QVariant GraphicsObjectNodeInstance::property(const QString &name) const
{
    return ObjectNodeInstance::property(name);
}

bool GraphicsObjectNodeInstance::equalGraphicsItem(QGraphicsItem *item) const
{
    return item == graphicsObject();
}

void initOption(QGraphicsItem *item, QStyleOptionGraphicsItem *option, const QTransform &transform)
{
    QGraphicsItemPrivate *privateItem = QGraphicsItemPrivate::get(item);
    privateItem->initStyleOption(option, transform, QRegion());
}

void GraphicsObjectNodeInstance::paintRecursively(QGraphicsItem *graphicsItem, QPainter *painter) const
{
    if (graphicsItem->isVisible()) {
        painter->save();
        painter->setTransform(graphicsItem->itemTransform(graphicsItem->parentItem()), true);
        painter->setOpacity(graphicsItem->opacity() * painter->opacity());
        QStyleOptionGraphicsItem option;
        initOption(graphicsItem, &option, painter->transform());
        graphicsItem->paint(painter, &option);
        foreach(QGraphicsItem *childItem, graphicsItem->childItems()) {
            paintRecursively(childItem, painter);
        }
        painter->restore();
    }
}

void GraphicsObjectNodeInstance::paint(QPainter *painter) const
{
    painter->save();
    Q_ASSERT(graphicsObject());
    if (hasContent()) {
        QStyleOptionGraphicsItem option;
        initOption(graphicsObject(), &option, painter->transform());
        graphicsObject()->paint(painter, &option);

    }
    foreach(QGraphicsItem *graphicsItem, graphicsObject()->childItems()) {
        QGraphicsObject *graphicsObject = qgraphicsitem_cast<QGraphicsObject*>(graphicsItem);
        if (graphicsObject
            && !nodeInstanceView()->hasInstanceForObject(graphicsObject))
            paintRecursively(graphicsItem, painter);
    }

    painter->restore();
}

QPair<QGraphicsObject*, bool> GraphicsObjectNodeInstance::createGraphicsObject(const NodeMetaInfo &metaInfo, QDeclarativeContext *context)
{
    QObject *object = ObjectNodeInstance::createObject(metaInfo, context);
    QGraphicsObject *graphicsObject = qobject_cast<QGraphicsObject*>(object);

    if (graphicsObject == 0)
        throw InvalidNodeInstanceException(__LINE__, __FUNCTION__, __FILE__);

//    graphicsObject->setCacheMode(QGraphicsItem::ItemCoordinateCache);
    bool hasContent = !graphicsObject->flags().testFlag(QGraphicsItem::ItemHasNoContents) || metaInfo.isComponent();
    graphicsObject->setFlag(QGraphicsItem::ItemHasNoContents, false);

    return qMakePair(graphicsObject, hasContent);
}

void GraphicsObjectNodeInstance::paintUpdate()
{
    graphicsObject()->update();
}
} // namespace Internal
} // namespace QmlDesigner
<commit_msg>QmlDesigner.instances: fix  NodeInstance::parent()<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "graphicsobjectnodeinstance.h"

#include "invalidnodeinstanceexception.h"
#include <QGraphicsObject>
#include "private/qgraphicsitem_p.h"
#include <QStyleOptionGraphicsItem>
#include "nodemetainfo.h"

namespace QmlDesigner {
namespace Internal {

GraphicsObjectNodeInstance::GraphicsObjectNodeInstance(QGraphicsObject *graphicsObject, bool hasContent)
   : ObjectNodeInstance(graphicsObject),
   m_hasContent(hasContent)
{
}

QGraphicsObject *GraphicsObjectNodeInstance::graphicsObject() const
{
    if (object() == 0)
        return 0;

    Q_ASSERT(qobject_cast<QGraphicsObject*>(object()));
    return static_cast<QGraphicsObject*>(object());
}

bool GraphicsObjectNodeInstance::hasContent() const
{
    return m_hasContent;
}

QPointF GraphicsObjectNodeInstance::position() const
{
    return graphicsObject()->pos();
}

QSizeF GraphicsObjectNodeInstance::size() const
{
    return graphicsObject()->boundingRect().size();
}

QTransform GraphicsObjectNodeInstance::transform() const
{
    if (!nodeInstanceView()->hasInstanceForNode(modelNode()))
        return sceneTransform();

    NodeInstance nodeInstanceParent = nodeInstanceView()->instanceForNode(modelNode()).parent();

    if (!nodeInstanceParent.isValid())
        return sceneTransform();

    QGraphicsObject *graphicsObjectParent = qobject_cast<QGraphicsObject*>(nodeInstanceParent.internalObject());
    if (graphicsObjectParent)
        return graphicsObject()->itemTransform(graphicsObjectParent);
    else
        return sceneTransform();
}

QTransform GraphicsObjectNodeInstance::customTransform() const
{
    return graphicsObject()->transform();
}

QTransform GraphicsObjectNodeInstance::sceneTransform() const
{
    return graphicsObject()->sceneTransform();
}

double GraphicsObjectNodeInstance::rotation() const
{
    return graphicsObject()->rotation();
}

double GraphicsObjectNodeInstance::scale() const
{
    return graphicsObject()->scale();
}

QList<QGraphicsTransform *> GraphicsObjectNodeInstance::transformations() const
{
    return graphicsObject()->transformations();
}

QPointF GraphicsObjectNodeInstance::transformOriginPoint() const
{
    return graphicsObject()->transformOriginPoint();
}

double GraphicsObjectNodeInstance::zValue() const
{
    return graphicsObject()->zValue();
}

double GraphicsObjectNodeInstance::opacity() const
{
    return graphicsObject()->opacity();
}

QObject *GraphicsObjectNodeInstance::parent() const
{
    if (!graphicsObject() || !graphicsObject()->parentItem())
        return 0;

    return graphicsObject()->parentItem()->toGraphicsObject();
}

QRectF GraphicsObjectNodeInstance::boundingRect() const
{
    return graphicsObject()->boundingRect();
}

bool GraphicsObjectNodeInstance::isTopLevel() const
{
    Q_ASSERT(graphicsObject());
    return !graphicsObject()->parentItem();
}

bool GraphicsObjectNodeInstance::isGraphicsObject() const
{
    return true;
}

void GraphicsObjectNodeInstance::setPropertyVariant(const QString &name, const QVariant &value)
{
    ObjectNodeInstance::setPropertyVariant(name, value);
}

QVariant GraphicsObjectNodeInstance::property(const QString &name) const
{
    return ObjectNodeInstance::property(name);
}

bool GraphicsObjectNodeInstance::equalGraphicsItem(QGraphicsItem *item) const
{
    return item == graphicsObject();
}

void initOption(QGraphicsItem *item, QStyleOptionGraphicsItem *option, const QTransform &transform)
{
    QGraphicsItemPrivate *privateItem = QGraphicsItemPrivate::get(item);
    privateItem->initStyleOption(option, transform, QRegion());
}

void GraphicsObjectNodeInstance::paintRecursively(QGraphicsItem *graphicsItem, QPainter *painter) const
{
    if (graphicsItem->isVisible()) {
        painter->save();
        painter->setTransform(graphicsItem->itemTransform(graphicsItem->parentItem()), true);
        painter->setOpacity(graphicsItem->opacity() * painter->opacity());
        QStyleOptionGraphicsItem option;
        initOption(graphicsItem, &option, painter->transform());
        graphicsItem->paint(painter, &option);
        foreach(QGraphicsItem *childItem, graphicsItem->childItems()) {
            paintRecursively(childItem, painter);
        }
        painter->restore();
    }
}

void GraphicsObjectNodeInstance::paint(QPainter *painter) const
{
    painter->save();
    Q_ASSERT(graphicsObject());
    if (hasContent()) {
        QStyleOptionGraphicsItem option;
        initOption(graphicsObject(), &option, painter->transform());
        graphicsObject()->paint(painter, &option);

    }
    foreach(QGraphicsItem *graphicsItem, graphicsObject()->childItems()) {
        QGraphicsObject *graphicsObject = qgraphicsitem_cast<QGraphicsObject*>(graphicsItem);
        if (graphicsObject
            && !nodeInstanceView()->hasInstanceForObject(graphicsObject))
            paintRecursively(graphicsItem, painter);
    }

    painter->restore();
}

QPair<QGraphicsObject*, bool> GraphicsObjectNodeInstance::createGraphicsObject(const NodeMetaInfo &metaInfo, QDeclarativeContext *context)
{
    QObject *object = ObjectNodeInstance::createObject(metaInfo, context);
    QGraphicsObject *graphicsObject = qobject_cast<QGraphicsObject*>(object);

    if (graphicsObject == 0)
        throw InvalidNodeInstanceException(__LINE__, __FUNCTION__, __FILE__);

//    graphicsObject->setCacheMode(QGraphicsItem::ItemCoordinateCache);
    bool hasContent = !graphicsObject->flags().testFlag(QGraphicsItem::ItemHasNoContents) || metaInfo.isComponent();
    graphicsObject->setFlag(QGraphicsItem::ItemHasNoContents, false);

    return qMakePair(graphicsObject, hasContent);
}

void GraphicsObjectNodeInstance::paintUpdate()
{
    graphicsObject()->update();
}
} // namespace Internal
} // namespace QmlDesigner
<|endoftext|>


<commit_before>// Copyright 2013 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/ui/webui/signin/profile_signin_confirmation_dialog.h"

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/prefs/pref_notifier_impl.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/testing_pref_service.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/extensions/extension_manifest_constants.h"
#include "chrome/common/extensions/permissions/permission_set.h"
#include "chrome/test/base/testing_pref_service_syncable.h"
#include "chrome/test/base/testing_profile.h"
#include "components/user_prefs/pref_registry_syncable.h"
#include "content/public/test/test_browser_thread.h"
#include "content/public/test/test_utils.h"

#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

template<typename T>
void GetValueAndQuit(T* result, base::Closure quit, T actual) {
  *result = actual;
  quit.Run();
}

template<typename T>
T GetCallbackResult(base::Callback<void(base::Callback<void(T)>)> callback) {
  T result = false;
  scoped_refptr<content::MessageLoopRunner> runner =
      new content::MessageLoopRunner;
  callback.Run(base::Bind(&GetValueAndQuit<T>, &result,
                          base::Bind(&content::MessageLoopRunner::Quit,
                                     runner)));
  runner->Run();
  return result;
}

// A pref store that can have its read_error property changed for testing.
class TestingPrefStoreWithCustomReadError : public TestingPrefStore {
 public:
  TestingPrefStoreWithCustomReadError()
      : read_error_(PersistentPrefStore::PREF_READ_ERROR_NO_FILE) {
    // By default the profile is "new" (NO_FILE means that the profile
    // wasn't found on disk, so it was created).
  }
  virtual PrefReadError GetReadError() const OVERRIDE {
    return read_error_;
  }
  virtual bool IsInitializationComplete() const OVERRIDE {
    return true;
  }
  void set_read_error(PrefReadError read_error) {
    read_error_ = read_error;
  }
 private:
  virtual ~TestingPrefStoreWithCustomReadError() {}
  PrefReadError read_error_;
};

#if defined(OS_WIN)
const base::FilePath::CharType kExtensionFilePath[] =
    FILE_PATH_LITERAL("c:\\foo");
#elif defined(OS_POSIX)
const base::FilePath::CharType kExtensionFilePath[] =
    FILE_PATH_LITERAL("/oo");
#endif

static scoped_refptr<extensions::Extension> CreateExtension(
    const std::string& name,
    const std::string& id) {
  DictionaryValue manifest;
  manifest.SetString(extension_manifest_keys::kVersion, "1.0.0.0");
  manifest.SetString(extension_manifest_keys::kName, name);
  std::string error;
  scoped_refptr<extensions::Extension> extension =
    extensions::Extension::Create(
        base::FilePath(kExtensionFilePath).AppendASCII(name),
        extensions::Manifest::INTERNAL,
        manifest,
        extensions::Extension::NO_FLAGS,
        id,
        &error);
  return extension;
}

}  // namespace

class ProfileSigninConfirmationDialogTest : public testing::Test {
 public:
  ProfileSigninConfirmationDialogTest()
      : ui_thread_(BrowserThread::UI, &message_loop_) {
  }
  virtual ~ProfileSigninConfirmationDialogTest() {}

  virtual void SetUp() OVERRIDE {
    // Create the profile.
    TestingProfile::Builder builder;
    user_prefs_ = new TestingPrefStoreWithCustomReadError;
    TestingPrefServiceSyncable* pref_service = new TestingPrefServiceSyncable(
        new TestingPrefStore(),
        user_prefs_,
        new TestingPrefStore(),
        new PrefRegistrySyncable(),
        new PrefNotifierImpl());
    chrome::RegisterUserPrefs(pref_service->registry());
    builder.SetPrefService(make_scoped_ptr<PrefServiceSyncable>(pref_service));
    profile_ = builder.Build();

    // Initialize the services we check.
    profile_->CreateBookmarkModel(true);
    profile_->BlockUntilBookmarkModelLoaded();
    profile_->CreateHistoryService(true, false);
    extensions::TestExtensionSystem* system =
        static_cast<extensions::TestExtensionSystem*>(
            extensions::ExtensionSystem::Get(profile_.get()));
    CommandLine command_line(CommandLine::NO_PROGRAM);
    system->CreateExtensionService(&command_line,
                                   base::FilePath(kExtensionFilePath),
                                   false);

    // Create a dialog, but don't display it.
    dialog_ = new ProfileSigninConfirmationDialog(
        profile_.get(), "",
        base::Bind(&base::DoNothing),
        base::Bind(&base::DoNothing),
        base::Bind(&base::DoNothing));
  }

  virtual void TearDown() OVERRIDE {
    delete dialog_;
  }

 protected:
  MessageLoopForUI message_loop_;
  content::TestBrowserThread ui_thread_;
  scoped_ptr<TestingProfile> profile_;
  TestingPrefStoreWithCustomReadError* user_prefs_;
  ProfileSigninConfirmationDialog* dialog_;
};

TEST_F(ProfileSigninConfirmationDialogTest, DoNotPromptForNewProfile) {
  // Profile is new and there's no profile data.
  EXPECT_FALSE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));
}

TEST_F(ProfileSigninConfirmationDialogTest, PromptForNewProfile_Bookmarks) {
  BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_.get());
  ASSERT_TRUE(model);

  // Profile is new but has bookmarks.
  model->AddURL(model->bookmark_bar_node(), 0,
                string16(ASCIIToUTF16("foo")),
                GURL("http://foo.com"));
  EXPECT_TRUE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));
}

TEST_F(ProfileSigninConfirmationDialogTest, PromptForNewProfile_Extensions) {
  ExtensionService* extensions =
      extensions::ExtensionSystem::Get(profile_.get())->extension_service();
  ASSERT_TRUE(extensions);

  // Profile is new but has synced extensions.

  // (The web store doesn't count.)
  scoped_refptr<extensions::Extension> webstore =
      CreateExtension("web store", extension_misc::kWebStoreAppId);
  extensions->extension_prefs()->AddGrantedPermissions(
      webstore->id(),
      make_scoped_refptr(new extensions::PermissionSet));
  extensions->AddExtension(webstore);
  EXPECT_FALSE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));

  scoped_refptr<extensions::Extension> extension = CreateExtension("foo", "");
  extensions->extension_prefs()->AddGrantedPermissions(
      extension->id(),
      make_scoped_refptr(new extensions::PermissionSet));
  extensions->AddExtension(extension);
  EXPECT_TRUE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));
}

TEST_F(ProfileSigninConfirmationDialogTest, PromptForNewProfile_History) {
  HistoryService* history = HistoryServiceFactory::GetForProfile(
      profile_.get(),
      Profile::EXPLICIT_ACCESS);
  ASSERT_TRUE(history);

  // Profile is new but has more than $(kHistoryEntriesBeforeNewProfilePrompt)
  // history items.
  char buf[18];
  for (int i = 0; i < 10; i++) {
    base::snprintf(buf, arraysize(buf), "http://foo.com/%d", i);
    history->AddPage(
        GURL(std::string(buf)), base::Time::Now(), NULL, 1,
        GURL(), history::RedirectList(), content::PAGE_TRANSITION_LINK,
        history::SOURCE_BROWSED, false);
  }
  EXPECT_TRUE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));
}

TEST_F(ProfileSigninConfirmationDialogTest, PromptForNewProfile_TypedURLs) {
  HistoryService* history = HistoryServiceFactory::GetForProfile(
      profile_.get(),
      Profile::EXPLICIT_ACCESS);
  ASSERT_TRUE(history);

  // Profile is new but has a typed URL.
  history->AddPage(
      GURL("http://example.com"), base::Time::Now(), NULL, 1,
      GURL(), history::RedirectList(), content::PAGE_TRANSITION_TYPED,
      history::SOURCE_BROWSED, false);
  EXPECT_TRUE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));
}

TEST_F(ProfileSigninConfirmationDialogTest, PromptForNewProfile_Restarted) {
  // Browser has been shut down since profile was created.
  user_prefs_->set_read_error(PersistentPrefStore::PREF_READ_ERROR_NONE);
  EXPECT_TRUE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));
}
<commit_msg>Remove MessageLoopRunner from ProfileSigninConfirmationDialogTest.<commit_after>// Copyright 2013 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/ui/webui/signin/profile_signin_confirmation_dialog.h"

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/prefs/pref_notifier_impl.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/testing_pref_service.h"
#include "base/run_loop.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/extensions/extension_manifest_constants.h"
#include "chrome/common/extensions/permissions/permission_set.h"
#include "chrome/test/base/testing_pref_service_syncable.h"
#include "chrome/test/base/testing_profile.h"
#include "components/user_prefs/pref_registry_syncable.h"
#include "content/public/test/test_browser_thread.h"
#include "content/public/test/test_utils.h"

#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

template<typename T>
void GetValueAndQuit(T* result, base::Closure quit, T actual) {
  *result = actual;
  quit.Run();
}

template<typename T>
T GetCallbackResult(base::Callback<void(base::Callback<void(T)>)> callback) {
  T result = false;
  base::RunLoop loop;
  callback.Run(base::Bind(&GetValueAndQuit<T>, &result, loop.QuitClosure()));
  loop.Run();
  return result;
}

// A pref store that can have its read_error property changed for testing.
class TestingPrefStoreWithCustomReadError : public TestingPrefStore {
 public:
  TestingPrefStoreWithCustomReadError()
      : read_error_(PersistentPrefStore::PREF_READ_ERROR_NO_FILE) {
    // By default the profile is "new" (NO_FILE means that the profile
    // wasn't found on disk, so it was created).
  }
  virtual PrefReadError GetReadError() const OVERRIDE {
    return read_error_;
  }
  virtual bool IsInitializationComplete() const OVERRIDE {
    return true;
  }
  void set_read_error(PrefReadError read_error) {
    read_error_ = read_error;
  }
 private:
  virtual ~TestingPrefStoreWithCustomReadError() {}
  PrefReadError read_error_;
};

#if defined(OS_WIN)
const base::FilePath::CharType kExtensionFilePath[] =
    FILE_PATH_LITERAL("c:\\foo");
#elif defined(OS_POSIX)
const base::FilePath::CharType kExtensionFilePath[] =
    FILE_PATH_LITERAL("/oo");
#endif

static scoped_refptr<extensions::Extension> CreateExtension(
    const std::string& name,
    const std::string& id) {
  DictionaryValue manifest;
  manifest.SetString(extension_manifest_keys::kVersion, "1.0.0.0");
  manifest.SetString(extension_manifest_keys::kName, name);
  std::string error;
  scoped_refptr<extensions::Extension> extension =
    extensions::Extension::Create(
        base::FilePath(kExtensionFilePath).AppendASCII(name),
        extensions::Manifest::INTERNAL,
        manifest,
        extensions::Extension::NO_FLAGS,
        id,
        &error);
  return extension;
}

}  // namespace

class ProfileSigninConfirmationDialogTest : public testing::Test {
 public:
  ProfileSigninConfirmationDialogTest()
      : ui_thread_(BrowserThread::UI, &message_loop_) {
  }
  virtual ~ProfileSigninConfirmationDialogTest() {}

  virtual void SetUp() OVERRIDE {
    // Create the profile.
    TestingProfile::Builder builder;
    user_prefs_ = new TestingPrefStoreWithCustomReadError;
    TestingPrefServiceSyncable* pref_service = new TestingPrefServiceSyncable(
        new TestingPrefStore(),
        user_prefs_,
        new TestingPrefStore(),
        new PrefRegistrySyncable(),
        new PrefNotifierImpl());
    chrome::RegisterUserPrefs(pref_service->registry());
    builder.SetPrefService(make_scoped_ptr<PrefServiceSyncable>(pref_service));
    profile_ = builder.Build();

    // Initialize the services we check.
    profile_->CreateBookmarkModel(true);
    profile_->BlockUntilBookmarkModelLoaded();
    profile_->CreateHistoryService(true, false);
    extensions::TestExtensionSystem* system =
        static_cast<extensions::TestExtensionSystem*>(
            extensions::ExtensionSystem::Get(profile_.get()));
    CommandLine command_line(CommandLine::NO_PROGRAM);
    system->CreateExtensionService(&command_line,
                                   base::FilePath(kExtensionFilePath),
                                   false);

    // Create a dialog, but don't display it.
    dialog_ = new ProfileSigninConfirmationDialog(
        profile_.get(), "",
        base::Bind(&base::DoNothing),
        base::Bind(&base::DoNothing),
        base::Bind(&base::DoNothing));
  }

  virtual void TearDown() OVERRIDE {
    delete dialog_;
  }

 protected:
  MessageLoopForUI message_loop_;
  content::TestBrowserThread ui_thread_;
  scoped_ptr<TestingProfile> profile_;
  TestingPrefStoreWithCustomReadError* user_prefs_;
  ProfileSigninConfirmationDialog* dialog_;
};

TEST_F(ProfileSigninConfirmationDialogTest, DoNotPromptForNewProfile) {
  // Profile is new and there's no profile data.
  EXPECT_FALSE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));
}

TEST_F(ProfileSigninConfirmationDialogTest, PromptForNewProfile_Bookmarks) {
  BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_.get());
  ASSERT_TRUE(model);

  // Profile is new but has bookmarks.
  model->AddURL(model->bookmark_bar_node(), 0,
                string16(ASCIIToUTF16("foo")),
                GURL("http://foo.com"));
  EXPECT_TRUE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));
}

TEST_F(ProfileSigninConfirmationDialogTest, PromptForNewProfile_Extensions) {
  ExtensionService* extensions =
      extensions::ExtensionSystem::Get(profile_.get())->extension_service();
  ASSERT_TRUE(extensions);

  // Profile is new but has synced extensions.

  // (The web store doesn't count.)
  scoped_refptr<extensions::Extension> webstore =
      CreateExtension("web store", extension_misc::kWebStoreAppId);
  extensions->extension_prefs()->AddGrantedPermissions(
      webstore->id(),
      make_scoped_refptr(new extensions::PermissionSet));
  extensions->AddExtension(webstore);
  EXPECT_FALSE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));

  scoped_refptr<extensions::Extension> extension = CreateExtension("foo", "");
  extensions->extension_prefs()->AddGrantedPermissions(
      extension->id(),
      make_scoped_refptr(new extensions::PermissionSet));
  extensions->AddExtension(extension);
  EXPECT_TRUE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));
}

TEST_F(ProfileSigninConfirmationDialogTest, PromptForNewProfile_History) {
  HistoryService* history = HistoryServiceFactory::GetForProfile(
      profile_.get(),
      Profile::EXPLICIT_ACCESS);
  ASSERT_TRUE(history);

  // Profile is new but has more than $(kHistoryEntriesBeforeNewProfilePrompt)
  // history items.
  char buf[18];
  for (int i = 0; i < 10; i++) {
    base::snprintf(buf, arraysize(buf), "http://foo.com/%d", i);
    history->AddPage(
        GURL(std::string(buf)), base::Time::Now(), NULL, 1,
        GURL(), history::RedirectList(), content::PAGE_TRANSITION_LINK,
        history::SOURCE_BROWSED, false);
  }
  EXPECT_TRUE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));
}

TEST_F(ProfileSigninConfirmationDialogTest, PromptForNewProfile_TypedURLs) {
  HistoryService* history = HistoryServiceFactory::GetForProfile(
      profile_.get(),
      Profile::EXPLICIT_ACCESS);
  ASSERT_TRUE(history);

  // Profile is new but has a typed URL.
  history->AddPage(
      GURL("http://example.com"), base::Time::Now(), NULL, 1,
      GURL(), history::RedirectList(), content::PAGE_TRANSITION_TYPED,
      history::SOURCE_BROWSED, false);
  EXPECT_TRUE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));
}

TEST_F(ProfileSigninConfirmationDialogTest, PromptForNewProfile_Restarted) {
  // Browser has been shut down since profile was created.
  user_prefs_->set_read_error(PersistentPrefStore::PREF_READ_ERROR_NONE);
  EXPECT_TRUE(
      GetCallbackResult(
          base::Bind(
              &ProfileSigninConfirmationDialog::CheckShouldPromptForNewProfile,
              base::Unretained(dialog_))));
}
<|endoftext|>


<commit_before>#include <libxml/xpath.h>

#include "XPathValidator.hh"

void ignoreStructuredError(void *userdata, xmlErrorPtr err)
{
}

XPathValidator::XPathValidator()
{
}

XPathValidator::State XPathValidator::validate(QString &exprStr, int &pos) const
{
    exprStr.replace('\'', '"');
    QByteArray expr(exprStr.toUtf8());

    xmlXPathContextPtr ctx;
    ctx = xmlXPathNewContext(0);
    xmlSetStructuredErrorFunc(ctx, &ignoreStructuredError);

    xmlXPathCompExprPtr r = xmlXPathCtxtCompile(ctx,
        reinterpret_cast<xmlChar const *>(expr.constData()));

    if (!r)
    {
        xmlXPathFreeContext(ctx);
        return XPathValidator::Intermediate;
    }

    xmlXPathFreeCompExpr(r);
    xmlXPathFreeContext(ctx);

    return XPathValidator::Acceptable;
}
<commit_msg>Empty XPath expressions are valid for our purposes.<commit_after>#include <libxml/xpath.h>

#include "XPathValidator.hh"

void ignoreStructuredError(void *userdata, xmlErrorPtr err)
{
}

XPathValidator::XPathValidator()
{
}

XPathValidator::State XPathValidator::validate(QString &exprStr, int &pos) const
{
    if (exprStr.trimmed().size() == 0)
        return XPathValidator::Acceptable;

    exprStr.replace('\'', '"');
    QByteArray expr(exprStr.toUtf8());

    xmlXPathContextPtr ctx;
    ctx = xmlXPathNewContext(0);
    xmlSetStructuredErrorFunc(ctx, &ignoreStructuredError);

    xmlXPathCompExprPtr r = xmlXPathCtxtCompile(ctx,
        reinterpret_cast<xmlChar const *>(expr.constData()));

    if (!r)
    {
        xmlXPathFreeContext(ctx);
        return XPathValidator::Intermediate;
    }

    xmlXPathFreeCompExpr(r);
    xmlXPathFreeContext(ctx);

    return XPathValidator::Acceptable;
}
<|endoftext|>


<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
*
* the treeview data code is largely inspired from the gtk redmond engine
*
* 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., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "oxygentreeviewdata.h"
#include "../config.h"
#include "../oxygengtkutils.h"

#include <gtk/gtk.h>
#include <iostream>

namespace Oxygen
{

    //________________________________________________________________________________
    void TreeViewData::connect( GtkWidget* widget )
    {

        #if OXYGEN_DEBUG
        std::cout << "Oxygen::TreeViewData::connect - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << std::endl;
        #endif

        // store target
        _target = widget;

        // base class
        HoverData::connect( widget );

        // get full-width flag
        if( GTK_IS_TREE_VIEW( widget ) )
        {
            gtk_widget_style_get( widget, "row_ending_details", &_fullWidth, NULL );

            if( hovered() )
            {
                // on connection, needs to check whether mouse pointer is in widget or not
                // to have the proper initial value of the hover flag
                GtkTreeView* treeView( GTK_TREE_VIEW( widget ) );
                gint xPointer,yPointer;
                gdk_window_get_pointer(widget->window,&xPointer,&yPointer, 0L);
                gtk_tree_view_convert_widget_to_bin_window_coords( treeView, xPointer, yPointer, &xPointer, &yPointer );
                updatePosition( widget, xPointer, yPointer );
            }

        }

        _motionId.connect( G_OBJECT(widget), "motion-notify-event", G_CALLBACK( motionNotifyEvent ), this );

        // also register scrollbars from parent scrollWindow
        registerScrollBars( widget );

    }

    //________________________________________________________________________________
    void TreeViewData::disconnect( GtkWidget* widget )
    {

        #if OXYGEN_DEBUG
        std::cout << "Oxygen::TreeViewData::disconnect - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << std::endl;
        #endif

        // reset target
        _target = 0L;

        // motion handler
        _motionId.disconnect();

        // also free path if valid
        _cellInfo.clear();

        // disconnect scrollbars
        _vScrollBar.disconnect();
        _hScrollBar.disconnect();

        // base class
        HoverData::disconnect( widget );

    }

    //________________________________________________________________________________
    void TreeViewData::updateHoveredCell( void )
    {
        if( !( isDirty() && GTK_IS_TREE_VIEW( _target ) ) ) return;
        _cellInfo = Gtk::CellInfo( GTK_TREE_VIEW( _target ), _x, _y );
        setDirty( false );
    }

    //________________________________________________________________________________
    void TreeViewData::updatePosition( GtkWidget* widget, int x, int y )
    {

        // check type and cast to treeview
        if( !GTK_IS_TREE_VIEW( widget ) ) return;
        GtkTreeView* treeView( GTK_TREE_VIEW( widget ) );

        // store position
        _x = x;
        _y = y;

        // get cellInfo at x and y
        Gtk::CellInfo cellInfo( treeView, x, y );

        // do nothing if unchanged
        if( cellInfo == _cellInfo ) return;

        // prepare update area
        // get old rectangle
        GdkRectangle oldRect( _cellInfo.backgroundRect( treeView ) );
        if( _fullWidth ) { oldRect.x = 0; oldRect.width = widget->allocation.width; }

        // get new rectangle and update position
        GdkRectangle newRect( cellInfo.backgroundRect( treeView ) );
        if( cellInfo.isValid() && _fullWidth )
        { newRect.x = 0; newRect.width = widget->allocation.width; }

        // take the union of both rectangles
        GdkRectangle updateRect;
        if( Gtk::gdk_rectangle_is_valid( &oldRect ) )
        {

            if( Gtk::gdk_rectangle_is_valid( &newRect ) ) gdk_rectangle_union( &oldRect, &newRect, &updateRect );
            else updateRect = oldRect;

        } else updateRect = newRect;

        // store new cell info
        _cellInfo = cellInfo;

        // convert to widget coordinates and schedule redraw
        gtk_tree_view_convert_bin_window_to_widget_coords( treeView, updateRect.x, updateRect.y, &updateRect.x, &updateRect.y );
        Gtk::gtk_widget_queue_draw( widget, &updateRect );

    }

    //________________________________________________________________________________
    void TreeViewData::clearPosition( GtkWidget* widget )
    {

        // check widget
        if( !widget ) widget = _target;
        if( !widget ) return;

        // check path and widget
        if( !( _cellInfo.isValid() && GTK_IS_TREE_VIEW( widget ) ) ) return;
        GtkTreeView* treeView( GTK_TREE_VIEW( widget ) );

        // prepare update area
        GdkRectangle updateRect( _cellInfo.backgroundRect( treeView ) );
        updateRect.x = 0;
        updateRect.width = widget->allocation.width;

        // clear path and column
        _cellInfo.clear();

        // schedule redraw
        gtk_tree_view_convert_bin_window_to_widget_coords( treeView, updateRect.x, updateRect.y, &updateRect.x, &updateRect.y );
        Gtk::gtk_widget_queue_draw( widget, &updateRect );

    }

    //________________________________________________________________________________
    void TreeViewData::triggerRepaint( void )
    {
        if( !( _target && hovered() ) ) return;
        if( setDirty( true ) ) Gtk::gtk_widget_queue_draw( _target );
    }

    //________________________________________________________________________________
    void TreeViewData::registerScrollBars( GtkWidget* widget )
    {

        // find parent scrolled window
        GtkWidget* parent( Gtk::gtk_parent_scrolled_window( widget ) );
        if( !parent ) return;

        // cast and register scrollbars
        GtkScrolledWindow *scrolledWindow( GTK_SCROLLED_WINDOW( parent ) );

        if( GtkWidget* hScrollBar = gtk_scrolled_window_get_hscrollbar( scrolledWindow ) )
        { registerChild( hScrollBar, _hScrollBar ); }

        if( GtkWidget* vScrollBar = gtk_scrolled_window_get_vscrollbar( scrolledWindow ) )
        { registerChild( vScrollBar, _vScrollBar ); }

    }

    //________________________________________________________________________________
    void TreeViewData::registerChild( GtkWidget* widget, ScrollBarData& data )
    {

        if( data._widget ) data.disconnect();

        #if OXYGEN_DEBUG
        std::cout << "Oxygen::TreeViewData::registerChild - " << widget << std::endl;
        #endif

        // make sure widget is not already in map
        data._widget = widget;
        data._destroyId.connect( G_OBJECT(widget), "destroy", G_CALLBACK( childDestroyNotifyEvent ), this );
        data._styleChangeId.connect( G_OBJECT(widget), "style-set", G_CALLBACK( childStyleChangeNotifyEvent ), this );
        data._valueChangedId.connect( G_OBJECT(widget), "value-changed", G_CALLBACK( childValueChanged ), this );

    }

    //________________________________________________________________________________
    void TreeViewData::unregisterChild( GtkWidget* widget )
    {
        if( widget == _vScrollBar._widget ) _vScrollBar.disconnect();
        else if( widget == _hScrollBar._widget ) _hScrollBar.disconnect();
    }

    //____________________________________________________________________________________________
    gboolean TreeViewData::childDestroyNotifyEvent( GtkWidget* widget, gpointer data )
    {
        static_cast<TreeViewData*>(data)->unregisterChild( widget );
        return FALSE;
    }

    //____________________________________________________________________________________________
    void TreeViewData::childStyleChangeNotifyEvent( GtkWidget* widget, GtkStyle*, gpointer data )
    { static_cast<TreeViewData*>(data)->unregisterChild( widget ); }

    //________________________________________________________________________________
    void TreeViewData::childValueChanged( GtkRange* widget, gpointer data )
    {
        static_cast<TreeViewData*>(data)->triggerRepaint();
        return;
    }

    //________________________________________________________________________________
    gboolean TreeViewData::motionNotifyEvent(GtkWidget* widget, GdkEventMotion* event, gpointer data )
    {
        static_cast<TreeViewData*>( data )->updatePosition( widget, (int)event->x, (int)event->y );
        return FALSE;
    }

    //____________________________________________________________________________________________
    void TreeViewData::ScrollBarData::disconnect( void )
    {

        if( !_widget ) return;

        #if OXYGEN_DEBUG
        std::cout << "Oxygen::TreeViewData::ScrollBarData::disconnect - " << _widget << std::endl;
        #endif

        _destroyId.disconnect();
        _styleChangeId.disconnect();
        _valueChangedId.disconnect();
        _widget = 0L;

    }

}
<commit_msg>no need to trigger repaint when scrolling<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
*
* the treeview data code is largely inspired from the gtk redmond engine
*
* 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., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "oxygentreeviewdata.h"
#include "../config.h"
#include "../oxygengtkutils.h"

#include <gtk/gtk.h>
#include <iostream>

namespace Oxygen
{

    //________________________________________________________________________________
    void TreeViewData::connect( GtkWidget* widget )
    {

        #if OXYGEN_DEBUG
        std::cout << "Oxygen::TreeViewData::connect - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << std::endl;
        #endif

        // store target
        _target = widget;

        // base class
        HoverData::connect( widget );

        // get full-width flag
        if( GTK_IS_TREE_VIEW( widget ) )
        {
            gtk_widget_style_get( widget, "row_ending_details", &_fullWidth, NULL );

            if( hovered() )
            {
                // on connection, needs to check whether mouse pointer is in widget or not
                // to have the proper initial value of the hover flag
                GtkTreeView* treeView( GTK_TREE_VIEW( widget ) );
                gint xPointer,yPointer;
                gdk_window_get_pointer(widget->window,&xPointer,&yPointer, 0L);
                gtk_tree_view_convert_widget_to_bin_window_coords( treeView, xPointer, yPointer, &xPointer, &yPointer );
                updatePosition( widget, xPointer, yPointer );
            }

        }

        _motionId.connect( G_OBJECT(widget), "motion-notify-event", G_CALLBACK( motionNotifyEvent ), this );

        // also register scrollbars from parent scrollWindow
        registerScrollBars( widget );

    }

    //________________________________________________________________________________
    void TreeViewData::disconnect( GtkWidget* widget )
    {

        #if OXYGEN_DEBUG
        std::cout << "Oxygen::TreeViewData::disconnect - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << std::endl;
        #endif

        // reset target
        _target = 0L;

        // motion handler
        _motionId.disconnect();

        // also free path if valid
        _cellInfo.clear();

        // disconnect scrollbars
        _vScrollBar.disconnect();
        _hScrollBar.disconnect();

        // base class
        HoverData::disconnect( widget );

    }

    //________________________________________________________________________________
    void TreeViewData::updateHoveredCell( void )
    {
        if( !( isDirty() && GTK_IS_TREE_VIEW( _target ) ) ) return;
        _cellInfo = Gtk::CellInfo( GTK_TREE_VIEW( _target ), _x, _y );
        setDirty( false );
    }

    //________________________________________________________________________________
    void TreeViewData::updatePosition( GtkWidget* widget, int x, int y )
    {

        // check type and cast to treeview
        if( !GTK_IS_TREE_VIEW( widget ) ) return;
        GtkTreeView* treeView( GTK_TREE_VIEW( widget ) );

        // store position
        _x = x;
        _y = y;

        // get cellInfo at x and y
        Gtk::CellInfo cellInfo( treeView, x, y );

        // do nothing if unchanged
        if( cellInfo == _cellInfo ) return;

        // prepare update area
        // get old rectangle
        GdkRectangle oldRect( _cellInfo.backgroundRect( treeView ) );
        if( _fullWidth ) { oldRect.x = 0; oldRect.width = widget->allocation.width; }

        // get new rectangle and update position
        GdkRectangle newRect( cellInfo.backgroundRect( treeView ) );
        if( cellInfo.isValid() && _fullWidth )
        { newRect.x = 0; newRect.width = widget->allocation.width; }

        // take the union of both rectangles
        GdkRectangle updateRect;
        if( Gtk::gdk_rectangle_is_valid( &oldRect ) )
        {

            if( Gtk::gdk_rectangle_is_valid( &newRect ) ) gdk_rectangle_union( &oldRect, &newRect, &updateRect );
            else updateRect = oldRect;

        } else updateRect = newRect;

        // store new cell info
        _cellInfo = cellInfo;

        // convert to widget coordinates and schedule redraw
        gtk_tree_view_convert_bin_window_to_widget_coords( treeView, updateRect.x, updateRect.y, &updateRect.x, &updateRect.y );
        Gtk::gtk_widget_queue_draw( widget, &updateRect );

    }

    //________________________________________________________________________________
    void TreeViewData::clearPosition( GtkWidget* widget )
    {

        // check widget
        if( !widget ) widget = _target;
        if( !widget ) return;

        // check path and widget
        if( !( _cellInfo.isValid() && GTK_IS_TREE_VIEW( widget ) ) ) return;
        GtkTreeView* treeView( GTK_TREE_VIEW( widget ) );

        // prepare update area
        GdkRectangle updateRect( _cellInfo.backgroundRect( treeView ) );
        updateRect.x = 0;
        updateRect.width = widget->allocation.width;

        // clear path and column
        _cellInfo.clear();

        // schedule redraw
        gtk_tree_view_convert_bin_window_to_widget_coords( treeView, updateRect.x, updateRect.y, &updateRect.x, &updateRect.y );
        Gtk::gtk_widget_queue_draw( widget, &updateRect );

    }

    //________________________________________________________________________________
    void TreeViewData::triggerRepaint( void )
    {
        if( !( _target && hovered() ) ) return;
        setDirty( true );
    }

    //________________________________________________________________________________
    void TreeViewData::registerScrollBars( GtkWidget* widget )
    {

        // find parent scrolled window
        GtkWidget* parent( Gtk::gtk_parent_scrolled_window( widget ) );
        if( !parent ) return;

        // cast and register scrollbars
        GtkScrolledWindow *scrolledWindow( GTK_SCROLLED_WINDOW( parent ) );

        if( GtkWidget* hScrollBar = gtk_scrolled_window_get_hscrollbar( scrolledWindow ) )
        { registerChild( hScrollBar, _hScrollBar ); }

        if( GtkWidget* vScrollBar = gtk_scrolled_window_get_vscrollbar( scrolledWindow ) )
        { registerChild( vScrollBar, _vScrollBar ); }

    }

    //________________________________________________________________________________
    void TreeViewData::registerChild( GtkWidget* widget, ScrollBarData& data )
    {

        if( data._widget ) data.disconnect();

        #if OXYGEN_DEBUG
        std::cout << "Oxygen::TreeViewData::registerChild - " << widget << std::endl;
        #endif

        // make sure widget is not already in map
        data._widget = widget;
        data._destroyId.connect( G_OBJECT(widget), "destroy", G_CALLBACK( childDestroyNotifyEvent ), this );
        data._styleChangeId.connect( G_OBJECT(widget), "style-set", G_CALLBACK( childStyleChangeNotifyEvent ), this );
        data._valueChangedId.connect( G_OBJECT(widget), "value-changed", G_CALLBACK( childValueChanged ), this );

    }

    //________________________________________________________________________________
    void TreeViewData::unregisterChild( GtkWidget* widget )
    {
        if( widget == _vScrollBar._widget ) _vScrollBar.disconnect();
        else if( widget == _hScrollBar._widget ) _hScrollBar.disconnect();
    }

    //____________________________________________________________________________________________
    gboolean TreeViewData::childDestroyNotifyEvent( GtkWidget* widget, gpointer data )
    {
        static_cast<TreeViewData*>(data)->unregisterChild( widget );
        return FALSE;
    }

    //____________________________________________________________________________________________
    void TreeViewData::childStyleChangeNotifyEvent( GtkWidget* widget, GtkStyle*, gpointer data )
    { static_cast<TreeViewData*>(data)->unregisterChild( widget ); }

    //________________________________________________________________________________
    void TreeViewData::childValueChanged( GtkRange* widget, gpointer data )
    {
        static_cast<TreeViewData*>(data)->triggerRepaint();
        return;
    }

    //________________________________________________________________________________
    gboolean TreeViewData::motionNotifyEvent(GtkWidget* widget, GdkEventMotion* event, gpointer data )
    {
        static_cast<TreeViewData*>( data )->updatePosition( widget, (int)event->x, (int)event->y );
        return FALSE;
    }

    //____________________________________________________________________________________________
    void TreeViewData::ScrollBarData::disconnect( void )
    {

        if( !_widget ) return;

        #if OXYGEN_DEBUG
        std::cout << "Oxygen::TreeViewData::ScrollBarData::disconnect - " << _widget << std::endl;
        #endif

        _destroyId.disconnect();
        _styleChangeId.disconnect();
        _valueChangedId.disconnect();
        _widget = 0L;

    }

}
<|endoftext|>


<commit_before><commit_msg>planning: fix a bug in traffic-light-unprotected-right-turn scenario when there's YELLOW light and traffic-rule decides to ignore it because of harsh decelatation<commit_after><|endoftext|>


<commit_before>//FRAGMENT(main)
#include <iostream>
#include <seqan/align.h>

using namespace seqan;

int main()
{
//FRAGMENT(init)
	Align< String<AminoAcid> > ali;
	appendValue(rows(ali), "PNCFDAKQRTASRPL");
	appendValue(rows(ali), "CFDKQKNNRTATRDTA");

//FRAGMENT(ali)
	LocalAlignmentFinder<> finder(ali);
	Score<int> sc(3,-2,-5,-1);
	unsigned count = 0;
	while (localAlignment(ali, finder, sc, 0, WatermanEggert()) && count < 3) {
		::std::cout << "Score = " << getScore(finder) << ::std::endl;
		::std::cout << ali;
		++count;
	}
	return 0;
}
<commit_msg>Correcting gap extension and gap open score.<commit_after>//FRAGMENT(main)
#include <iostream>
#include <seqan/align.h>

using namespace seqan;

int main()
{
//FRAGMENT(init)
	Align< String<AminoAcid> > ali;
	appendValue(rows(ali), "PNCFDAKQRTASRPL");
	appendValue(rows(ali), "CFDKQKNNRTATRDTA");

//FRAGMENT(ali)
	LocalAlignmentFinder<> finder(ali);
	Score<int> sc(3,-2,-1,-5);
	unsigned count = 0;
	while (localAlignment(ali, finder, sc, 0, WatermanEggert()) && count < 3) {
		::std::cout << "Score = " << getScore(finder) << ::std::endl;
		::std::cout << ali;
		++count;
	}
	return 0;
}
<|endoftext|>


<commit_before>/*******************************************************************************
  The MIT License (MIT)

  Copyright (c) 2015 Manuel Freiberger

  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 "catch.hpp"

#include "../src/statemachine.hpp"
#include <cstring>

using namespace fsm11;

using StateMachine_t = fsm11::StateMachine<>;
using State_t = StateMachine_t::state_type;

TEST_CASE("construct a state", "[state]")
{
    State_t s("name");

    REQUIRE(s.childMode() == State_t::Exclusive);
    REQUIRE(!std::strcmp(s.name(), "name"));
    REQUIRE(s.parent() == 0);
    REQUIRE(s.isAtomic());
    REQUIRE(!s.isCompound());
    REQUIRE(!s.isParallel());
    REQUIRE(s.stateMachine() == 0);
    REQUIRE(!s.isActive());
    REQUIRE(s.initialState() == 0);

    REQUIRE(s.beginTransitions() == s.endTransitions());
    REQUIRE(s.cbeginTransitions() == s.cendTransitions());
}

TEST_CASE("set the parent of a state", "[state]")
{
    State_t p1("p1");
    State_t p2("p2");

    State_t c("c", &p1);
    REQUIRE(&p1 == c.parent());
    REQUIRE(!p1.isAtomic());
    REQUIRE(p2.isAtomic());

    c.setParent(&p2);
    REQUIRE(&p2 == c.parent());
    REQUIRE(p1.isAtomic());
    REQUIRE(!p2.isAtomic());

    c.setParent(&p1);
    REQUIRE(&p1 == c.parent());
    REQUIRE(!p1.isAtomic());
    REQUIRE(p2.isAtomic());
}

TEST_CASE("set the state machine", "[state]")
{
    StateMachine_t sm1;
    State_t s1("s1", &sm1);
    State_t s2("s2");
    State_t s3("s3", &s2);

    REQUIRE(s1.stateMachine() == &sm1);
    REQUIRE(s2.stateMachine() == nullptr);
    REQUIRE(s3.stateMachine() == nullptr);
    s2.setParent(&s1);
    REQUIRE(s1.stateMachine() == &sm1);
    REQUIRE(s2.stateMachine() == &sm1);
    REQUIRE(s3.stateMachine() == &sm1);

    State_t s4("s4", &s2);
    REQUIRE(s4.stateMachine() == &sm1);

    REQUIRE(!s1.isAtomic());

    StateMachine_t sm2;
    s2.setParent(&sm2);

    REQUIRE(s1.stateMachine() == &sm1);
    REQUIRE(s2.stateMachine() == &sm2);
    REQUIRE(s3.stateMachine() == &sm2);
    REQUIRE(s4.stateMachine() == &sm2);

    REQUIRE(s1.isAtomic());
}

TEST_CASE("change the child mode", "[state]")
{
    State_t s("s");
    State_t c("c", &s);

    REQUIRE(State_t::Exclusive == s.childMode());
    REQUIRE(s.isCompound());
    REQUIRE(!s.isParallel());

    s.setChildMode(State_t::Parallel);
    REQUIRE(State_t::Parallel == s.childMode());
    REQUIRE(!s.isCompound());
    REQUIRE(s.isParallel());

    s.setChildMode(State_t::Exclusive);
    REQUIRE(State_t::Exclusive == s.childMode());
    REQUIRE(s.isCompound());
    REQUIRE(!s.isParallel());
}

TEST_CASE("set an initial state", "[state]")
{
    StateMachine_t sm;
    State_t s1("s1", &sm);
    State_t s2("s2");
    State_t s3("s3", &s2);

    REQUIRE(s2.initialState() == 0);
    s2.setInitialState(&s3);
    REQUIRE(s2.initialState() == &s3);

    REQUIRE(sm.initialState() == 0);
    sm.setInitialState(&s1);
    REQUIRE(sm.initialState() == &s1);
}

TEST_CASE("find a child", "[state]")
{
    State_t p("p");
    State_t c1("c1", &p);
    State_t c2("c2", &p);
    State_t c3("c3", &p);
    State_t c11("c11", &c1);
    State_t c12("c12", &c1);
    State_t c31("c31", &c3);
    State_t c32("c32", &c3);

    State_t* found;

    found = p.findChild("c1");
    REQUIRE(found == &c1);

    found = c3.findChild("c32");
    REQUIRE(found == &c32);

    found = p.findChild("p");
    REQUIRE(found == nullptr);

    found = c1.findChild("p");
    REQUIRE(found == nullptr);

    found = c1.findChild("");
    REQUIRE(found == nullptr);
}

TEST_CASE("find a descendant", "[state]")
{
    State_t p("p");
    State_t c1("c1", &p);
    State_t c2("c2", &p);
    State_t c3("c3", &p);
    State_t c11("c11", &c1);
    State_t c12("c12", &c1);
    State_t c31("c31", &c3);
    State_t c32("c32", &c3);

    State_t* found;

    found = p.findDescendant({});
    REQUIRE(found == &p);

    found = p.findDescendant({"c1"});
    REQUIRE(found == &c1);

    found = c3.findDescendant({"c32"});
    REQUIRE(found == &c32);

    found = p.findDescendant({"c3", "c32"});
    REQUIRE(found == &c32);

    found = p.findDescendant({"p"});
    REQUIRE(found == nullptr);

    found = c1.findDescendant({"p"});
    REQUIRE(found == nullptr);

    found = c1.findDescendant({""});
    REQUIRE(found == nullptr);
}
<commit_msg>Make sure that an FSM can be constructed in parts.<commit_after>/*******************************************************************************
  The MIT License (MIT)

  Copyright (c) 2015 Manuel Freiberger

  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 "catch.hpp"

#include "../src/statemachine.hpp"

#include <cstring>
#include <initializer_list>

using namespace fsm11;

using StateMachine_t = fsm11::StateMachine<>;
using State_t = StateMachine_t::state_type;

TEST_CASE("construct a state", "[state]")
{
    State_t s("name");

    REQUIRE(s.childMode() == State_t::Exclusive);
    REQUIRE(!std::strcmp(s.name(), "name"));
    REQUIRE(s.parent() == 0);
    REQUIRE(s.isAtomic());
    REQUIRE(!s.isCompound());
    REQUIRE(!s.isParallel());
    REQUIRE(s.stateMachine() == 0);
    REQUIRE(!s.isActive());
    REQUIRE(s.initialState() == 0);

    REQUIRE(s.beginTransitions() == s.endTransitions());
    REQUIRE(s.cbeginTransitions() == s.cendTransitions());
}

TEST_CASE("set the parent of a state", "[state]")
{
    State_t p1("p1");
    State_t p2("p2");

    State_t c("c", &p1);
    REQUIRE(&p1 == c.parent());
    REQUIRE(!p1.isAtomic());
    REQUIRE(p2.isAtomic());

    c.setParent(&p2);
    REQUIRE(&p2 == c.parent());
    REQUIRE(p1.isAtomic());
    REQUIRE(!p2.isAtomic());

    c.setParent(&p1);
    REQUIRE(&p1 == c.parent());
    REQUIRE(!p1.isAtomic());
    REQUIRE(p2.isAtomic());
}

TEST_CASE("set the state machine", "[state]")
{
    StateMachine_t sm1;
    State_t s1("s1", &sm1);
    State_t s2("s2");
    State_t s3("s3", &s2);

    REQUIRE(s1.stateMachine() == &sm1);
    REQUIRE(s2.stateMachine() == nullptr);
    REQUIRE(s3.stateMachine() == nullptr);
    s2.setParent(&s1);
    REQUIRE(s1.stateMachine() == &sm1);
    REQUIRE(s2.stateMachine() == &sm1);
    REQUIRE(s3.stateMachine() == &sm1);

    State_t s4("s4", &s2);
    REQUIRE(s4.stateMachine() == &sm1);

    REQUIRE(!s1.isAtomic());

    StateMachine_t sm2;
    s2.setParent(&sm2);

    REQUIRE(s1.stateMachine() == &sm1);
    REQUIRE(s2.stateMachine() == &sm2);
    REQUIRE(s3.stateMachine() == &sm2);
    REQUIRE(s4.stateMachine() == &sm2);

    REQUIRE(s1.isAtomic());
}

TEST_CASE("change the child mode", "[state]")
{
    State_t s("s");
    State_t c("c", &s);

    REQUIRE(State_t::Exclusive == s.childMode());
    REQUIRE(s.isCompound());
    REQUIRE(!s.isParallel());

    s.setChildMode(State_t::Parallel);
    REQUIRE(State_t::Parallel == s.childMode());
    REQUIRE(!s.isCompound());
    REQUIRE(s.isParallel());

    s.setChildMode(State_t::Exclusive);
    REQUIRE(State_t::Exclusive == s.childMode());
    REQUIRE(s.isCompound());
    REQUIRE(!s.isParallel());
}

TEST_CASE("set an initial state", "[state]")
{
    StateMachine_t sm;
    State_t s1("s1", &sm);
    State_t s2("s2");
    State_t s3("s3", &s2);

    REQUIRE(s2.initialState() == 0);
    s2.setInitialState(&s3);
    REQUIRE(s2.initialState() == &s3);

    REQUIRE(sm.initialState() == 0);
    sm.setInitialState(&s1);
    REQUIRE(sm.initialState() == &s1);
}

TEST_CASE("find a child", "[state]")
{
    State_t p("p");
    State_t c1("c1", &p);
    State_t c2("c2", &p);
    State_t c3("c3", &p);
    State_t c11("c11", &c1);
    State_t c12("c12", &c1);
    State_t c31("c31", &c3);
    State_t c32("c32", &c3);

    State_t* found;

    found = p.findChild("c1");
    REQUIRE(found == &c1);

    found = c3.findChild("c32");
    REQUIRE(found == &c32);

    found = p.findChild("p");
    REQUIRE(found == nullptr);

    found = c1.findChild("p");
    REQUIRE(found == nullptr);

    found = c1.findChild("");
    REQUIRE(found == nullptr);
}

TEST_CASE("find a descendant", "[state]")
{
    State_t p("p");
    State_t c1("c1", &p);
    State_t c2("c2", &p);
    State_t c3("c3", &p);
    State_t c11("c11", &c1);
    State_t c12("c12", &c1);
    State_t c31("c31", &c3);
    State_t c32("c32", &c3);

    State_t* found;

    found = p.findDescendant({});
    REQUIRE(found == &p);

    found = p.findDescendant({"c1"});
    REQUIRE(found == &c1);

    found = c3.findDescendant({"c32"});
    REQUIRE(found == &c32);

    found = p.findDescendant({"c3", "c32"});
    REQUIRE(found == &c32);

    found = p.findDescendant({"p"});
    REQUIRE(found == nullptr);

    found = c1.findDescendant({"p"});
    REQUIRE(found == nullptr);

    found = c1.findDescendant({""});
    REQUIRE(found == nullptr);
}

SCENARIO("a state hierarchy can be constructed in parts", "[state]")
{
    GIVEN ("two distinct state trees")
    {
        StateMachine_t sm;
        State_t a("a", &sm);
        State_t a1("a1", &a);
        State_t a2("a2", &a);
        State_t a3("a3", &a1);
        State_t a4("a4", &a1);

        State_t b("b");
        State_t b1("b1", &b);
        State_t b2("b2", &b);
        State_t b3("b3", &b1);
        State_t b4("b4", &b1);

        REQUIRE(b.parent() == nullptr);

        WHEN ("a tree is added to an FSM")
        {
            b.setParent(&sm);
            REQUIRE(b.parent() == &sm);
            THEN ("the state machine of the sub-tree changes")
            {
                for (State_t* state : {&b, &b1, &b2, &b3, &b4})
                    REQUIRE(state->stateMachine() == &sm);
            }
        }

        WHEN ("a tree is added as sub-tree")
        {
            b.setParent(&a);
            REQUIRE(b.parent() == &a);
            THEN ("the state machine of the sub-tree changes")
            {
                for (State_t* state : {&b, &b1, &b2, &b3, &b4})
                    REQUIRE(state->stateMachine() == &sm);
            }
        }
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
const ll C = 1000000007;

int N, M;
ll dp[3010][3010][2];

int main () {
  cin >> N >> M;
  for (auto i = 0; i < M; ++i) {
    for (auto j = 0; j <= N; ++j) {
      for (auto k = 0; k < 2; ++k) {
        dp[i][j][k] = 0;
      }
    }
  }
  for (auto i = 0; i < M; ++i) {
    for (auto j = 0; j <= N; ++j) {
      if (j == 0) {
        dp[i][j][0] = 0;
        dp[i][j][1] = 1;
      } else {
        dp[i][j][0] = 1;
        dp[i][j][1] = 0;
      }
    }
  }
  for (auto i = 0; i < M; ++i) {
    for (auto j = 0; j <= N; ++j) {
      if (j == 1) {
        dp[i+1][j-1][1] += dp[i][j][0];
        dp[i+1][j-1][1] %= C;
      } else if (j > 0) {
        dp[i+1][j-1][0] += dp[i][j][0];
        dp[i+1][j-1][0] %= C;
      }
      if (j < N) {
        dp[i+1][j+1][0] += dp[i][j][0];
        dp[i+1][j+1][0] %= C;
      }
      if (j == 1) {
        dp[i+1][j][1] += dp[i][j][0];
        dp[i+1][j][1] %= C;
      } else if (j > 0) {
        dp[i+1][j][0] += dp[i][j][0];
        dp[i+1][j][0] %= C;
      }
      if (j < N) {
        dp[i+1][j][0] += dp[i][j][0];
        dp[i+1][j][0] %= C;
      }
      if (j > 0) {
        dp[i+1][j-1][1] += dp[i][j][1];
        dp[i+1][j-1][1] %= C;
      }
      if (j < N) {
        dp[i+1][j+1][1] += dp[i][j][1];
        dp[i+1][j+1][1] %= C;
      }
      if (j > 0) {
        dp[i+1][j][1] += dp[i][j][1];
        dp[i+1][j][1] %= C;
      }
      if (j < N) {
        dp[i+1][j][1] += dp[i][j][1];
        dp[i+1][j][1] %= C;
      }
    }
  }
  ll ans = 0;
  for (auto j = 0; j <= N; ++j) {
    ans += dp[M][j][1];
    ans %= M;
  }
  cout << ans << endl;
}
<commit_msg>tried D.cpp to 'D'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
const ll C = 1000000007;

int N, M;
ll dp[3010][3010][2];

int main () {
  cin >> N >> M;
  for (auto i = 0; i < M; ++i) {
    for (auto j = 0; j <= N; ++j) {
      for (auto k = 0; k < 2; ++k) {
        dp[i][j][k] = 0;
      }
    }
  }
  for (auto j = 0; j <= N; ++j) {
    if (j == 0) {
      dp[0][j][0] = 0;
      dp[0][j][1] = 1;
    } else {
      dp[0][j][0] = 1;
      dp[0][j][1] = 0;
    }
  }
  for (auto i = 0; i < M; ++i) {
    for (auto j = 0; j <= N; ++j) {
      if (j == 1) {
        dp[i+1][j-1][1] += dp[i][j][0];
        dp[i+1][j-1][1] %= C;
      } else if (j > 0) {
        dp[i+1][j-1][0] += dp[i][j][0];
        dp[i+1][j-1][0] %= C;
      }
      if (j < N) {
        dp[i+1][j+1][0] += dp[i][j][0];
        dp[i+1][j+1][0] %= C;
      }
      if (j == 1) {
        dp[i+1][j][1] += dp[i][j][0];
        dp[i+1][j][1] %= C;
      } else if (j > 0) {
        dp[i+1][j][0] += dp[i][j][0];
        dp[i+1][j][0] %= C;
      }
      if (j < N) {
        dp[i+1][j][0] += dp[i][j][0];
        dp[i+1][j][0] %= C;
      }
      if (j > 0) {
        dp[i+1][j-1][1] += dp[i][j][1];
        dp[i+1][j-1][1] %= C;
      }
      if (j < N) {
        dp[i+1][j+1][1] += dp[i][j][1];
        dp[i+1][j+1][1] %= C;
      }
      if (j > 0) {
        dp[i+1][j][1] += dp[i][j][1];
        dp[i+1][j][1] %= C;
      }
      if (j < N) {
        dp[i+1][j][1] += dp[i][j][1];
        dp[i+1][j][1] %= C;
      }
    }
  }
  ll ans = 0;
  for (auto j = 0; j <= N; ++j) {
    ans += dp[M][j][1];
    ans %= M;
  }
  cout << ans << endl;
}
<|endoftext|>


<commit_before>/*Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
*/

#include <stdio.h>

class Solution {
public:
	int addDigits(int num) {
		return (num - 9 *((num - 1)/9));
	}
};

int main() {
	Solution s;

	int ret = s.addDigits(12345);
	printf("Return value is %d\n", ret);

	return 0;
}
<commit_msg>task258 accepted<commit_after><|endoftext|>


<commit_before>/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-8-4 22:09:58
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const char ds[4] = {'D', 'R', 'U', 'L'};

typedef tuple<ll, int, int> state;

// const int C = 1e6+10;
const ll infty = 1000000007;

int N, M, K;
string D;
string S[1010];
ll dist[200010][4];
ll ans[1010][1010];

int main()
{
  cin >> N >> M >> K;
  cin >> D;
  D = D + D + D;
  for (auto i = 0; i < N; i++)
  {
    cin >> S[i];
  }
  for (auto k = 0; k < 4; k++)
  {
    dist[2 * K][k] = infty;
  }
  for (int i = 2 * K - 1; i >= 0; i--)
  {
    for (auto k = 0; k < 4; k++)
    {
      if (D[i + 1] == ds[k])
      {
        dist[i][k] = 1;
      }
      else
      {
        dist[i][k] = dist[i + 1][k] + 1;
      }
    }
  }
  int sx, sy, gx, gy;
  fill(&ans[0][0], &ans[0][0] + 1010 * 1010, -1);
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < M; j++)
    {
      if (S[i][j] == 'S')
      {
        sx = i;
        sy = j;
      }
      else if (S[i][j] == 'G')
      {
        gx = i;
        gy = j;
      }
    }
  }
  priority_queue<state, vector<state>, greater<state>> Q;
  Q.push(state(0, sx, sy));
  while (!Q.empty())
  {
    ll d = get<0>(Q.top());
    int x = get<1>(Q.top());
    int y = get<2>(Q.top());
    Q.pop();
    if (ans[x][y] == -1)
    {
      ans[x][y] = d;
      if (x == gx && y == gy)
      {
        cout << d << endl;
        return 0;
      }
      for (auto k = 0; k < 4; k++)
      {
        int new_x = x + dx[k];
        int new_y = y + dy[k];
        if (0 <= new_x && new_x < N && 0 <= new_y && new_y < M && S[new_x][new_y] != '#' && ans[new_x][new_y] == -1)
        {
          ll new_d = d + dist[d % K][k];
          if (new_d < infty)
          {
            Q.push(state(new_d, new_x, new_y));
          }
        }
      }
    }
  }
  cout << -1 << endl;
}<commit_msg>tried E.cpp to 'E'<commit_after>/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-8-4 22:09:58
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const char ds[4] = {'D', 'R', 'U', 'L'};

typedef tuple<ll, int, int> state;

// const int C = 1e6+10;
const ll infty = 1000000007;

int N, M, K;
string D;
string S[1010];
ll dist[200010][4];
ll ans[1010][1010];

int main()
{
  cin >> N >> M >> K;
  cin >> D;
  D = D + D + D;
  for (auto i = 0; i < N; i++)
  {
    cin >> S[i];
  }
  for (auto k = 0; k < 4; k++)
  {
    dist[2 * K][k] = infty;
  }
  for (int i = 2 * K - 1; i >= 0; i--)
  {
    for (auto k = 0; k < 4; k++)
    {
      if (D[i + 1] == ds[k])
      {
        dist[i][k] = 1;
      }
      else
      {
        dist[i][k] = dist[i + 1][k] + 1;
      }
    }
  }
  int sx, sy, gx, gy;
  fill(&ans[0][0], &ans[0][0] + 1010 * 1010, -1);
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < M; j++)
    {
      if (S[i][j] == 'S')
      {
        sx = i;
        sy = j;
      }
      else if (S[i][j] == 'G')
      {
        gx = i;
        gy = j;
      }
    }
  }
  priority_queue<state, vector<state>, greater<state>> Q;
  Q.push(state(0, sx, sy));
  while (!Q.empty())
  {
    ll d = get<0>(Q.top());
    int x = get<1>(Q.top());
    int y = get<2>(Q.top());
    Q.pop();
    if (ans[x][y] == -1)
    {
      ans[x][y] = d;
      cerr << "ans[" << x << "][" << y << "] = " << ans[x][y] << endl;
      if (x == gx && y == gy)
      {
        cout << d << endl;
        return 0;
      }
      for (auto k = 0; k < 4; k++)
      {
        int new_x = x + dx[k];
        int new_y = y + dy[k];
        if (0 <= new_x && new_x < N && 0 <= new_y && new_y < M && S[new_x][new_y] != '#' && ans[new_x][new_y] == -1)
        {
          ll new_d = d + dist[d % K][k];
          if (new_d < infty)
          {
            Q.push(state(new_d, new_x, new_y));
          }
        }
      }
    }
  }
  cout << -1 << endl;
}<|endoftext|>