<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_input_method_library.h"
#include "chrome/browser/chromeos/cros/mock_screen_lock_library.h"
#include "chrome/browser/chromeos/login/mock_authenticator.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/screen_locker_tester.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/browser_dialogs.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "views/controls/textfield/textfield.h"
#include "views/window/window_gtk.h"

namespace {

// An object that wait for lock state and fullscreen state.
class Waiter : public NotificationObserver {
 public:
  explicit Waiter(Browser* browser)
      : browser_(browser),
        running_(false) {
    registrar_.Add(this,
                   NotificationType::SCREEN_LOCK_STATE_CHANGED,
                   NotificationService::AllSources());
    handler_id_ = g_signal_connect(
        G_OBJECT(browser_->window()->GetNativeHandle()),
        "window-state-event",
        G_CALLBACK(OnWindowStateEventThunk),
        this);
  }

  ~Waiter() {
    g_signal_handler_disconnect(
        G_OBJECT(browser_->window()->GetNativeHandle()),
        handler_id_);
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);
    if (running_)
      MessageLoop::current()->Quit();
  }

  // Wait until the two conditions are met.
  void Wait(bool locker_state, bool fullscreen) {
    running_ = true;
    scoped_ptr<chromeos::test::ScreenLockerTester>
        tester(chromeos::ScreenLocker::GetTester());
    while (tester->IsLocked() != locker_state ||
           browser_->window()->IsFullscreen() != fullscreen) {
      ui_test_utils::RunMessageLoop();
    }
    // Make sure all pending tasks are executed.
    ui_test_utils::RunAllPendingInMessageLoop();
    running_ = false;
  }

  CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,
                       GdkEventWindowState*);

 private:
  Browser* browser_;
  gulong handler_id_;
  NotificationRegistrar registrar_;

  // Are we currently running the message loop?
  bool running_;

  DISALLOW_COPY_AND_ASSIGN(Waiter);
};

gboolean Waiter::OnWindowStateEvent(GtkWidget* widget,
                                    GdkEventWindowState* event) {
  MessageLoop::current()->Quit();
  return false;
}

}  // namespace

namespace chromeos {

class ScreenLockerTest : public CrosInProcessBrowserTest {
 public:
  ScreenLockerTest() : mock_screen_lock_library_(NULL),
                       mock_input_method_library_(NULL) {
  }

 protected:
  MockScreenLockLibrary *mock_screen_lock_library_;
  MockInputMethodLibrary *mock_input_method_library_;

  // Test the no password mode with different unlock scheme given by
  // |unlock| function.
  void TestNoPassword(void (unlock)(views::Widget*)) {
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
        .Times(1)
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
        .Times(1)
        .RetiresOnSaturation();
    UserManager::Get()->OffTheRecordUserLoggedIn();
    ScreenLocker::Show();
    scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
    tester->EmulateWindowManagerReady();
    if (!chromeos::ScreenLocker::GetTester()->IsLocked())
      ui_test_utils::WaitForNotification(
          NotificationType::SCREEN_LOCK_STATE_CHANGED);
    EXPECT_TRUE(tester->IsLocked());
    tester->InjectMockAuthenticator("", "");

    unlock(tester->GetWidget());

    ui_test_utils::RunAllPendingInMessageLoop();
    EXPECT_TRUE(tester->IsLocked());

    // Emulate LockScreen request from PowerManager (via SessionManager).
    ScreenLocker::Hide();
    ui_test_utils::RunAllPendingInMessageLoop();
    EXPECT_FALSE(tester->IsLocked());
  }

  void LockScreenWithUser(test::ScreenLockerTester* tester,
                          const std::string& user) {
    UserManager::Get()->UserLoggedIn(user);
    ScreenLocker::Show();
    tester->EmulateWindowManagerReady();
    if (!tester->IsLocked()) {
      ui_test_utils::WaitForNotification(
          NotificationType::SCREEN_LOCK_STATE_CHANGED);
    }
    EXPECT_TRUE(tester->IsLocked());
  }

 private:
  virtual void SetUpInProcessBrowserTestFixture() {
    cros_mock_->InitStatusAreaMocks();
    cros_mock_->InitMockScreenLockLibrary();
    mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();
    mock_input_method_library_ = cros_mock_->mock_input_method_library();
    EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))
        .Times(1)
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())
        .Times(1)
        .RetiresOnSaturation();
    // Expectations for the status are on the screen lock window.
    cros_mock_->SetStatusAreaMocksExpectations();
    // Expectations for the status area on the browser window.
    cros_mock_->SetStatusAreaMocksExpectations();
  }

  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
    command_line->AppendSwitch(switches::kNoFirstRun);
  }

  DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);
};

// See http://crbug.com/79374
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, FLAKY_TestBasic) {
  EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())
      .Times(1)
      .WillRepeatedly((testing::Return(0)))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  UserManager::Get()->UserLoggedIn("user");
  ScreenLocker::Show();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  tester->EmulateWindowManagerReady();
  if (!chromeos::ScreenLocker::GetTester()->IsLocked())
    ui_test_utils::WaitForNotification(
        NotificationType::SCREEN_LOCK_STATE_CHANGED);

  // Test to make sure that the widget is actually appearing and is of
  // reasonable size, preventing a regression of
  // http://code.google.com/p/chromium-os/issues/detail?id=5987
  gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds();
  EXPECT_GT(lock_bounds.width(), 10);
  EXPECT_GT(lock_bounds.height(), 10);

  tester->InjectMockAuthenticator("user", "pass");
  EXPECT_TRUE(tester->IsLocked());
  tester->EnterPassword("fail");
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_TRUE(tester->IsLocked());
  tester->EnterPassword("pass");
  ui_test_utils::RunAllPendingInMessageLoop();
  // Successful authentication simply send a unlock request to PowerManager.
  EXPECT_TRUE(tester->IsLocked());

  // Emulate LockScreen request from PowerManager (via SessionManager).
  // TODO(oshima): Find out better way to handle this in mock.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

// Temporarily disabling screen locker tests while investigating the
// issue crbug.com/78764.
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestFullscreenExit) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  {
    Waiter waiter(browser());
    browser()->ToggleFullscreenMode();
    waiter.Wait(false /* not locked */, true /* full screen */);
    EXPECT_TRUE(browser()->window()->IsFullscreen());
    EXPECT_FALSE(tester->IsLocked());
  }
  {
    Waiter waiter(browser());
    UserManager::Get()->UserLoggedIn("user");
    ScreenLocker::Show();
    tester->EmulateWindowManagerReady();
    waiter.Wait(true /* locked */, false /* full screen */);
    EXPECT_FALSE(browser()->window()->IsFullscreen());
    EXPECT_TRUE(tester->IsLocked());
  }
  tester->InjectMockAuthenticator("user", "pass");
  tester->EnterPassword("pass");
  ui_test_utils::RunAllPendingInMessageLoop();
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

void MouseMove(views::Widget* widget) {
  ui_controls::SendMouseMove(10, 10);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest,
                       DISABLED_TestNoPasswordWithMouseMove) {
  TestNoPassword(MouseMove);
}

void MouseClick(views::Widget* widget) {
  ui_controls::SendMouseClick(ui_controls::RIGHT);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest,
                       DISABLED_TestNoPasswordWithMouseClick) {
  TestNoPassword(MouseClick);
}

void KeyPress(views::Widget* widget) {
  ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),
                            ui::VKEY_SPACE, false, false, false, false);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithKeyPress) {
  TestNoPassword(KeyPress);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(2)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  LockScreenWithUser(tester.get(), "user");

  // Ensure there's a profile or this test crashes.
  ProfileManager::GetDefaultProfile();

  // Calling Show again simply send LockCompleted signal.
  ScreenLocker::Show();
  EXPECT_TRUE(tester->IsLocked());

  // Close the locker to match expectations.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  LockScreenWithUser(tester.get(), "user");

  // Ensure there's a profile or this test crashes.
  ProfileManager::GetDefaultProfile();

  tester->SetPassword("password");
  EXPECT_EQ("password", tester->GetPassword());
  // Escape clears the password.
  ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()),
                            ui::VKEY_ESCAPE, false, false, false, false);
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_EQ("", tester->GetPassword());

  // Close the locker to match expectations.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

}  // namespace chromeos
<commit_msg>Disabling TestBasic<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_input_method_library.h"
#include "chrome/browser/chromeos/cros/mock_screen_lock_library.h"
#include "chrome/browser/chromeos/login/mock_authenticator.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/screen_locker_tester.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/browser_dialogs.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "views/controls/textfield/textfield.h"
#include "views/window/window_gtk.h"

namespace {

// An object that wait for lock state and fullscreen state.
class Waiter : public NotificationObserver {
 public:
  explicit Waiter(Browser* browser)
      : browser_(browser),
        running_(false) {
    registrar_.Add(this,
                   NotificationType::SCREEN_LOCK_STATE_CHANGED,
                   NotificationService::AllSources());
    handler_id_ = g_signal_connect(
        G_OBJECT(browser_->window()->GetNativeHandle()),
        "window-state-event",
        G_CALLBACK(OnWindowStateEventThunk),
        this);
  }

  ~Waiter() {
    g_signal_handler_disconnect(
        G_OBJECT(browser_->window()->GetNativeHandle()),
        handler_id_);
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);
    if (running_)
      MessageLoop::current()->Quit();
  }

  // Wait until the two conditions are met.
  void Wait(bool locker_state, bool fullscreen) {
    running_ = true;
    scoped_ptr<chromeos::test::ScreenLockerTester>
        tester(chromeos::ScreenLocker::GetTester());
    while (tester->IsLocked() != locker_state ||
           browser_->window()->IsFullscreen() != fullscreen) {
      ui_test_utils::RunMessageLoop();
    }
    // Make sure all pending tasks are executed.
    ui_test_utils::RunAllPendingInMessageLoop();
    running_ = false;
  }

  CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,
                       GdkEventWindowState*);

 private:
  Browser* browser_;
  gulong handler_id_;
  NotificationRegistrar registrar_;

  // Are we currently running the message loop?
  bool running_;

  DISALLOW_COPY_AND_ASSIGN(Waiter);
};

gboolean Waiter::OnWindowStateEvent(GtkWidget* widget,
                                    GdkEventWindowState* event) {
  MessageLoop::current()->Quit();
  return false;
}

}  // namespace

namespace chromeos {

class ScreenLockerTest : public CrosInProcessBrowserTest {
 public:
  ScreenLockerTest() : mock_screen_lock_library_(NULL),
                       mock_input_method_library_(NULL) {
  }

 protected:
  MockScreenLockLibrary *mock_screen_lock_library_;
  MockInputMethodLibrary *mock_input_method_library_;

  // Test the no password mode with different unlock scheme given by
  // |unlock| function.
  void TestNoPassword(void (unlock)(views::Widget*)) {
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
        .Times(1)
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
        .Times(1)
        .RetiresOnSaturation();
    UserManager::Get()->OffTheRecordUserLoggedIn();
    ScreenLocker::Show();
    scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
    tester->EmulateWindowManagerReady();
    if (!chromeos::ScreenLocker::GetTester()->IsLocked())
      ui_test_utils::WaitForNotification(
          NotificationType::SCREEN_LOCK_STATE_CHANGED);
    EXPECT_TRUE(tester->IsLocked());
    tester->InjectMockAuthenticator("", "");

    unlock(tester->GetWidget());

    ui_test_utils::RunAllPendingInMessageLoop();
    EXPECT_TRUE(tester->IsLocked());

    // Emulate LockScreen request from PowerManager (via SessionManager).
    ScreenLocker::Hide();
    ui_test_utils::RunAllPendingInMessageLoop();
    EXPECT_FALSE(tester->IsLocked());
  }

  void LockScreenWithUser(test::ScreenLockerTester* tester,
                          const std::string& user) {
    UserManager::Get()->UserLoggedIn(user);
    ScreenLocker::Show();
    tester->EmulateWindowManagerReady();
    if (!tester->IsLocked()) {
      ui_test_utils::WaitForNotification(
          NotificationType::SCREEN_LOCK_STATE_CHANGED);
    }
    EXPECT_TRUE(tester->IsLocked());
  }

 private:
  virtual void SetUpInProcessBrowserTestFixture() {
    cros_mock_->InitStatusAreaMocks();
    cros_mock_->InitMockScreenLockLibrary();
    mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();
    mock_input_method_library_ = cros_mock_->mock_input_method_library();
    EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))
        .Times(1)
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())
        .Times(1)
        .RetiresOnSaturation();
    // Expectations for the status are on the screen lock window.
    cros_mock_->SetStatusAreaMocksExpectations();
    // Expectations for the status area on the browser window.
    cros_mock_->SetStatusAreaMocksExpectations();
  }

  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
    command_line->AppendSwitch(switches::kNoFirstRun);
  }

  DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);
};

// Temporarily disabling all screen locker tests while investigating the
// issue crbug.com/78764.
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestBasic) {
  EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())
      .Times(1)
      .WillRepeatedly((testing::Return(0)))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  UserManager::Get()->UserLoggedIn("user");
  ScreenLocker::Show();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  tester->EmulateWindowManagerReady();
  if (!chromeos::ScreenLocker::GetTester()->IsLocked())
    ui_test_utils::WaitForNotification(
        NotificationType::SCREEN_LOCK_STATE_CHANGED);

  // Test to make sure that the widget is actually appearing and is of
  // reasonable size, preventing a regression of
  // http://code.google.com/p/chromium-os/issues/detail?id=5987
  gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds();
  EXPECT_GT(lock_bounds.width(), 10);
  EXPECT_GT(lock_bounds.height(), 10);

  tester->InjectMockAuthenticator("user", "pass");
  EXPECT_TRUE(tester->IsLocked());
  tester->EnterPassword("fail");
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_TRUE(tester->IsLocked());
  tester->EnterPassword("pass");
  ui_test_utils::RunAllPendingInMessageLoop();
  // Successful authentication simply send a unlock request to PowerManager.
  EXPECT_TRUE(tester->IsLocked());

  // Emulate LockScreen request from PowerManager (via SessionManager).
  // TODO(oshima): Find out better way to handle this in mock.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestFullscreenExit) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  {
    Waiter waiter(browser());
    browser()->ToggleFullscreenMode();
    waiter.Wait(false /* not locked */, true /* full screen */);
    EXPECT_TRUE(browser()->window()->IsFullscreen());
    EXPECT_FALSE(tester->IsLocked());
  }
  {
    Waiter waiter(browser());
    UserManager::Get()->UserLoggedIn("user");
    ScreenLocker::Show();
    tester->EmulateWindowManagerReady();
    waiter.Wait(true /* locked */, false /* full screen */);
    EXPECT_FALSE(browser()->window()->IsFullscreen());
    EXPECT_TRUE(tester->IsLocked());
  }
  tester->InjectMockAuthenticator("user", "pass");
  tester->EnterPassword("pass");
  ui_test_utils::RunAllPendingInMessageLoop();
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

void MouseMove(views::Widget* widget) {
  ui_controls::SendMouseMove(10, 10);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest,
                       DISABLED_TestNoPasswordWithMouseMove) {
  TestNoPassword(MouseMove);
}

void MouseClick(views::Widget* widget) {
  ui_controls::SendMouseClick(ui_controls::RIGHT);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest,
                       DISABLED_TestNoPasswordWithMouseClick) {
  TestNoPassword(MouseClick);
}

void KeyPress(views::Widget* widget) {
  ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),
                            ui::VKEY_SPACE, false, false, false, false);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithKeyPress) {
  TestNoPassword(KeyPress);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(2)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  LockScreenWithUser(tester.get(), "user");

  // Ensure there's a profile or this test crashes.
  ProfileManager::GetDefaultProfile();

  // Calling Show again simply send LockCompleted signal.
  ScreenLocker::Show();
  EXPECT_TRUE(tester->IsLocked());

  // Close the locker to match expectations.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  LockScreenWithUser(tester.get(), "user");

  // Ensure there's a profile or this test crashes.
  ProfileManager::GetDefaultProfile();

  tester->SetPassword("password");
  EXPECT_EQ("password", tester->GetPassword());
  // Escape clears the password.
  ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()),
                            ui::VKEY_ESCAPE, false, false, false, false);
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_EQ("", tester->GetPassword());

  // Close the locker to match expectations.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

}  // namespace chromeos
<|endoftext|>


<commit_before>#include <legui/HorizontalSplitter.h>

namespace legui
{
    void HorizontalSplitter::setBoundingBox(const sf::FloatRect &box)
    {

    }
    void HorizontalSplitter::updateSize()
    {

    }
};
<commit_msg>Implemented the HorizontalSplitter.<commit_after>#include <legui/HorizontalSplitter.h>
#include <legui/Config.h>

namespace legui
{
    void HorizontalSplitter::setBoundingBox(const sf::FloatRect &box)
    {
        float offset = 0;
        for(std::size_t i = 0; i < getSize(); ++i)
        {
            if(i % 2 == 0)  //Number is even. (left side)
            {
                m_widgets[i]->setBoundingBox(sf::FloatRect(box.left, box.height + offset, box.width / 2, Config::getFloat("STANDARD_HEIGHT")));
            }
            else            //Number is not even. (right side)
            {
                m_widgets[i]->setBoundingBox(sf::FloatRect(box.left + box.width / 2, box.height + offset, box.width / 2, Config::getFloat("STANDARD_HEIGHT")));
                //Update the size of the widget.
                m_widgets[i]->updateSize();
                //Increase the y offset based on the height of the last right element.
                offset += m_widgets[i]->getBoundingBox().height;
            }
        }
    }
    void HorizontalSplitter::updateSize()
    {
        m_boundingBox.height = 0;
        for(auto &it : m_widgets)
        {
            it->updateSize();
            m_boundingBox.height += it->getBoundingBox().height;
        }
    }
};
<|endoftext|>


<commit_before>#include <cctag/visualDebug.hpp>
#include <cctag/fileDebug.hpp>

#include <boost/filesystem.hpp>
#include <opencv2/opencv.hpp>

namespace bfs = boost::filesystem;

namespace cctag
{

CCTagVisualDebug::CCTagVisualDebug()
{
}

CCTagVisualDebug::~CCTagVisualDebug()
{
}

void CCTagVisualDebug::initializeFolders(const boost::filesystem::path & rootPath, const std::string & outputFolder, std::size_t nCrowns)
{
#ifdef CCTAG_SERIALIZE
  // Create inputImagePath/result if it does not exist
  std::stringstream resultFolderName, localizationFolderName, identificationFolderName, absoluteOutputFolderName;

  resultFolderName << rootPath.string();

  if( outputFolder != "" ) {
    resultFolderName << "/" << outputFolder;
    if (!bfs::exists(resultFolderName.str())) {
      bfs::create_directory(resultFolderName.str());
    }
  }

  resultFolderName << "/cctag" << nCrowns << "CC";

  if (!bfs::exists(resultFolderName.str())) {
      bfs::create_directory(resultFolderName.str());
  }

  localizationFolderName << resultFolderName.str() << "/localization";
  identificationFolderName << resultFolderName.str() << "/identification";

  if (!bfs::exists(localizationFolderName.str())) {
      bfs::create_directory(localizationFolderName.str());
  }

  if (!bfs::exists(identificationFolderName.str())) {
      bfs::create_directory(identificationFolderName.str());
  }

  _pathRoot = resultFolderName.str();
  CCTAG_COUT_VAR(_pathRoot);
#endif
}

void CCTagVisualDebug::setPyramidLevel(int level) {
#ifdef CCTAG_SERIALIZE
  _pyramidLevel = level;
#endif
}

int CCTagVisualDebug::getPyramidLevel() {
    return _pyramidLevel;
}

std::string CCTagVisualDebug::getPath() const {
  return _path;
}

void CCTagVisualDebug::setImageFileName(const std::string& imageFileName) {
#ifdef CCTAG_SERIALIZE
  _imageFileName = imageFileName;
    CCTAG_COUT_VAR(_imageFileName);
  _path = _pathRoot + "/" + imageFileName;
  CCTAG_COUT_VAR(_path);
  if (!bfs::exists(_path)) {
    bfs::create_directory(_path);
    CCTAG_COUT("creation done");
  }
  CCTAG_COUT("exit");
#endif
}

void CCTagVisualDebug::initBackgroundImage(const cv::Mat & back)
{
#ifdef CCTAG_SERIALIZE
  cv::Mat temp; // todo@Lilian: why do I need to use temp ?
  cvtColor(back, temp, cv::COLOR_GRAY2RGB);
  _backImage = temp.clone();
#endif
}

void CCTagVisualDebug::newSession(const std::string & sessionName) {
#ifdef CCTAG_SERIALIZE
  // Don't erase old sessions
  if (_sessions.find(sessionName) == _sessions.end()) {
      _sessions[sessionName] = _backImage;
  }
#endif
}

void CCTagVisualDebug::drawText(const cctag::Point2dN<double> & p, const std::string & text, const cctag::Color & color) {
#ifdef CCTAG_SERIALIZE
  CvFont font1;
  cvInitFont(&font1, CV_FONT_HERSHEY_SIMPLEX, 0.8, 0.8, 0, 2);

  IplImage iplBack = _backImage;
  cvPutText( &iplBack, text.c_str(),
          cvPoint((int) p.x(), (int) p.y()),
          &font1, CV_RGB(color[0] * 255, color[1] * 255, color[2] * 255));
#endif
}

void CCTagVisualDebug::drawPoint(const cctag::Point2dN<double> & point, const cctag::Color & color) {
#ifdef CCTAG_SERIALIZE
  if (point.x() >= 1 && point.x() < _backImage.cols-1 &&
          point.y() >= 1 && point.y() < _backImage.rows-1)
  {
    cv::Vec3b cvColor;
    cvColor.val[0] = 255*color[0];
    cvColor.val[1] = 255*color[1];
    cvColor.val[2] = 255*color[2];
    _backImage.at<cv::Vec3b>(point.y(),point.x()) = cvColor;
    //cv::rectangle(_backImage, cvPoint(point.x()-1.0,point.y()-1.0), cvPoint(point.x()+1.0,point.y()+1.0), cv::Scalar(255*color[0], 255*color[1], 255*color[2]),0);
  }
#endif // CCTAG_SERIALIZE
}

void CCTagVisualDebug::drawPoint(const cctag::DirectedPoint2d<double> & point, const cctag::Color & color) {
#ifdef CCTAG_SERIALIZE
  if (point.x() >= 1 && point.x() < _backImage.cols-1 &&
          point.y() >= 1 && point.y() < _backImage.rows-1)
  {
    //cv::Vec3b cvColor;
    //cvColor.val[0] = 255*color[0];
    //cvColor.val[1] = 255*color[1];
    //cvColor.val[2] = 255*color[2];
    //_backImage.at<cv::Vec3b>(point.y(),point.x()) = cvColor;
    cv::Point p1(point.x(),point.y());
    cv::Point p2(point.x() + point.dX(),point.y() + point.dY());
    cv::arrowedLine( _backImage, p1, p2, cv::Scalar(255*color[0], 255*color[1], 255*color[2]) );

    //cv::rectangle(_backImage, cvPoint(point.x()-1.0,point.y()-1.0), cvPoint(point.x()+1.0,point.y()+1.0), cv::Scalar(255*color[0], 255*color[1], 255*color[2]),0);
  }
#endif // CCTAG_SERIALIZE
}

void CCTagVisualDebug::drawPoints(const std::vector<cctag::Point2dN<double> > & points, const cctag::Color & color)
{
#ifdef CCTAG_SERIALIZE
  BOOST_FOREACH(const cctag::Point2dN<double> & point, points) {
      CCTagVisualDebug::instance().drawPoint(point, cctag::color_red);
  }
#endif
}

// todo templater la function ci-dessus avec celle ci-dessous
void CCTagVisualDebug::drawPoints(const std::vector<cctag::DirectedPoint2d<double> > & points, const cctag::Color & color)
{
#ifdef CCTAG_SERIALIZE
  BOOST_FOREACH(const cctag::Point2dN<double> & point, points) {
      CCTagVisualDebug::instance().drawPoint(cctag::Point2dN<double>(point.x(),point.y()), cctag::color_red);
  }
#endif
}

void CCTagVisualDebug::drawMarker(const cctag::CCTag& marker, bool drawScaledMarker)
{
#ifdef CCTAG_SERIALIZE
  numerical::geometry::Ellipse rescaledOuterEllipse;
  if (drawScaledMarker) {
      rescaledOuterEllipse = marker.rescaledOuterEllipse();
  } else {
      rescaledOuterEllipse = marker.outerEllipse();
  }
  Point2dN<double> & center = rescaledOuterEllipse.center();

  // Display ellipses
  if (drawScaledMarker) {
      rescaledOuterEllipse = marker.rescaledOuterEllipse();
  } else {
      rescaledOuterEllipse = marker.outerEllipse();
  }

  cv::Scalar color;
  // Set the color
  if (marker.getStatus() == status::no_collected_cuts) {
    // Magenta
    color = cv::Scalar(255,0,255);
  }else if (marker.getStatus() == status::no_selected_cuts) {
    // Cyan
    color = cv::Scalar(0,255,255);
  }else if(marker.getStatus() == status::opti_has_diverged){
    // Red
    color = cv::Scalar(255,0,0);
  }else if(marker.getStatus() == status::id_not_reliable){
    // Cyan
    color = cv::Scalar(0,255,255);
  }else if(marker.getStatus() == status::id_reliable){
    // Green
    color = cv::Scalar(0,255,0);
  }else if(marker.getStatus() == status::degenerate){
    // Yellow 1
    color = cv::Scalar(255,255,0);
  }else if(marker.getStatus() == 0 ){
    // Green
    color = cv::Scalar(0,255,0);
  }

  //CCTAT_COUT_VAR(color);

  cv::ellipse(_backImage , cv::Point(center.x(),center.y()),
      cv::Size(rescaledOuterEllipse.a(), rescaledOuterEllipse.b()),
      rescaledOuterEllipse.angle()*180/M_PI, 0, 360, color);
#endif
}

void CCTagVisualDebug::drawInfos(const cctag::CCTag& marker, bool drawScaledMarker)
{
#ifdef CCTAG_SERIALIZE
    CvFont font1;
  cvInitFont(&font1, CV_FONT_HERSHEY_SIMPLEX, 0.8, 0.8, 0, 2);

  std::string sId = boost::lexical_cast<std::string>(marker.id() + 1);

  int x, y;
  if (drawScaledMarker) {
      x = int (marker.rescaledOuterEllipse().center().x());
      y = int (marker.rescaledOuterEllipse().center().y());
  } else {
      x = int (marker.outerEllipse().center().x());
      y = int (marker.outerEllipse().center().y());
  }

  IplImage iplImg = _backImage;
  cvPutText( &iplImg, sId.c_str(),
          cvPoint(x-10, y+10),
          &font1, CV_RGB(255, 140, 0));
#endif
}

std::string CCTagVisualDebug::getImageFileName() const {
    return _imageFileName;
}

void CCTagVisualDebug::out(const std::string & filename) const {
#ifdef CCTAG_SERIALIZE
  cv::imwrite(filename, _backImage);
#endif
}

void CCTagVisualDebug::outPutAllSessions() const {
#ifdef CCTAG_SERIALIZE
    BOOST_FOREACH(const Sessions::const_iterator::value_type & v, _sessions) {
        const std::string filename = _path + "/" + v.first + ".png";
        cv::imwrite(filename, v.second);
    }
#endif
}

void CCTagVisualDebug::writeLocalizationView(cctag::CCTag::List& markers) const {
#ifdef CCTAG_SERIALIZE
    std::stringstream localizationResultFileName;
    localizationResultFileName << "../localization/" << _imageFileName;
    CCTagVisualDebug::instance().newSession(localizationResultFileName.str());

    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
        CCTagVisualDebug::instance().drawMarker(marker);
        CCTagVisualDebug::instance().drawInfos(marker);
    }
#endif
}

void CCTagVisualDebug::writeIdentificationView(cctag::CCTag::List& markers) const {
#ifdef CCTAG_SERIALIZE

    std::stringstream identificationResultFileName;
    identificationResultFileName << "../identification/" << _imageFileName;
    CCTagVisualDebug::instance().newSession(identificationResultFileName.str());

    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
        CCTagVisualDebug::instance().drawMarker(marker);
        CCTagVisualDebug::instance().drawPoints(marker.rescaledOuterEllipsePoints(), cctag::color_red);
        CCTagVisualDebug::instance().drawInfos(marker);
    }

#endif
}

void CCTagVisualDebug::clearSessions() {
#ifdef CCTAG_SERIALIZE
    _sessions.erase(_sessions.begin(), _sessions.end());
#endif
}

} // namespace cctag
<commit_msg>less debug output unless VISUAL_DEBUG is given<commit_after>#include <cctag/visualDebug.hpp>
#include <cctag/fileDebug.hpp>

#include <boost/filesystem.hpp>
#include <opencv2/opencv.hpp>

namespace bfs = boost::filesystem;

namespace cctag
{

CCTagVisualDebug::CCTagVisualDebug()
{
}

CCTagVisualDebug::~CCTagVisualDebug()
{
}

void CCTagVisualDebug::initializeFolders(const boost::filesystem::path & rootPath, const std::string & outputFolder, std::size_t nCrowns)
{
#ifdef CCTAG_SERIALIZE
  // Create inputImagePath/result if it does not exist
  std::stringstream resultFolderName, localizationFolderName, identificationFolderName, absoluteOutputFolderName;

  resultFolderName << rootPath.string();

  if( outputFolder != "" ) {
    resultFolderName << "/" << outputFolder;
    if (!bfs::exists(resultFolderName.str())) {
      bfs::create_directory(resultFolderName.str());
    }
  }

  resultFolderName << "/cctag" << nCrowns << "CC";

  if (!bfs::exists(resultFolderName.str())) {
      bfs::create_directory(resultFolderName.str());
  }

  localizationFolderName << resultFolderName.str() << "/localization";
  identificationFolderName << resultFolderName.str() << "/identification";

  if (!bfs::exists(localizationFolderName.str())) {
      bfs::create_directory(localizationFolderName.str());
  }

  if (!bfs::exists(identificationFolderName.str())) {
      bfs::create_directory(identificationFolderName.str());
  }

  _pathRoot = resultFolderName.str();
  CCTAG_COUT_VAR(_pathRoot);
#endif
}

void CCTagVisualDebug::setPyramidLevel(int level) {
#ifdef CCTAG_SERIALIZE
  _pyramidLevel = level;
#endif
}

int CCTagVisualDebug::getPyramidLevel() {
    return _pyramidLevel;
}

std::string CCTagVisualDebug::getPath() const {
  return _path;
}

void CCTagVisualDebug::setImageFileName(const std::string& imageFileName) {
#ifdef CCTAG_SERIALIZE
  _imageFileName = imageFileName;
    CCTAG_COUT_VAR(_imageFileName);
  _path = _pathRoot + "/" + imageFileName;
  CCTAG_COUT_VAR(_path);
  if (!bfs::exists(_path)) {
    bfs::create_directory(_path);
    CCTAG_COUT("creation done");
  }
  CCTAG_COUT("exit");
#endif
}

void CCTagVisualDebug::initBackgroundImage(const cv::Mat & back)
{
#ifdef CCTAG_SERIALIZE
  cv::Mat temp; // todo@Lilian: why do I need to use temp ?
  cvtColor(back, temp, cv::COLOR_GRAY2RGB);
  _backImage = temp.clone();
#endif
}

void CCTagVisualDebug::newSession(const std::string & sessionName) {
#ifdef CCTAG_SERIALIZE
  // Don't erase old sessions
  if (_sessions.find(sessionName) == _sessions.end()) {
      _sessions[sessionName] = _backImage;
  }
#endif
}

void CCTagVisualDebug::drawText(const cctag::Point2dN<double> & p, const std::string & text, const cctag::Color & color) {
#ifdef CCTAG_SERIALIZE
  CvFont font1;
  cvInitFont(&font1, CV_FONT_HERSHEY_SIMPLEX, 0.8, 0.8, 0, 2);

  IplImage iplBack = _backImage;
  cvPutText( &iplBack, text.c_str(),
          cvPoint((int) p.x(), (int) p.y()),
          &font1, CV_RGB(color[0] * 255, color[1] * 255, color[2] * 255));
#endif
}

void CCTagVisualDebug::drawPoint(const cctag::Point2dN<double> & point, const cctag::Color & color) {
#ifdef CCTAG_SERIALIZE
  if (point.x() >= 1 && point.x() < _backImage.cols-1 &&
          point.y() >= 1 && point.y() < _backImage.rows-1)
  {
    cv::Vec3b cvColor;
    cvColor.val[0] = 255*color[0];
    cvColor.val[1] = 255*color[1];
    cvColor.val[2] = 255*color[2];
    _backImage.at<cv::Vec3b>(point.y(),point.x()) = cvColor;
    //cv::rectangle(_backImage, cvPoint(point.x()-1.0,point.y()-1.0), cvPoint(point.x()+1.0,point.y()+1.0), cv::Scalar(255*color[0], 255*color[1], 255*color[2]),0);
  }
#endif // CCTAG_SERIALIZE
}

void CCTagVisualDebug::drawPoint(const cctag::DirectedPoint2d<double> & point, const cctag::Color & color) {
#ifdef CCTAG_SERIALIZE
  if (point.x() >= 1 && point.x() < _backImage.cols-1 &&
          point.y() >= 1 && point.y() < _backImage.rows-1)
  {
    //cv::Vec3b cvColor;
    //cvColor.val[0] = 255*color[0];
    //cvColor.val[1] = 255*color[1];
    //cvColor.val[2] = 255*color[2];
    //_backImage.at<cv::Vec3b>(point.y(),point.x()) = cvColor;
    cv::Point p1(point.x(),point.y());
    cv::Point p2(point.x() + point.dX(),point.y() + point.dY());
    cv::arrowedLine( _backImage, p1, p2, cv::Scalar(255*color[0], 255*color[1], 255*color[2]) );

    //cv::rectangle(_backImage, cvPoint(point.x()-1.0,point.y()-1.0), cvPoint(point.x()+1.0,point.y()+1.0), cv::Scalar(255*color[0], 255*color[1], 255*color[2]),0);
  }
#endif // CCTAG_SERIALIZE
}

void CCTagVisualDebug::drawPoints(const std::vector<cctag::Point2dN<double> > & points, const cctag::Color & color)
{
#ifdef CCTAG_SERIALIZE
  BOOST_FOREACH(const cctag::Point2dN<double> & point, points) {
      CCTagVisualDebug::instance().drawPoint(point, cctag::color_red);
  }
#endif
}

// todo templater la function ci-dessus avec celle ci-dessous
void CCTagVisualDebug::drawPoints(const std::vector<cctag::DirectedPoint2d<double> > & points, const cctag::Color & color)
{
#ifdef CCTAG_SERIALIZE
  BOOST_FOREACH(const cctag::Point2dN<double> & point, points) {
      CCTagVisualDebug::instance().drawPoint(cctag::Point2dN<double>(point.x(),point.y()), cctag::color_red);
  }
#endif
}

void CCTagVisualDebug::drawMarker(const cctag::CCTag& marker, bool drawScaledMarker)
{
#ifdef CCTAG_SERIALIZE
  numerical::geometry::Ellipse rescaledOuterEllipse;
  if (drawScaledMarker) {
      rescaledOuterEllipse = marker.rescaledOuterEllipse();
  } else {
      rescaledOuterEllipse = marker.outerEllipse();
  }
  Point2dN<double> & center = rescaledOuterEllipse.center();

  // Display ellipses
  if (drawScaledMarker) {
      rescaledOuterEllipse = marker.rescaledOuterEllipse();
  } else {
      rescaledOuterEllipse = marker.outerEllipse();
  }

  cv::Scalar color;
  // Set the color
  if (marker.getStatus() == status::no_collected_cuts) {
    // Magenta
    color = cv::Scalar(255,0,255);
  }else if (marker.getStatus() == status::no_selected_cuts) {
    // Cyan
    color = cv::Scalar(0,255,255);
  }else if(marker.getStatus() == status::opti_has_diverged){
    // Red
    color = cv::Scalar(255,0,0);
  }else if(marker.getStatus() == status::id_not_reliable){
    // Cyan
    color = cv::Scalar(0,255,255);
  }else if(marker.getStatus() == status::id_reliable){
    // Green
    color = cv::Scalar(0,255,0);
  }else if(marker.getStatus() == status::degenerate){
    // Yellow 1
    color = cv::Scalar(255,255,0);
  }else if(marker.getStatus() == 0 ){
    // Green
    color = cv::Scalar(0,255,0);
  }

  //CCTAT_COUT_VAR(color);

  cv::ellipse(_backImage , cv::Point(center.x(),center.y()),
      cv::Size(rescaledOuterEllipse.a(), rescaledOuterEllipse.b()),
      rescaledOuterEllipse.angle()*180/M_PI, 0, 360, color);
#endif
}

void CCTagVisualDebug::drawInfos(const cctag::CCTag& marker, bool drawScaledMarker)
{
#ifdef CCTAG_SERIALIZE
    CvFont font1;
  cvInitFont(&font1, CV_FONT_HERSHEY_SIMPLEX, 0.8, 0.8, 0, 2);

  std::string sId = boost::lexical_cast<std::string>(marker.id() + 1);

  int x, y;
  if (drawScaledMarker) {
      x = int (marker.rescaledOuterEllipse().center().x());
      y = int (marker.rescaledOuterEllipse().center().y());
  } else {
      x = int (marker.outerEllipse().center().x());
      y = int (marker.outerEllipse().center().y());
  }

  IplImage iplImg = _backImage;
  cvPutText( &iplImg, sId.c_str(),
          cvPoint(x-10, y+10),
          &font1, CV_RGB(255, 140, 0));
#endif
}

std::string CCTagVisualDebug::getImageFileName() const {
    return _imageFileName;
}

void CCTagVisualDebug::out(const std::string & filename) const {
#if defined(CCTAG_SERIALIZE) && defined(VISUAL_DEBUG)
  cv::imwrite(filename, _backImage);
#endif
}

void CCTagVisualDebug::outPutAllSessions() const {
#if defined(CCTAG_SERIALIZE) && defined(VISUAL_DEBUG)
    BOOST_FOREACH(const Sessions::const_iterator::value_type & v, _sessions) {
        const std::string filename = _path + "/" + v.first + ".png";
        cv::imwrite(filename, v.second);
    }
#endif
}

void CCTagVisualDebug::writeLocalizationView(cctag::CCTag::List& markers) const {
#ifdef CCTAG_SERIALIZE
    std::stringstream localizationResultFileName;
    localizationResultFileName << "../localization/" << _imageFileName;
    CCTagVisualDebug::instance().newSession(localizationResultFileName.str());

    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
        CCTagVisualDebug::instance().drawMarker(marker);
        CCTagVisualDebug::instance().drawInfos(marker);
    }
#endif
}

void CCTagVisualDebug::writeIdentificationView(cctag::CCTag::List& markers) const {
#ifdef CCTAG_SERIALIZE

    std::stringstream identificationResultFileName;
    identificationResultFileName << "../identification/" << _imageFileName;
    CCTagVisualDebug::instance().newSession(identificationResultFileName.str());

    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
        CCTagVisualDebug::instance().drawMarker(marker);
        CCTagVisualDebug::instance().drawPoints(marker.rescaledOuterEllipsePoints(), cctag::color_red);
        CCTagVisualDebug::instance().drawInfos(marker);
    }

#endif
}

void CCTagVisualDebug::clearSessions() {
#ifdef CCTAG_SERIALIZE
    _sessions.erase(_sessions.begin(), _sessions.end());
#endif
}

} // namespace cctag
<|endoftext|>


<commit_before>#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>

#define MAX_BUF 1024

#include <sstream>
#include <iostream>
#include <boost/property_tree/json_parser.hpp>

int main()
{
    int fd = socket( AF_LOCAL, SOCK_DGRAM, 0 );

	struct sockaddr_un addr;
	bzero( &addr, sizeof(addr) );
	addr.sun_family = AF_LOCAL;
	strcpy( addr.sun_path, "/tmp/mpu.6050.unix.domain" );

    char buf[MAX_BUF];
   if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0) {
    perror("setsockopt(SO_REUSEADDR) failed");
   }
   if(::bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0)
   {

     printf(" cannot bind socket: %d. Passed in address is invalid or port is in use",errno);

     return 0;

   }

    int degree = 90;
    while(degree >0) {
    	socklen_t len = sizeof(addr);
        int ret = ::recvfrom(fd, buf, MAX_BUF, 0, (struct sockaddr *)&addr, &len);
        if(ret>0){
            //printf("Received: %s\n", buf);
            std::stringstream ss;
            ss << buf;
            boost::property_tree::ptree pt;
            boost::property_tree::read_json(ss, pt);
            std::cout << pt.get<double>("yaw") << std::endl;
        } else if (ret==0){
        } else {
            printf("ret=<%d>\n",ret);
        }
    }
    close(fd);

    return 0;
}
<commit_msg>Update turn.cpp<commit_after>#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>

#define MAX_BUF 1024

#include <sstream>
#include <iostream>
#include <boost/property_tree/json_parser.hpp>

int main()
{
    int fd = socket( AF_LOCAL, SOCK_DGRAM, 0 );

	struct sockaddr_un addr;
	bzero( &addr, sizeof(addr) );
	addr.sun_family = AF_LOCAL;
	strcpy( addr.sun_path, "/tmp/mpu.6050.unix.domain" );

   int use = 1;
   if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &use, sizeof(int)) < 0) {
    perror("setsockopt(SO_REUSEADDR) failed");
   }
   if(::bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0)
   {

     printf(" cannot bind socket: %d. Passed in address is invalid or port is in use",errno);

     return 0;

   }

    char buf[MAX_BUF];
    int degree = 90;
    while(degree >0) {
    	socklen_t len = sizeof(addr);
        int ret = ::recvfrom(fd, buf, MAX_BUF, 0, (struct sockaddr *)&addr, &len);
        if(ret>0){
            //printf("Received: %s\n", buf);
            std::stringstream ss;
            ss << buf;
            boost::property_tree::ptree pt;
            boost::property_tree::read_json(ss, pt);
            std::cout << pt.get<double>("yaw") << std::endl;
        } else if (ret==0){
        } else {
            printf("ret=<%d>\n",ret);
        }
    }
    close(fd);

    return 0;
}
<|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

    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 "Math/DualComplex.h"
#include "Math/DualQuaternion.h"

namespace Corrade { namespace Utility {

#ifndef DOXYGEN_GENERATING_OUTPUT
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<2, 2, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<3, 3, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<4, 4, Magnum::Float>>;
#ifndef MAGNUM_TARGET_GLES
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<2, 2, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<3, 3, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<4, 4, Magnum::Double>>;
#endif

template struct ConfigurationValue<Magnum::Math::RectangularMatrix<2, 3, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<3, 2, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<2, 4, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<4, 2, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<3, 4, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<4, 3, Magnum::Float>>;
#ifndef MAGNUM_TARGET_GLES
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<2, 3, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<3, 2, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<2, 4, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<4, 2, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<3, 4, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<4, 3, Magnum::Double>>;
#endif

/* For some reason mingw's GCC instantiates ConfigurationValue<Magnum::Math::Geometry::Rectangle<...>>
   (which depends on ConfigurationValue<Magnum::Math::Vector<4, ...>) before
   these and then loudly complains about multiple definitions. WTF. */

template struct ConfigurationValue<Magnum::Math::Vector<2, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::Vector<3, Magnum::Float>>;
#ifndef _WIN32
template struct ConfigurationValue<Magnum::Math::Vector<4, Magnum::Float>>;
#endif
template struct ConfigurationValue<Magnum::Math::Vector<2, Magnum::Int>>;
template struct ConfigurationValue<Magnum::Math::Vector<3, Magnum::Int>>;
#ifndef _WIN32
template struct ConfigurationValue<Magnum::Math::Vector<4, Magnum::Int>>;
#endif
template struct ConfigurationValue<Magnum::Math::Vector<2, Magnum::UnsignedInt>>;
template struct ConfigurationValue<Magnum::Math::Vector<3, Magnum::UnsignedInt>>;
#ifndef _WIN32
template struct ConfigurationValue<Magnum::Math::Vector<4, Magnum::UnsignedInt>>;
#endif
#ifndef MAGNUM_TARGET_GLES
template struct ConfigurationValue<Magnum::Math::Vector<2, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::Vector<3, Magnum::Double>>;
#ifndef _WIN32
template struct ConfigurationValue<Magnum::Math::Vector<4, Magnum::Double>>;
#endif
#endif
#endif

}}

namespace Magnum { namespace Math {

#ifndef DOXYGEN_GENERATING_OUTPUT
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Complex<Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Complex<Double>&);
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualComplex<Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualComplex<Double>&);
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualQuaternion<Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualQuaternion<Double>&);
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Quaternion<Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Quaternion<Double>&);
#endif

/* Check proper size of GL types */
static_assert(sizeof(Vector<2, Float>) == 8, "Improper size of 2-element Float vector");
static_assert(sizeof(Vector<3, Float>) == 12, "Improper size of 3-element Float vector");
static_assert(sizeof(Vector<4, Float>) == 16, "Improper size of 4-element Float vector");
static_assert(sizeof(Vector<2, Int>) == 8, "Improper size of 2-element Int vector");
static_assert(sizeof(Vector<3, Int>) == 12, "Improper size of 3-element Int vector");
static_assert(sizeof(Vector<4, Int>) == 16, "Improper size of 4-element Int vector");
static_assert(sizeof(Vector<2, UnsignedInt>) == 8, "Improper size of 2-element UnsignedInt vector");
static_assert(sizeof(Vector<3, UnsignedInt>) == 12, "Improper size of 3-element UnsignedInt vector");
static_assert(sizeof(Vector<4, UnsignedInt>) == 16, "Improper size of 4-element UnsignedInt vector");
#ifndef MAGNUM_TARGET_GLES
static_assert(sizeof(Vector<2, Double>) == 16, "Improper size of 2-element Double vector");
static_assert(sizeof(Vector<3, Double>) == 24, "Improper size of 3-element Double vector");
static_assert(sizeof(Vector<4, Double>) == 32, "Improper size of 4-element Double vector");
#endif

static_assert(sizeof(RectangularMatrix<2, 2, Float>) == 16, "Improper size of 2x2 Float matrix");
static_assert(sizeof(RectangularMatrix<3, 3, Float>) == 36, "Improper size of 3x3 Float matrix");
static_assert(sizeof(RectangularMatrix<4, 4, Float>) == 64, "Improper size of 4x4 Float matrix");
#ifndef MAGNUM_TARGET_GLES
static_assert(sizeof(RectangularMatrix<2, 2, Double>) == 32, "Improper size of 2x2 Double matrix");
static_assert(sizeof(RectangularMatrix<3, 3, Double>) == 72, "Improper size of 3x3 Double matrix");
static_assert(sizeof(RectangularMatrix<4, 4, Double>) == 128, "Improper size of 4x4 Double matrix");
#endif

static_assert(sizeof(RectangularMatrix<2, 3, Float>) == 24, "Improper size of 2x3 Float matrix");
static_assert(sizeof(RectangularMatrix<3, 2, Float>) == 24, "Improper size of 3x2 Float matrix");
static_assert(sizeof(RectangularMatrix<2, 4, Float>) == 32, "Improper size of 2x4 Float matrix");
static_assert(sizeof(RectangularMatrix<4, 2, Float>) == 32, "Improper size of 4x2 Float matrix");
static_assert(sizeof(RectangularMatrix<3, 4, Float>) == 48, "Improper size of 3x4 Float matrix");
static_assert(sizeof(RectangularMatrix<4, 3, Float>) == 48, "Improper size of 4x3 Float matrix");
#ifndef MAGNUM_TARGET_GLES
static_assert(sizeof(RectangularMatrix<2, 3, Double>) == 48, "Improper size of 2x3 Double matrix");
static_assert(sizeof(RectangularMatrix<3, 2, Double>) == 48, "Improper size of 3x2 Double matrix");
static_assert(sizeof(RectangularMatrix<2, 4, Double>) == 64, "Improper size of 2x4 Double matrix");
static_assert(sizeof(RectangularMatrix<4, 2, Double>) == 64, "Improper size of 4x2 Double matrix");
static_assert(sizeof(RectangularMatrix<3, 4, Double>) == 96, "Improper size of 3x4 Double matrix");
static_assert(sizeof(RectangularMatrix<4, 3, Double>) == 96, "Improper size of 4x3 Double matrix");
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 2, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 3, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 4, Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 2, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 3, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 4, Double>&);
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 3, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 2, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 4, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 2, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 4, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 3, Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 3, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 2, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 4, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 2, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 4, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 3, Double>&);
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit<Rad, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit<Deg, Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit<Rad, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit<Deg, Double>&);
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, Int>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, Int>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, Int>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, UnsignedInt>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, UnsignedInt>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, UnsignedInt>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, Double>&);
#endif
#endif

}}

<commit_msg>MinGW32's linker issues _are only_ MinGW32's fault.<commit_after>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

    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 "Math/DualComplex.h"
#include "Math/DualQuaternion.h"

namespace Corrade { namespace Utility {

#ifndef DOXYGEN_GENERATING_OUTPUT
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<2, 2, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<3, 3, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<4, 4, Magnum::Float>>;
#ifndef MAGNUM_TARGET_GLES
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<2, 2, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<3, 3, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<4, 4, Magnum::Double>>;
#endif

template struct ConfigurationValue<Magnum::Math::RectangularMatrix<2, 3, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<3, 2, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<2, 4, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<4, 2, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<3, 4, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<4, 3, Magnum::Float>>;
#ifndef MAGNUM_TARGET_GLES
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<2, 3, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<3, 2, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<2, 4, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<4, 2, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<3, 4, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::RectangularMatrix<4, 3, Magnum::Double>>;
#endif

/* For some reason mingw's GCC instantiates ConfigurationValue<Magnum::Math::Geometry::Rectangle<...>>
   (which depends on ConfigurationValue<Magnum::Math::Vector<4, ...>) before
   these and then loudly complains about multiple definitions. WTF. */

template struct ConfigurationValue<Magnum::Math::Vector<2, Magnum::Float>>;
template struct ConfigurationValue<Magnum::Math::Vector<3, Magnum::Float>>;
#ifndef __MINGW32__
template struct ConfigurationValue<Magnum::Math::Vector<4, Magnum::Float>>;
#endif
template struct ConfigurationValue<Magnum::Math::Vector<2, Magnum::Int>>;
template struct ConfigurationValue<Magnum::Math::Vector<3, Magnum::Int>>;
#ifndef __MINGW32__
template struct ConfigurationValue<Magnum::Math::Vector<4, Magnum::Int>>;
#endif
template struct ConfigurationValue<Magnum::Math::Vector<2, Magnum::UnsignedInt>>;
template struct ConfigurationValue<Magnum::Math::Vector<3, Magnum::UnsignedInt>>;
#ifndef __MINGW32__
template struct ConfigurationValue<Magnum::Math::Vector<4, Magnum::UnsignedInt>>;
#endif
#ifndef MAGNUM_TARGET_GLES
template struct ConfigurationValue<Magnum::Math::Vector<2, Magnum::Double>>;
template struct ConfigurationValue<Magnum::Math::Vector<3, Magnum::Double>>;
#ifndef __MINGW32__
template struct ConfigurationValue<Magnum::Math::Vector<4, Magnum::Double>>;
#endif
#endif
#endif

}}

namespace Magnum { namespace Math {

#ifndef DOXYGEN_GENERATING_OUTPUT
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Complex<Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Complex<Double>&);
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualComplex<Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualComplex<Double>&);
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualQuaternion<Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const DualQuaternion<Double>&);
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Quaternion<Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Quaternion<Double>&);
#endif

/* Check proper size of GL types */
static_assert(sizeof(Vector<2, Float>) == 8, "Improper size of 2-element Float vector");
static_assert(sizeof(Vector<3, Float>) == 12, "Improper size of 3-element Float vector");
static_assert(sizeof(Vector<4, Float>) == 16, "Improper size of 4-element Float vector");
static_assert(sizeof(Vector<2, Int>) == 8, "Improper size of 2-element Int vector");
static_assert(sizeof(Vector<3, Int>) == 12, "Improper size of 3-element Int vector");
static_assert(sizeof(Vector<4, Int>) == 16, "Improper size of 4-element Int vector");
static_assert(sizeof(Vector<2, UnsignedInt>) == 8, "Improper size of 2-element UnsignedInt vector");
static_assert(sizeof(Vector<3, UnsignedInt>) == 12, "Improper size of 3-element UnsignedInt vector");
static_assert(sizeof(Vector<4, UnsignedInt>) == 16, "Improper size of 4-element UnsignedInt vector");
#ifndef MAGNUM_TARGET_GLES
static_assert(sizeof(Vector<2, Double>) == 16, "Improper size of 2-element Double vector");
static_assert(sizeof(Vector<3, Double>) == 24, "Improper size of 3-element Double vector");
static_assert(sizeof(Vector<4, Double>) == 32, "Improper size of 4-element Double vector");
#endif

static_assert(sizeof(RectangularMatrix<2, 2, Float>) == 16, "Improper size of 2x2 Float matrix");
static_assert(sizeof(RectangularMatrix<3, 3, Float>) == 36, "Improper size of 3x3 Float matrix");
static_assert(sizeof(RectangularMatrix<4, 4, Float>) == 64, "Improper size of 4x4 Float matrix");
#ifndef MAGNUM_TARGET_GLES
static_assert(sizeof(RectangularMatrix<2, 2, Double>) == 32, "Improper size of 2x2 Double matrix");
static_assert(sizeof(RectangularMatrix<3, 3, Double>) == 72, "Improper size of 3x3 Double matrix");
static_assert(sizeof(RectangularMatrix<4, 4, Double>) == 128, "Improper size of 4x4 Double matrix");
#endif

static_assert(sizeof(RectangularMatrix<2, 3, Float>) == 24, "Improper size of 2x3 Float matrix");
static_assert(sizeof(RectangularMatrix<3, 2, Float>) == 24, "Improper size of 3x2 Float matrix");
static_assert(sizeof(RectangularMatrix<2, 4, Float>) == 32, "Improper size of 2x4 Float matrix");
static_assert(sizeof(RectangularMatrix<4, 2, Float>) == 32, "Improper size of 4x2 Float matrix");
static_assert(sizeof(RectangularMatrix<3, 4, Float>) == 48, "Improper size of 3x4 Float matrix");
static_assert(sizeof(RectangularMatrix<4, 3, Float>) == 48, "Improper size of 4x3 Float matrix");
#ifndef MAGNUM_TARGET_GLES
static_assert(sizeof(RectangularMatrix<2, 3, Double>) == 48, "Improper size of 2x3 Double matrix");
static_assert(sizeof(RectangularMatrix<3, 2, Double>) == 48, "Improper size of 3x2 Double matrix");
static_assert(sizeof(RectangularMatrix<2, 4, Double>) == 64, "Improper size of 2x4 Double matrix");
static_assert(sizeof(RectangularMatrix<4, 2, Double>) == 64, "Improper size of 4x2 Double matrix");
static_assert(sizeof(RectangularMatrix<3, 4, Double>) == 96, "Improper size of 3x4 Double matrix");
static_assert(sizeof(RectangularMatrix<4, 3, Double>) == 96, "Improper size of 4x3 Double matrix");
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 2, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 3, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 4, Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 2, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 3, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 4, Double>&);
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 3, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 2, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 4, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 2, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 4, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 3, Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 3, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 2, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<2, 4, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 2, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<3, 4, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const RectangularMatrix<4, 3, Double>&);
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit<Rad, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit<Deg, Float>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit<Rad, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Unit<Deg, Double>&);
#endif

template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, Float>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, Int>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, Int>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, Int>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, UnsignedInt>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, UnsignedInt>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, UnsignedInt>&);
#ifndef MAGNUM_TARGET_GLES
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<2, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<3, Double>&);
template Corrade::Utility::Debug operator<<(Corrade::Utility::Debug, const Vector<4, Double>&);
#endif
#endif

}}

<|endoftext|>


<commit_before>//===- llvm/ADT/SmallVector.cpp - 'Normally small' vectors ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License.
// ==============================================================================
// LLVM Release License
// ==============================================================================
// University of Illinois/NCSA
// Open Source License
//
// Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign.
// All rights reserved.
//
// Developed by:
//
// LLVM Team
//
// University of Illinois at Urbana-Champaign
//
// http://llvm.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal with
// 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:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimers in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the names of the LLVM Team, University of Illinois at
// Urbana-Champaign, nor the names of its contributors may be used to
// endorse or promote products derived from this Software without specific
// prior written permission.
//
// 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
// CONTRIBUTORS 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 WITH THE
// SOFTWARE.
//
//===----------------------------------------------------------------------===//
//
// This file implements the SmallVector class.
//
//===----------------------------------------------------------------------===//

#include "OgreSmallVector.h"

namespace Ogre {

/// grow_pod - This is an implementation of the grow() method which only works
/// on POD-like datatypes and is out of line to reduce code duplication.
void SmallVectorBase::grow_pod(size_t MinSizeInBytes, size_t TSize) {
	size_t CurSizeBytes = size_in_bytes();
  size_t NewCapacityInBytes = 2 * capacity_in_bytes() + TSize; // Always grow.
	if (NewCapacityInBytes < MinSizeInBytes)
		NewCapacityInBytes = MinSizeInBytes;

  void *NewElts;
  if (this->isSmall()) {
    NewElts = malloc(NewCapacityInBytes);

	// Copy the elements over.  No need to run dtors on PODs.
	memcpy(NewElts, this->BeginX, CurSizeBytes);
  } else {
    // If this wasn't grown from the inline copy, grow the allocated space.
    NewElts = realloc(this->BeginX, NewCapacityInBytes);
  }

	this->EndX = (char*)NewElts+CurSizeBytes;
	this->BeginX = NewElts;
	this->CapacityX = (char*)this->BeginX + NewCapacityInBytes;
}

}<commit_msg>Added missing #include "OgreStableHeaders.h" to OgreSmallVector.cpp.<commit_after>//===- llvm/ADT/SmallVector.cpp - 'Normally small' vectors ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License.
// ==============================================================================
// LLVM Release License
// ==============================================================================
// University of Illinois/NCSA
// Open Source License
//
// Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign.
// All rights reserved.
//
// Developed by:
//
// LLVM Team
//
// University of Illinois at Urbana-Champaign
//
// http://llvm.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal with
// 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:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimers in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the names of the LLVM Team, University of Illinois at
// Urbana-Champaign, nor the names of its contributors may be used to
// endorse or promote products derived from this Software without specific
// prior written permission.
//
// 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
// CONTRIBUTORS 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 WITH THE
// SOFTWARE.
//
//===----------------------------------------------------------------------===//
//
// This file implements the SmallVector class.
//
//===----------------------------------------------------------------------===//

#include "OgreStableHeaders.h"

#include "OgreSmallVector.h"

namespace Ogre {

/// grow_pod - This is an implementation of the grow() method which only works
/// on POD-like datatypes and is out of line to reduce code duplication.
void SmallVectorBase::grow_pod(size_t MinSizeInBytes, size_t TSize) {
	size_t CurSizeBytes = size_in_bytes();
  size_t NewCapacityInBytes = 2 * capacity_in_bytes() + TSize; // Always grow.
	if (NewCapacityInBytes < MinSizeInBytes)
		NewCapacityInBytes = MinSizeInBytes;

  void *NewElts;
  if (this->isSmall()) {
    NewElts = malloc(NewCapacityInBytes);

	// Copy the elements over.  No need to run dtors on PODs.
	memcpy(NewElts, this->BeginX, CurSizeBytes);
  } else {
    // If this wasn't grown from the inline copy, grow the allocated space.
    NewElts = realloc(this->BeginX, NewCapacityInBytes);
  }

	this->EndX = (char*)NewElts+CurSizeBytes;
	this->BeginX = NewElts;
	this->CapacityX = (char*)this->BeginX + NewCapacityInBytes;
}

}<|endoftext|>


<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/data/service/data_transfer.h"

#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace data {
namespace {

class TestDataTransferServer : public DataTransferServer {
 public:
  explicit TestDataTransferServer(bool* called) : called_(called) {}
  Status Start() override {
    *called_ = true;
    return Status::OK();
  }
  int get_port() override { return 0; }

 private:
  bool* called_;
};

template <class T>
GetElementResult MakeElementResult(T value) {
  GetElementResult result;
  result.components.push_back(Tensor(std::move(value)));
  result.element_index = 0;
  result.end_of_sequence = false;
  return result;
}

TEST(DataTransferTest, RegisterDataTransferServerBuilder) {
  bool called = false;
  DataTransferServer::Register("test", [&called](auto _) {
    return std::make_shared<TestDataTransferServer>(&called);
  });

  std::shared_ptr<DataTransferServer> server;
  TF_ASSERT_OK(DataTransferServer::Build("test", {}, &server));
  EXPECT_FALSE(called);

  TF_ASSERT_OK(server->Start());
  EXPECT_TRUE(called);
}

TEST(DataTransferTest, EstimateMemoryUsageBytes) {
  GetElementResult empty;
  EXPECT_GT(empty.EstimatedMemoryUsageBytes(), 0);

  Tensor tensor(DT_INT64, TensorShape({10, 10}));
  GetElementResult int64_result = MakeElementResult(tensor);
  EXPECT_GT(int64_result.EstimatedMemoryUsageBytes(), 100 * sizeof(int64_t));
  EXPECT_GT(int64_result.EstimatedMemoryUsageBytes(),
            int64_result.components[0].AllocatedBytes());
  EXPECT_GE(int64_result.EstimatedMemoryUsageBytes(), sizeof(int64_result));
}

TEST(DataTransferTest, EstimateVarintMemoryUsageBytes) {
  const size_t data_size = 1000;
  CompressedElement compressed;
  compressed.set_data(std::string(data_size, 'a'));

  Tensor tensor(DT_VARIANT, TensorShape({}));
  tensor.scalar<Variant>()() = std::move(compressed);

  GetElementResult variant_result = MakeElementResult(tensor);
  EXPECT_GT(variant_result.EstimatedMemoryUsageBytes(), data_size);
}

TEST(DataTransferTest, CopyGetElementResult) {
  std::string hello_world = "hello, world!";
  GetElementResult result = MakeElementResult(hello_world);
  ASSERT_EQ(result.components.size(), 1);
  EXPECT_GT(result.EstimatedMemoryUsageBytes(), hello_world.size());

  GetElementResult copy = result.Copy();
  ASSERT_EQ(copy.components.size(), 1);
  test::ExpectEqual(result.components[0], copy.components[0]);
  EXPECT_EQ(copy.EstimatedMemoryUsageBytes(),
            result.EstimatedMemoryUsageBytes());
}
}  // namespace
}  // namespace data
}  // namespace tensorflow
<commit_msg>#tf-data-service Add a test to verify estimated Tensor size.<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/data/service/data_transfer.h"

#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace data {
namespace {

class TestDataTransferServer : public DataTransferServer {
 public:
  explicit TestDataTransferServer(bool* called) : called_(called) {}
  Status Start() override {
    *called_ = true;
    return Status::OK();
  }
  int get_port() override { return 0; }

 private:
  bool* called_;
};

template <class T>
GetElementResult MakeElementResult(T value) {
  GetElementResult result;
  result.components.push_back(Tensor(std::move(value)));
  result.element_index = 0;
  result.end_of_sequence = false;
  return result;
}

TEST(DataTransferTest, RegisterDataTransferServerBuilder) {
  bool called = false;
  DataTransferServer::Register("test", [&called](auto _) {
    return std::make_shared<TestDataTransferServer>(&called);
  });

  std::shared_ptr<DataTransferServer> server;
  TF_ASSERT_OK(DataTransferServer::Build("test", {}, &server));
  EXPECT_FALSE(called);

  TF_ASSERT_OK(server->Start());
  EXPECT_TRUE(called);
}

TEST(DataTransferTest, EstimateMemoryUsageBytes) {
  GetElementResult empty;
  EXPECT_GT(empty.EstimatedMemoryUsageBytes(), 0);

  Tensor tensor(DT_INT64, TensorShape({10, 100}));
  GetElementResult int64_result = MakeElementResult(tensor);
  EXPECT_GT(int64_result.EstimatedMemoryUsageBytes(), 1000 * sizeof(int64_t));
  EXPECT_GT(int64_result.EstimatedMemoryUsageBytes(),
            int64_result.components[0].AllocatedBytes());
  EXPECT_GE(int64_result.EstimatedMemoryUsageBytes(), sizeof(int64_result));
}

TEST(DataTransferTest, EstimateVariantMemoryUsageBytes) {
  const size_t data_size = 1000;
  CompressedElement compressed;
  compressed.set_data(std::string(data_size, 'a'));

  Tensor tensor(DT_VARIANT, TensorShape({}));
  tensor.scalar<Variant>()() = compressed;

  GetElementResult variant_result = MakeElementResult(tensor);
  EXPECT_GT(variant_result.EstimatedMemoryUsageBytes(), data_size);
  EXPECT_GT(variant_result.EstimatedMemoryUsageBytes(),
            compressed.ByteSizeLong());
  EXPECT_GT(variant_result.EstimatedMemoryUsageBytes(),
            compressed.SpaceUsedLong());
}

TEST(DataTransferTest, CopyGetElementResult) {
  std::string hello_world = "hello, world!";
  GetElementResult result = MakeElementResult(hello_world);
  ASSERT_EQ(result.components.size(), 1);
  EXPECT_GT(result.EstimatedMemoryUsageBytes(), hello_world.size());

  GetElementResult copy = result.Copy();
  ASSERT_EQ(copy.components.size(), 1);
  test::ExpectEqual(result.components[0], copy.components[0]);
  EXPECT_EQ(copy.EstimatedMemoryUsageBytes(),
            result.EstimatedMemoryUsageBytes());
}
}  // namespace
}  // namespace data
}  // namespace tensorflow
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------//
// \file Chimera_MCSA.cpp
// \author Stuart R. Slattery
// \brief Monte Carlo Synthetic Acceleration solver definition.
//---------------------------------------------------------------------------//

#include "Chimera_MCSA.hpp"
#include "Chimera_AdjointMC.hpp"

#include <Epetra_Map.h>
#include <Epetra_Vector.h>

namespace Chimera
{
namespace Solvers
{
//---------------------------------------------------------------------------//
/*!
 * \brief Constructor.
 */
MCSA::MCSA( Teuchos::RCP<Epetra_LinearProblem> &linear_problem )
    : d_linear_problem( linear_problem )
    , d_num_iters( 0 )
{ /* ... */ }

//---------------------------------------------------------------------------//
/*!
 * \brief Destructor.
 */
MCSA::~MCSA()
{ /* ... */ }

//---------------------------------------------------------------------------//
/*!
 * \brief Solve.
 */
void MCSA::iterate( const int max_iters, const double tolerance,
		    const int num_histories, const double weight_cutoff )
{
    // Extract the linear problem.
    Epetra_CrsMatrix *A =
	dynamic_cast<Epetra_CrsMatrix*>( d_linear_problem->GetMatrix() );
    Epetra_Vector *x =
	dynamic_cast<Epetra_Vector*>( d_linear_problem->GetLHS() );
    const Epetra_Vector *b =
	dynamic_cast<Epetra_Vector*>( d_linear_problem->GetRHS() );

    // Setup the residual Adjoint MC solver.
    Epetra_Map row_map = A->RowMap();
    Epetra_Vector delta_x( row_map );
    Epetra_Vector residual( row_map );
    Teuchos::RCP<Epetra_LinearProblem> residual_problem = Teuchos::rcp(
	new Epetra_LinearProblem( A, &delta_x, &residual ) );
    AdjointMC mc_solver = AdjointMC( residual_problem );

    // Iterate.
    Epetra_CrsMatrix H = mc_solver.getH();
    Epetra_Vector temp_vec( row_map );
    d_num_iters = 0;
    double residual_norm = 1.0;
    double b_norm;
    b->NormInf( &b_norm );
    double conv_crit = b_norm*tolerance;
    while ( residual_norm > conv_crit && d_num_iters < max_iters )
    {
	// Richardson iteration.
	H.Apply( *x, temp_vec );
	x->Update( 1.0, temp_vec, 1.0, *b, 0.0 );

	// Compute the residual.
	A->Apply( *x, temp_vec );
	residual.Update( 1.0, *b, -1.0, temp_vec, 0.0 );

	// Solve for delta_x.
	mc_solver.walk( num_histories, weight_cutoff );

	// Apply delta_x.
	x->Update( 1.0, delta_x, 1.0 );

	// Update convergence check.
	residual.NormInf( &residual_norm );
	++d_num_iters;
    }
}

//---------------------------------------------------------------------------//

} // end namespace Solvers
} // end namespace Chimera

//---------------------------------------------------------------------------//
// end Chimera_MCSA.cpp
//---------------------------------------------------------------------------//

<commit_msg>added output to mcsa<commit_after>//---------------------------------------------------------------------------//
// \file Chimera_MCSA.cpp
// \author Stuart R. Slattery
// \brief Monte Carlo Synthetic Acceleration solver definition.
//---------------------------------------------------------------------------//

#include "Chimera_MCSA.hpp"
#include "Chimera_AdjointMC.hpp"

#include <Epetra_Map.h>
#include <Epetra_Vector.h>

namespace Chimera
{
namespace Solvers
{
//---------------------------------------------------------------------------//
/*!
 * \brief Constructor.
 */
MCSA::MCSA( Teuchos::RCP<Epetra_LinearProblem> &linear_problem )
    : d_linear_problem( linear_problem )
    , d_num_iters( 0 )
{ /* ... */ }

//---------------------------------------------------------------------------//
/*!
 * \brief Destructor.
 */
MCSA::~MCSA()
{ /* ... */ }

//---------------------------------------------------------------------------//
/*!
 * \brief Solve.
 */
void MCSA::iterate( const int max_iters, const double tolerance,
		    const int num_histories, const double weight_cutoff )
{
    // Extract the linear problem.
    Epetra_CrsMatrix *A =
	dynamic_cast<Epetra_CrsMatrix*>( d_linear_problem->GetMatrix() );
    Epetra_Vector *x =
	dynamic_cast<Epetra_Vector*>( d_linear_problem->GetLHS() );
    const Epetra_Vector *b =
	dynamic_cast<Epetra_Vector*>( d_linear_problem->GetRHS() );

    // Setup the residual Adjoint MC solver.
    Epetra_Map row_map = A->RowMap();
    Epetra_Vector delta_x( row_map );
    Epetra_Vector residual( row_map );
    Teuchos::RCP<Epetra_LinearProblem> residual_problem = Teuchos::rcp(
	new Epetra_LinearProblem( A, &delta_x, &residual ) );
    AdjointMC mc_solver = AdjointMC( residual_problem );

    // Iterate.
    Epetra_CrsMatrix H = mc_solver.getH();
    Epetra_Vector temp_vec( row_map );
    d_num_iters = 0;
    double residual_norm = 1.0;
    double b_norm;
    b->NormInf( &b_norm );
    double conv_crit = b_norm*tolerance;
    while ( residual_norm > conv_crit && d_num_iters < max_iters )
    {
	// Richardson iteration.
	H.Apply( *x, temp_vec );
	x->Update( 1.0, temp_vec, 1.0, *b, 0.0 );

	// Compute the residual.
	A->Apply( *x, temp_vec );
	residual.Update( 1.0, *b, -1.0, temp_vec, 0.0 );

	// Solve for delta_x.
	mc_solver.walk( num_histories, weight_cutoff );

	// Apply delta_x.
	x->Update( 1.0, delta_x, 1.0 );

	// Update convergence check.
	residual.NormInf( &residual_norm );
	++d_num_iters;
    }

    std::cout << "MCSA Iterations: " << d_num_iters << std::endl;
    std::cout << "Residual: " << residual_norm << std::endl;
}

//---------------------------------------------------------------------------//

} // end namespace Solvers
} // end namespace Chimera

//---------------------------------------------------------------------------//
// end Chimera_MCSA.cpp
//---------------------------------------------------------------------------//

<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include<BALL/FORMAT/readFile.h>

using namespace std;

namespace BALL
{

	char* ReadFile::getToken_(Position& pos, char delimiter) const
	{
		int len = 0;
		char* p = new char[200];

		if(pos >= strlen(line_))
		{
			Log.error() << "in getToken_ : pos too large" << endl;
			throw ReadFileError();
		}

		while (line_[pos] && line_[pos] != delimiter)
		{
			++pos;
		}

		++pos;

		while (line_[pos] != delimiter)
		{
			if (!line_[pos])
			{
				Log.error() << "open token" << endl;
				throw ReadFileError();
			}

			p[len] = line_[pos];
			++len;
			++pos;
		}

		++pos;

		if(len == 0)
		{
			Log.error() << "token could not be read" << endl;
			throw ReadFileError();
		}

		p[len] = '\0';
		return p;
	}

	char* ReadFile::getToken_(Position& pos) const
	{
		int len = 0;
		char* p = new char[200];

		if(pos >= strlen(line_))
		{
			Log.error() << "in getToken_ : pos too large" << endl;
			throw ReadFileError();
		}

		while (line_[pos] && isspace(line_[pos]))
		{
			++pos;
		}

		while (line_[pos] && !isspace(line_[pos]))
		{
			p[len] = line_[pos];
			++len;
			++pos;
		}

		if(len == 0)
		{
			Log.error() << "token could not be read" << endl;
			throw ReadFileError();
		}

		p[len] = '\0';
		return p;
	}

	char* ReadFile::getToken_() const
	{
		if (strlen(line_) > 199)
		{
			Log.error() << "line too long" << endl;
			throw ReadFileError();
		}
		int len = 0;
		int pos = 0;

		char* p = new char[200];

		if(p == 0)
		{
			Log.error() << "memory could not be assigned" << endl;
			throw ReadFileError();
		}

		while (line_[pos] && isspace(line_[pos]))
		{
			++pos;
		}

		while (line_[pos] && !isspace(line_[pos]))
		{
			p[len] = line_[pos];
			++len;
			++pos;
		}

		if(len == 0)
		{
			Log.error() << "token could not be read" << endl;
			throw ReadFileError();
		}

		p[len] = '\0';
		return p;
	}

	string ReadFile::copyString_(Position start, Position end) const
	{
		if (end >= strlen(line_))
		{
			Log.error() << "error in copyString_";
			throw ReadFileError();
		}
		string dest;
		for (; start <= end ; ++start)
		{
			dest += line_[start];
		}
		return dest;
	}

	int ReadFile::switch_(const vector<string>& data) const
	{
		Position i = 0;
		while (i < data.size())
		{
			if (strcmp(line_, data[i].c_str()) == 0)
			{
				return i;
			}
			++i;
		}
		return (-1);
	}

	bool ReadFile::startsWith_(const char* text) const
	{
		return (memcmp(line_, text, strlen(text)) == 0);
	}

	bool ReadFile::search_(const char* text)
	{
		while (!in.eof())
		{
			readLine_();

			if (startsWith_(text))
			{
				return true;
			}
		}
		return false;
	}

	bool ReadFile::search_(const char* text, const char* stop)
	{
		while (!in.eof())
		{
			readLine_();
			if (has_(stop))
			{
				return false;
			}

			if (startsWith_(text))
			{
				return true;
			}
		}
		return false;
	}

	void ReadFile::test_(bool condition, char* msg) const
	{
		if (condition == false)
		{
			Log.error() << msg;
			throw ReadFileError();
		}
	}

	void ReadFile::readLine_()
	{
		in.getline(line_,200);
	}

	void ReadFile::skipLines_(int number)
	{
		for (int i = 0;  i <= number ; i++)
		{
			in.getline(line_,200);
		}
	}

	bool ReadFile::has_(const char* text) const
	{
		Position pos_line = 0;
		Position pos_line2;
		Position pos_text;
		if(strlen(line_) == 0 || strlen(text) == 0 ||
			 strlen(line_) < strlen(text) )
		{
			return false;
		}

		while (line_[pos_line])
		{
			pos_text = 0;
			pos_line2 = pos_line;
			while (text[pos_text])
			{
				if (line_[pos_line2] != text[pos_text])
				{
					break;
				}
				++pos_text;
				++pos_line2;
			}

			if (!text[pos_text])
			{
				return true;
			}

			++pos_line;
		}

		return false;
	}

} //namespace<commit_msg>changed: in test now a warning is given<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include<BALL/FORMAT/readFile.h>

using namespace std;

namespace BALL
{

	char* ReadFile::getToken_(Position& pos, char delimiter) const
	{
		int len = 0;
		char* p = new char[200];

		if(pos >= strlen(line_))
		{
			Log.error() << "in getToken_ : pos too large" << endl;
			throw ReadFileError();
		}

		while (line_[pos] && line_[pos] != delimiter)
		{
			++pos;
		}

		++pos;

		while (line_[pos] != delimiter)
		{
			if (!line_[pos])
			{
				Log.error() << "open token" << endl;
				throw ReadFileError();
			}

			p[len] = line_[pos];
			++len;
			++pos;
		}

		++pos;

		if(len == 0)
		{
			Log.error() << "token could not be read" << endl;
			throw ReadFileError();
		}

		p[len] = '\0';
		return p;
	}

	char* ReadFile::getToken_(Position& pos) const
	{
		int len = 0;
		char* p = new char[200];

		if(pos >= strlen(line_))
		{
			Log.error() << "in getToken_ : pos too large" << endl;
			throw ReadFileError();
		}

		while (line_[pos] && isspace(line_[pos]))
		{
			++pos;
		}

		while (line_[pos] && !isspace(line_[pos]))
		{
			p[len] = line_[pos];
			++len;
			++pos;
		}

		if(len == 0)
		{
			Log.error() << "token could not be read" << endl;
			throw ReadFileError();
		}

		p[len] = '\0';
		return p;
	}

	char* ReadFile::getToken_() const
	{
		if (strlen(line_) > 199)
		{
			Log.error() << "line too long" << endl;
			throw ReadFileError();
		}
		int len = 0;
		int pos = 0;

		char* p = new char[200];

		if(p == 0)
		{
			Log.error() << "memory could not be assigned" << endl;
			throw ReadFileError();
		}

		while (line_[pos] && isspace(line_[pos]))
		{
			++pos;
		}

		while (line_[pos] && !isspace(line_[pos]))
		{
			p[len] = line_[pos];
			++len;
			++pos;
		}

		if(len == 0)
		{
			Log.error() << "token could not be read" << endl;
			throw ReadFileError();
		}

		p[len] = '\0';
		return p;
	}

	string ReadFile::copyString_(Position start, Position end) const
	{
		if (end >= strlen(line_))
		{
			Log.error() << "error in copyString_";
			throw ReadFileError();
		}
		string dest;
		for (; start <= end ; ++start)
		{
			dest += line_[start];
		}
		return dest;
	}

	int ReadFile::switch_(const vector<string>& data) const
	{
		Position i = 0;
		while (i < data.size())
		{
			if (strcmp(line_, data[i].c_str()) == 0)
			{
				return i;
			}
			++i;
		}
		return (-1);
	}

	bool ReadFile::startsWith_(const char* text) const
	{
		return (memcmp(line_, text, strlen(text)) == 0);
	}

	bool ReadFile::search_(const char* text)
	{
		while (!in.eof())
		{
			readLine_();

			if (startsWith_(text))
			{
				return true;
			}
		}
		return false;
	}

	bool ReadFile::search_(const char* text, const char* stop)
	{
		while (!in.eof())
		{
			readLine_();
			if (has_(stop))
			{
				return false;
			}

			if (startsWith_(text))
			{
				return true;
			}
		}
		return false;
	}

	void ReadFile::test_(bool condition, char* msg) const
	{
		if (condition == false)
		{
			Log.warn() << msg;
			throw ReadFileError();
		}
	}

	void ReadFile::readLine_()
	{
		in.getline(line_,200);
	}

	void ReadFile::skipLines_(int number)
	{
		for (int i = 0;  i <= number ; i++)
		{
			in.getline(line_,200);
		}
	}

	bool ReadFile::has_(const char* text) const
	{
		Position pos_line = 0;
		Position pos_line2;
		Position pos_text;
		if(strlen(line_) == 0 || strlen(text) == 0 ||
			 strlen(line_) < strlen(text) )
		{
			return false;
		}

		while (line_[pos_line])
		{
			pos_text = 0;
			pos_line2 = pos_line;
			while (text[pos_text])
			{
				if (line_[pos_line2] != text[pos_text])
				{
					break;
				}
				++pos_text;
				++pos_line2;
			}

			if (!text[pos_text])
			{
				return true;
			}

			++pos_line;
		}

		return false;
	}

} //namespace<|endoftext|>