<commit_before>/*
 * Copyright (c) 2018, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "application_manager/application.h"
#include "application_manager/commands/command_request_test.h"
#include "application_manager/mock_application.h"
#include "application_manager/commands/commands_test.h"
#include "rc_rpc_plugin/commands/hmi/rc_on_remote_control_settings_notification.h"
#include "rc_rpc_plugin/rc_rpc_plugin.h"
#include "rc_rpc_plugin/rc_module_constants.h"
#include "rc_rpc_plugin/mock/mock_resource_allocation_manager.h"
#include "rc_rpc_plugin/mock/mock_interior_data_cache.h"
#include "rc_rpc_plugin/mock/mock_interior_data_manager.h"
#include "gtest/gtest.h"
#include "interfaces/MOBILE_API.h"

using ::testing::_;
using ::testing::Return;
using ::testing::NiceMock;
using ::testing::SaveArg;
using ::testing::Mock;
using application_manager::ApplicationSet;
using application_manager::commands::MessageSharedPtr;
using test::components::application_manager_test::MockApplication;
using test::components::application_manager_test::MockApplicationManager;
using test::components::commands_test::CommandsTest;
using test::components::commands_test::CommandsTestMocks;

namespace {
const uint32_t kAppId = 0u;
const uint32_t kConnectionKey = 1u;
const std::string kPolicyAppId = "Test";
}

namespace rc_rpc_plugin_test {
using namespace rc_rpc_plugin;
using application_manager::ApplicationSet;

class RCOnRemoteControlSettingsNotificationTest
    : public CommandsTest<CommandsTestMocks::kIsNice> {
 public:
  RCOnRemoteControlSettingsNotificationTest()
      : mock_app_(std::make_shared<NiceMock<MockApplication> >()) {}
  MessageSharedPtr CreateBasicMessage() {
    MessageSharedPtr message = CreateMessage();
    (*message)[application_manager::strings::params]
              [application_manager::strings::function_id] =
                  mobile_apis::FunctionID::SetInteriorVehicleDataID;
    (*message)[application_manager::strings::params]
              [application_manager::strings::connection_key] = kConnectionKey;
    (*message)[application_manager::strings::params]
              [application_manager::strings::connection_key] = kAppId;
    smart_objects::SmartObject& msg_param =
        (*message)[application_manager::strings::msg_params];
    msg_param[message_params::kModuleType] = enums_value::kClimate;

    return message;
  }

  template <class Command>
  std::shared_ptr<Command> CreateRCCommand(MessageSharedPtr& msg) {
    InitCommand(kDefaultTimeout_);
    RCCommandParams params{app_mngr_,
                           mock_rpc_service_,
                           mock_hmi_capabilities_,
                           mock_policy_handler_,
                           mock_allocation_manager_,
                           mock_interior_data_cache_,
                           mock_interior_data_manager_};
    return std::make_shared<Command>(msg ? msg : msg = CreateMessage(), params);
  }

 protected:
  std::shared_ptr<MockApplication> mock_app_;
  testing::NiceMock<rc_rpc_plugin_test::MockResourceAllocationManager>
      mock_allocation_manager_;
  testing::NiceMock<rc_rpc_plugin_test::MockInteriorDataCache>
      mock_interior_data_cache_;
  testing::NiceMock<rc_rpc_plugin_test::MockInteriorDataManager>
      mock_interior_data_manager_;
};

TEST_F(RCOnRemoteControlSettingsNotificationTest,
       Run_Allowed_SetAccessMode) {  // Arrange
  MessageSharedPtr mobile_message = CreateBasicMessage();
  (*mobile_message)[application_manager::strings::msg_params]
                   [message_params::kAllowed] = true;

  // Expectations

  ON_CALL(mock_allocation_manager_, GetAccessMode())
      .WillByDefault(Return(hmi_apis::Common_RCAccessMode::ASK_DRIVER));

  EXPECT_CALL(mock_allocation_manager_,
              SetAccessMode(hmi_apis::Common_RCAccessMode::ASK_DRIVER));
  // Act
  std::shared_ptr<
      rc_rpc_plugin::commands::RCOnRemoteControlSettingsNotification> command =
      CreateRCCommand<
          rc_rpc_plugin::commands::RCOnRemoteControlSettingsNotification>(
          mobile_message);

  command->Run();
}

TEST_F(RCOnRemoteControlSettingsNotificationTest,
       Run_NotAllowed_ResetAllAllocations) {
  // Arrange
  MessageSharedPtr mobile_message = CreateBasicMessage();
  (*mobile_message)[application_manager::strings::msg_params]
                   [message_params::kAllowed] = false;

  EXPECT_CALL(mock_allocation_manager_, ResetAllAllocations());
  EXPECT_CALL(mock_interior_data_manager_, OnDisablingRC());

  // Act
  std::shared_ptr<
      rc_rpc_plugin::commands::RCOnRemoteControlSettingsNotification> command =
      CreateRCCommand<
          rc_rpc_plugin::commands::RCOnRemoteControlSettingsNotification>(
          mobile_message);

  command->Run();
  Mock::VerifyAndClearExpectations(&app_mngr_);
}

}  // namespace rc_rpc_plugin_test
<commit_msg>Fix style<commit_after>/*
 * Copyright (c) 2018, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "application_manager/application.h"
#include "application_manager/commands/command_request_test.h"
#include "application_manager/mock_application.h"
#include "application_manager/commands/commands_test.h"
#include "rc_rpc_plugin/commands/hmi/rc_on_remote_control_settings_notification.h"
#include "rc_rpc_plugin/rc_rpc_plugin.h"
#include "rc_rpc_plugin/rc_module_constants.h"
#include "rc_rpc_plugin/mock/mock_resource_allocation_manager.h"
#include "rc_rpc_plugin/mock/mock_interior_data_cache.h"
#include "rc_rpc_plugin/mock/mock_interior_data_manager.h"
#include "gtest/gtest.h"
#include "interfaces/MOBILE_API.h"

using ::testing::_;
using ::testing::Return;
using ::testing::NiceMock;
using ::testing::SaveArg;
using ::testing::Mock;
using application_manager::ApplicationSet;
using application_manager::commands::MessageSharedPtr;
using test::components::application_manager_test::MockApplication;
using test::components::application_manager_test::MockApplicationManager;
using test::components::commands_test::CommandsTest;
using test::components::commands_test::CommandsTestMocks;

namespace {
const uint32_t kAppId = 0u;
const uint32_t kConnectionKey = 1u;
const std::string kPolicyAppId = "Test";
}

namespace rc_rpc_plugin_test {
using namespace rc_rpc_plugin;
using application_manager::ApplicationSet;

class RCOnRemoteControlSettingsNotificationTest
    : public CommandsTest<CommandsTestMocks::kIsNice> {
 public:
  RCOnRemoteControlSettingsNotificationTest()
      : mock_app_(std::make_shared<NiceMock<MockApplication> >()) {}
  MessageSharedPtr CreateBasicMessage() {
    MessageSharedPtr message = CreateMessage();
    (*message)[application_manager::strings::params]
              [application_manager::strings::function_id] =
                  mobile_apis::FunctionID::SetInteriorVehicleDataID;
    (*message)[application_manager::strings::params]
              [application_manager::strings::connection_key] = kConnectionKey;
    (*message)[application_manager::strings::params]
              [application_manager::strings::connection_key] = kAppId;
    smart_objects::SmartObject& msg_param =
        (*message)[application_manager::strings::msg_params];
    msg_param[message_params::kModuleType] = enums_value::kClimate;

    return message;
  }

  template <class Command>
  std::shared_ptr<Command> CreateRCCommand(MessageSharedPtr& msg) {
    InitCommand(kDefaultTimeout_);
    RCCommandParams params{app_mngr_,
                           mock_rpc_service_,
                           mock_hmi_capabilities_,
                           mock_policy_handler_,
                           mock_allocation_manager_,
                           mock_interior_data_cache_,
                           mock_interior_data_manager_};
    return std::make_shared<Command>(msg ? msg : msg = CreateMessage(), params);
  }

 protected:
  std::shared_ptr<MockApplication> mock_app_;
  testing::NiceMock<rc_rpc_plugin_test::MockResourceAllocationManager>
      mock_allocation_manager_;
  testing::NiceMock<rc_rpc_plugin_test::MockInteriorDataCache>
      mock_interior_data_cache_;
  testing::NiceMock<rc_rpc_plugin_test::MockInteriorDataManager>
      mock_interior_data_manager_;
};

TEST_F(RCOnRemoteControlSettingsNotificationTest,
       Run_Allowed_SetAccessMode) {  // Arrange
  MessageSharedPtr mobile_message = CreateBasicMessage();
  (*mobile_message)[application_manager::strings::msg_params]
                   [message_params::kAllowed] = true;

  // Expectations

  ON_CALL(mock_allocation_manager_, GetAccessMode())
      .WillByDefault(Return(hmi_apis::Common_RCAccessMode::ASK_DRIVER));

  EXPECT_CALL(mock_allocation_manager_,
              SetAccessMode(hmi_apis::Common_RCAccessMode::ASK_DRIVER));
  // Act
  std::shared_ptr<
      rc_rpc_plugin::commands::RCOnRemoteControlSettingsNotification> command =
      CreateRCCommand<
          rc_rpc_plugin::commands::RCOnRemoteControlSettingsNotification>(
          mobile_message);

  command->Run();
}

TEST_F(RCOnRemoteControlSettingsNotificationTest,
       Run_NotAllowed_ResetAllAllocations) {
  // Arrange
  MessageSharedPtr mobile_message = CreateBasicMessage();
  (*mobile_message)[application_manager::strings::msg_params]
                   [message_params::kAllowed] = false;

  EXPECT_CALL(mock_allocation_manager_, ResetAllAllocations());
  EXPECT_CALL(mock_interior_data_manager_, OnDisablingRC());

  // Act
  std::shared_ptr<
      rc_rpc_plugin::commands::RCOnRemoteControlSettingsNotification> command =
      CreateRCCommand<
          rc_rpc_plugin::commands::RCOnRemoteControlSettingsNotification>(
          mobile_message);

  command->Run();
  Mock::VerifyAndClearExpectations(&app_mngr_);
}

}  // namespace rc_rpc_plugin_test
<|endoftext|>


<commit_before>#include "player.h"

#include <QCoreApplication>

namespace sp = Spotinetta;

namespace Sonetta {

Player::Player(Spotinetta::Session *session, AudioOutput *output, QObject *parent)
    :   QObject(parent), m_session(session), m_shuffle(false), m_repeat(false),
      m_output(output), m_queue(new QueueModel(this))
{
    Q_ASSERT(session != nullptr);

    m_watcher = new sp::TrackWatcher(session, this);
    m_positionTimer = new QTimer(this);

    // Set up connections
    connect(session, &sp::Session::endOfTrack, this, &Player::next);
    connect(m_positionTimer, &QTimer::timeout, this, &Player::positionChanged);

    // This ensures a track is eventually played whether it's loaded
    // or not
    connect(m_watcher, &sp::TrackWatcher::loaded, [this] {
        play(m_watcher->watched());
    });;

    m_positionTimer->start(150);
}

bool Player::shuffle() const
{
    return m_shuffle;
}

bool Player::repeat() const
{
    return m_repeat;
}

int Player::position() const
{
    return m_output.isNull() ? 0 : m_output->position();
}

sp::Track Player::track() const
{
    return m_watcher->watched();
}

void Player::setShuffle(bool enable)
{
    if (m_shuffle != enable)
    {
        m_shuffle = enable;
        emit shuffleChanged();
    }
}

void Player::setRepeat(bool enable)
{
    if (m_repeat != enable)
    {
        m_repeat = enable;
        emit repeatChanged();
    }
}

QObject * Player::queue() const
{
    return m_queue;
}

void Player::play(const Spotinetta::Track &track)
{
    if (track != this->track())
    {
        m_watcher->watch(track);
        emit trackChanged();
    }

    if (track.isLoaded())
    {
        if (m_session->load(track))
        {
            m_session->play();

            if (!m_output.isNull())
                m_output->resetPosition(0);
        }
    }

    // If track is not loaded, it will be played when it is loaded,
    // as the watcher's loaded signal is connected to play(track)
}

void Player::enqueue(const Spotinetta::Track &track)
{
    // Assumes track is loaded, might want to add watcher and enqueue when ready
    // or it may be better to add watch functionality to QueueModel
    m_queue->enqueue(track);
}

void Player::play()
{
    m_session->play();
}

void Player::playPause()
{
    if (m_session->playbackState() == sp::Session::PlaybackState::Paused)
    {
        play();
    }
    else
    {
        pause();
    }
}

void Player::pause()
{
    m_session->pause();
}

void Player::next()
{
    if (!m_queue->isEmpty())
    {
        play(m_queue->dequeue());
    }
    else
    {
        pause();
        m_watcher->watch(sp::Track());
    }

    // Emit outside if because of end of track situations
    emit trackChanged();
}

}
<commit_msg>Upgraded next() of Player to tackle unavailable tacks when dequeuing from QueueModel<commit_after>#include "player.h"

#include <QCoreApplication>

namespace sp = Spotinetta;

namespace Sonetta {

Player::Player(Spotinetta::Session *session, AudioOutput *output, QObject *parent)
    :   QObject(parent), m_session(session), m_shuffle(false), m_repeat(false),
      m_output(output), m_queue(new QueueModel(this))
{
    Q_ASSERT(session != nullptr);

    m_watcher = new sp::TrackWatcher(session, this);
    m_positionTimer = new QTimer(this);

    // Set up connections
    connect(session, &sp::Session::endOfTrack, this, &Player::next);
    connect(m_positionTimer, &QTimer::timeout, this, &Player::positionChanged);

    // This ensures a track is eventually played whether it's loaded
    // or not
    connect(m_watcher, &sp::TrackWatcher::loaded, [this] {
        play(m_watcher->watched());
    });;

    m_positionTimer->start(150);
}

bool Player::shuffle() const
{
    return m_shuffle;
}

bool Player::repeat() const
{
    return m_repeat;
}

int Player::position() const
{
    return m_output.isNull() ? 0 : m_output->position();
}

sp::Track Player::track() const
{
    return m_watcher->watched();
}

void Player::setShuffle(bool enable)
{
    if (m_shuffle != enable)
    {
        m_shuffle = enable;
        emit shuffleChanged();
    }
}

void Player::setRepeat(bool enable)
{
    if (m_repeat != enable)
    {
        m_repeat = enable;
        emit repeatChanged();
    }
}

QObject * Player::queue() const
{
    return m_queue;
}

void Player::play(const Spotinetta::Track &track)
{
    if (track != this->track())
    {
        m_watcher->watch(track);
        emit trackChanged();
    }

    if (track.isLoaded())
    {
        if (m_session->load(track))
        {
            m_session->play();

            if (!m_output.isNull())
                m_output->resetPosition(0);
        }
    }

    // If track is not loaded, it will be played when it is loaded,
    // as the watcher's loaded signal is connected to play(track)
}

void Player::enqueue(const Spotinetta::Track &track)
{
    // Assumes track is loaded, might want to add watcher and enqueue when ready
    // or it may be better to add watch functionality to QueueModel
    m_queue->enqueue(track);
}

void Player::play()
{
    m_session->play();
}

void Player::playPause()
{
    if (m_session->playbackState() == sp::Session::PlaybackState::Paused)
    {
        play();
    }
    else
    {
        pause();
    }
}

void Player::pause()
{
    m_session->pause();
}

void Player::next()
{
    sp::Track track;
    // Try to get an available track from queue
    while (track.availability(m_session) != sp::Track::Availability::Available)
        track = m_queue->dequeue();

    if (track.isValid())
    {
        play(track);
    }
    else {
        pause();
        m_watcher->watch(sp::Track());
    }

    // Emit outside if because of end of track situations
    emit trackChanged();
}

}
<|endoftext|>


<commit_before>#include <uv.h>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>

#include "pm.h"
#include "constants.h"

HWND handle;
DWORD threadId;
HANDLE threadHandle;

HANDLE notifyEvent;

char *notify_msg;

bool isRunning = false;

DWORD WINAPI ListenerThread( LPVOID lpParam );

void NotifyAsync(uv_work_t* req);
void NotifyFinished(uv_work_t* req);

void NotifyAsync(uv_work_t* req)
{
    WaitForSingleObject(notifyEvent, INFINITE);
}

void NotifyFinished(uv_work_t* req)
{
    if (isRunning)
    {
        Notify(notify_msg);
        uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
    }
}

static long FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    if(message == WM_POWERBROADCAST)
    {
		// printf("%d\n", wParam);
		if (wParam == PBT_APMRESUMESUSPEND)
		{
			// printf("wake\n");
            notify_msg = (char *)WAKE_NOTIFY;
            SetEvent(notifyEvent);
		}

		if (wParam == PBT_APMRESUMEAUTOMATIC)
		{
			// printf("waking\n");
            // strcpy(notify_msg, "waking");
            // SetEvent(notifyEvent);
		}

		if (wParam == PBT_APMSUSPEND)
		{
			// printf("sleeping\n");
            notify_msg = (char *)SLEEP_NOTIFY;
            SetEvent(notifyEvent);
		}

		if (wParam == PBT_APMPOWERSTATUSCHANGE)
		{
			// printf("PBT_APMPOWERSTATUSCHANGE\n");
            // SetEvent(notifyEvent);
		}

        //Do something
        return TRUE;
    }
    else
        return DefWindowProc(hWnd, message, wParam, lParam);
}

DWORD WINAPI ListenerThread( LPVOID lpParam )
{

    const char *className = "ListnerThreadPmNotify";

    WNDCLASS wc = {0};

    // Set up and register window class
    wc.lpfnWndProc = (WNDPROC)WindowProc;
    wc.lpszClassName = className;
    RegisterClass(&wc);
    HWND hWin = CreateWindow(className, className, 0, 0, 0, 0, 0, NULL, NULL, NULL, 0);

    BOOL bRet;
    MSG msg;
    while( (bRet = GetMessage( &msg, hWin, 0, 0 )) != 0)
    {
        if (bRet == -1)
        {
            // handle the error and possibly exit
        }
        else
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return 0;
}

void Start()
{
    isRunning = true;
    threadHandle = CreateThread(
        NULL,                   // default security attributes
        0,                      // use default stack size
        ListenerThread,         // thread function name
        NULL,                   // argument to thread function
        0,                      // use default creation flags
        &threadId);

    uv_work_t* req = new uv_work_t();
    uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}

void Stop()
{
    isRunning = false;
    SetEvent(notifyEvent);

    // ExitThread(threadHandle);
}

void InitPM()
{
    notifyEvent = CreateEvent(NULL, false /* auto-reset event */, false /* non-signalled state */, "");
    Start();
}<commit_msg>Listener thread name contains ThreadId<commit_after>#include <uv.h>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>

#include "pm.h"
#include "constants.h"

#define MAX_THREAD_WINDOW_NAME 64

HWND handle;
DWORD threadId;
HANDLE threadHandle;

HANDLE notifyEvent;

char *notify_msg;

bool isRunning = false;

DWORD WINAPI ListenerThread( LPVOID lpParam );

void NotifyAsync(uv_work_t* req);
void NotifyFinished(uv_work_t* req);

void NotifyAsync(uv_work_t* req)
{
    WaitForSingleObject(notifyEvent, INFINITE);
}

void NotifyFinished(uv_work_t* req)
{
    if (isRunning)
    {
        Notify(notify_msg);
        uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
    }
}

static long FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    if(message == WM_POWERBROADCAST)
    {
		// printf("%d\n", wParam);
		if (wParam == PBT_APMRESUMESUSPEND)
		{
			// printf("wake\n");

            notify_msg = (char *)WAKE_NOTIFY;
            SetEvent(notifyEvent);
		}

		if (wParam == PBT_APMRESUMEAUTOMATIC)
		{
			// printf("waking\n");
            // strcpy(notify_msg, "waking");
            // SetEvent(notifyEvent);
		}

		if (wParam == PBT_APMSUSPEND)
		{
			// printf("sleeping\n");

            notify_msg = (char *)SLEEP_NOTIFY;
            SetEvent(notifyEvent);
		}

		if (wParam == PBT_APMPOWERSTATUSCHANGE)
		{
			// printf("PBT_APMPOWERSTATUSCHANGE\n");
            // SetEvent(notifyEvent);
		}

        //Do something
        return TRUE;
    }
    else
        return DefWindowProc(hWnd, message, wParam, lParam);
}

DWORD WINAPI ListenerThread( LPVOID lpParam )
{
    char className[MAX_THREAD_WINDOW_NAME];
    _snprintf(className, MAX_THREAD_WINDOW_NAME, "ListnerThreadPmNotify_%d", GetCurrentThreadId());

    WNDCLASS wc = {0};

    // Set up and register window class
    wc.lpfnWndProc = (WNDPROC)WindowProc;
    wc.lpszClassName = className;
    RegisterClass(&wc);
    HWND hWin = CreateWindow(className, className, 0, 0, 0, 0, 0, NULL, NULL, NULL, 0);

    BOOL bRet;
    MSG msg;
    while( (bRet = GetMessage( &msg, hWin, 0, 0 )) != 0)
    {
        if (bRet == -1)
        {
            // handle the error and possibly exit
        }
        else
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return 0;
}

void Start()
{
    isRunning = true;
    threadHandle = CreateThread(
        NULL,                   // default security attributes
        0,                      // use default stack size
        ListenerThread,         // thread function name
        NULL,                   // argument to thread function
        0,                      // use default creation flags
        &threadId);

    uv_work_t* req = new uv_work_t();
    uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}

void Stop()
{
    isRunning = false;
    SetEvent(notifyEvent);

    // ExitThread(threadHandle);
}

void InitPM()
{
    notifyEvent = CreateEvent(NULL, false /* auto-reset event */, false /* non-signalled state */, "");
    Start();
}<|endoftext|>


<commit_before>//===- ModuleDebugLineFragment.cpp -------------------------------*- C++-*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/DebugInfo/CodeView/ModuleDebugLineFragment.h"

#include "llvm/DebugInfo/CodeView/CodeViewError.h"
#include "llvm/DebugInfo/CodeView/ModuleDebugFileChecksumFragment.h"
#include "llvm/DebugInfo/CodeView/ModuleDebugFragmentRecord.h"
#include "llvm/DebugInfo/CodeView/StringTable.h"

using namespace llvm;
using namespace llvm::codeview;

Error LineColumnExtractor::extract(BinaryStreamRef Stream, uint32_t &Len,
                                   LineColumnEntry &Item,
                                   const LineFragmentHeader *Header) {
  using namespace codeview;
  const LineBlockFragmentHeader *BlockHeader;
  BinaryStreamReader Reader(Stream);
  if (auto EC = Reader.readObject(BlockHeader))
    return EC;
  bool HasColumn = Header->Flags & uint16_t(LF_HaveColumns);
  uint32_t LineInfoSize =
      BlockHeader->NumLines *
      (sizeof(LineNumberEntry) + (HasColumn ? sizeof(ColumnNumberEntry) : 0));
  if (BlockHeader->BlockSize < sizeof(LineBlockFragmentHeader))
    return make_error<CodeViewError>(cv_error_code::corrupt_record,
                                     "Invalid line block record size");
  uint32_t Size = BlockHeader->BlockSize - sizeof(LineBlockFragmentHeader);
  if (LineInfoSize > Size)
    return make_error<CodeViewError>(cv_error_code::corrupt_record,
                                     "Invalid line block record size");
  // The value recorded in BlockHeader->BlockSize includes the size of
  // LineBlockFragmentHeader.
  Len = BlockHeader->BlockSize;
  Item.NameIndex = BlockHeader->NameIndex;
  if (auto EC = Reader.readArray(Item.LineNumbers, BlockHeader->NumLines))
    return EC;
  if (HasColumn) {
    if (auto EC = Reader.readArray(Item.Columns, BlockHeader->NumLines))
      return EC;
  }
  return Error::success();
}

ModuleDebugLineFragmentRef::ModuleDebugLineFragmentRef()
    : ModuleDebugFragmentRef(ModuleDebugFragmentKind::Lines) {}

Error ModuleDebugLineFragmentRef::initialize(BinaryStreamReader Reader) {
  if (auto EC = Reader.readObject(Header))
    return EC;

  if (auto EC =
          Reader.readArray(LinesAndColumns, Reader.bytesRemaining(), Header))
    return EC;

  return Error::success();
}

bool ModuleDebugLineFragmentRef::hasColumnInfo() const {
  return !!(Header->Flags & LF_HaveColumns);
}

ModuleDebugLineFragment::ModuleDebugLineFragment(
    ModuleDebugFileChecksumFragment &Checksums, StringTable &Strings)
    : ModuleDebugFragment(ModuleDebugFragmentKind::Lines), Checksums(Checksums),
      Strings(Strings) {}

void ModuleDebugLineFragment::createBlock(StringRef FileName) {
  uint32_t Offset = Checksums.mapChecksumOffset(FileName);

  Blocks.emplace_back(Offset);
}

void ModuleDebugLineFragment::addLineInfo(uint32_t Offset,
                                          const LineInfo &Line) {
  Block &B = Blocks.back();
  LineNumberEntry LNE;
  LNE.Flags = Line.getRawData();
  LNE.Offset = Offset;
  B.Lines.push_back(LNE);
}

void ModuleDebugLineFragment::addLineAndColumnInfo(uint32_t Offset,
                                                   const LineInfo &Line,
                                                   uint32_t ColStart,
                                                   uint32_t ColEnd) {
  Block &B = Blocks.back();
  assert(B.Lines.size() == B.Columns.size());

  addLineInfo(Offset, Line);
  ColumnNumberEntry CNE;
  CNE.StartColumn = ColStart;
  CNE.EndColumn = ColEnd;
  B.Columns.push_back(CNE);
}

Error ModuleDebugLineFragment::commit(BinaryStreamWriter &Writer) {
  LineFragmentHeader Header;
  Header.CodeSize = CodeSize;
  Header.Flags = hasColumnInfo() ? LF_HaveColumns : 0;
  Header.RelocOffset = RelocOffset;
  Header.RelocSegment = RelocSegment;

  if (auto EC = Writer.writeObject(Header))
    return EC;

  for (const auto &B : Blocks) {
    LineBlockFragmentHeader BlockHeader;
    assert(B.Lines.size() == B.Columns.size() || B.Columns.empty());

    BlockHeader.NumLines = B.Lines.size();
    BlockHeader.BlockSize = sizeof(LineBlockFragmentHeader);
    BlockHeader.BlockSize += BlockHeader.NumLines * sizeof(LineNumberEntry);
    if (hasColumnInfo())
      BlockHeader.BlockSize += BlockHeader.NumLines * sizeof(ColumnNumberEntry);
    BlockHeader.NameIndex = B.ChecksumBufferOffset;
    if (auto EC = Writer.writeObject(BlockHeader))
      return EC;

    if (auto EC = Writer.writeArray(makeArrayRef(B.Lines)))
      return EC;

    if (hasColumnInfo()) {
      if (auto EC = Writer.writeArray(makeArrayRef(B.Columns)))
        return EC;
    }
  }
  return Error::success();
}

uint32_t ModuleDebugLineFragment::calculateSerializedLength() {
  uint32_t Size = sizeof(LineFragmentHeader);
  for (const auto &B : Blocks) {
    Size += sizeof(LineBlockFragmentHeader);
    Size += B.Lines.size() * sizeof(LineNumberEntry);
    if (hasColumnInfo())
      Size += B.Columns.size() * sizeof(ColumnNumberEntry);
  }
  return Size;
}

void ModuleDebugLineFragment::setRelocationAddress(uint16_t Segment,
                                                   uint16_t Offset) {
  RelocOffset = Offset;
  RelocSegment = Segment;
}

void ModuleDebugLineFragment::setCodeSize(uint32_t Size) { CodeSize = Size; }

void ModuleDebugLineFragment::setFlags(LineFlags Flags) { this->Flags = Flags; }

bool ModuleDebugLineFragment::hasColumnInfo() const {
  return Flags & LF_HaveColumns;
}
<commit_msg>[CodeView] Remove constructor initialization of a removed field.<commit_after>//===- ModuleDebugLineFragment.cpp -------------------------------*- C++-*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/DebugInfo/CodeView/ModuleDebugLineFragment.h"

#include "llvm/DebugInfo/CodeView/CodeViewError.h"
#include "llvm/DebugInfo/CodeView/ModuleDebugFileChecksumFragment.h"
#include "llvm/DebugInfo/CodeView/ModuleDebugFragmentRecord.h"
#include "llvm/DebugInfo/CodeView/StringTable.h"

using namespace llvm;
using namespace llvm::codeview;

Error LineColumnExtractor::extract(BinaryStreamRef Stream, uint32_t &Len,
                                   LineColumnEntry &Item,
                                   const LineFragmentHeader *Header) {
  using namespace codeview;
  const LineBlockFragmentHeader *BlockHeader;
  BinaryStreamReader Reader(Stream);
  if (auto EC = Reader.readObject(BlockHeader))
    return EC;
  bool HasColumn = Header->Flags & uint16_t(LF_HaveColumns);
  uint32_t LineInfoSize =
      BlockHeader->NumLines *
      (sizeof(LineNumberEntry) + (HasColumn ? sizeof(ColumnNumberEntry) : 0));
  if (BlockHeader->BlockSize < sizeof(LineBlockFragmentHeader))
    return make_error<CodeViewError>(cv_error_code::corrupt_record,
                                     "Invalid line block record size");
  uint32_t Size = BlockHeader->BlockSize - sizeof(LineBlockFragmentHeader);
  if (LineInfoSize > Size)
    return make_error<CodeViewError>(cv_error_code::corrupt_record,
                                     "Invalid line block record size");
  // The value recorded in BlockHeader->BlockSize includes the size of
  // LineBlockFragmentHeader.
  Len = BlockHeader->BlockSize;
  Item.NameIndex = BlockHeader->NameIndex;
  if (auto EC = Reader.readArray(Item.LineNumbers, BlockHeader->NumLines))
    return EC;
  if (HasColumn) {
    if (auto EC = Reader.readArray(Item.Columns, BlockHeader->NumLines))
      return EC;
  }
  return Error::success();
}

ModuleDebugLineFragmentRef::ModuleDebugLineFragmentRef()
    : ModuleDebugFragmentRef(ModuleDebugFragmentKind::Lines) {}

Error ModuleDebugLineFragmentRef::initialize(BinaryStreamReader Reader) {
  if (auto EC = Reader.readObject(Header))
    return EC;

  if (auto EC =
          Reader.readArray(LinesAndColumns, Reader.bytesRemaining(), Header))
    return EC;

  return Error::success();
}

bool ModuleDebugLineFragmentRef::hasColumnInfo() const {
  return !!(Header->Flags & LF_HaveColumns);
}

ModuleDebugLineFragment::ModuleDebugLineFragment(
    ModuleDebugFileChecksumFragment &Checksums, StringTable &Strings)
    : ModuleDebugFragment(ModuleDebugFragmentKind::Lines),
      Checksums(Checksums) {}

void ModuleDebugLineFragment::createBlock(StringRef FileName) {
  uint32_t Offset = Checksums.mapChecksumOffset(FileName);

  Blocks.emplace_back(Offset);
}

void ModuleDebugLineFragment::addLineInfo(uint32_t Offset,
                                          const LineInfo &Line) {
  Block &B = Blocks.back();
  LineNumberEntry LNE;
  LNE.Flags = Line.getRawData();
  LNE.Offset = Offset;
  B.Lines.push_back(LNE);
}

void ModuleDebugLineFragment::addLineAndColumnInfo(uint32_t Offset,
                                                   const LineInfo &Line,
                                                   uint32_t ColStart,
                                                   uint32_t ColEnd) {
  Block &B = Blocks.back();
  assert(B.Lines.size() == B.Columns.size());

  addLineInfo(Offset, Line);
  ColumnNumberEntry CNE;
  CNE.StartColumn = ColStart;
  CNE.EndColumn = ColEnd;
  B.Columns.push_back(CNE);
}

Error ModuleDebugLineFragment::commit(BinaryStreamWriter &Writer) {
  LineFragmentHeader Header;
  Header.CodeSize = CodeSize;
  Header.Flags = hasColumnInfo() ? LF_HaveColumns : 0;
  Header.RelocOffset = RelocOffset;
  Header.RelocSegment = RelocSegment;

  if (auto EC = Writer.writeObject(Header))
    return EC;

  for (const auto &B : Blocks) {
    LineBlockFragmentHeader BlockHeader;
    assert(B.Lines.size() == B.Columns.size() || B.Columns.empty());

    BlockHeader.NumLines = B.Lines.size();
    BlockHeader.BlockSize = sizeof(LineBlockFragmentHeader);
    BlockHeader.BlockSize += BlockHeader.NumLines * sizeof(LineNumberEntry);
    if (hasColumnInfo())
      BlockHeader.BlockSize += BlockHeader.NumLines * sizeof(ColumnNumberEntry);
    BlockHeader.NameIndex = B.ChecksumBufferOffset;
    if (auto EC = Writer.writeObject(BlockHeader))
      return EC;

    if (auto EC = Writer.writeArray(makeArrayRef(B.Lines)))
      return EC;

    if (hasColumnInfo()) {
      if (auto EC = Writer.writeArray(makeArrayRef(B.Columns)))
        return EC;
    }
  }
  return Error::success();
}

uint32_t ModuleDebugLineFragment::calculateSerializedLength() {
  uint32_t Size = sizeof(LineFragmentHeader);
  for (const auto &B : Blocks) {
    Size += sizeof(LineBlockFragmentHeader);
    Size += B.Lines.size() * sizeof(LineNumberEntry);
    if (hasColumnInfo())
      Size += B.Columns.size() * sizeof(ColumnNumberEntry);
  }
  return Size;
}

void ModuleDebugLineFragment::setRelocationAddress(uint16_t Segment,
                                                   uint16_t Offset) {
  RelocOffset = Offset;
  RelocSegment = Segment;
}

void ModuleDebugLineFragment::setCodeSize(uint32_t Size) { CodeSize = Size; }

void ModuleDebugLineFragment::setFlags(LineFlags Flags) { this->Flags = Flags; }

bool ModuleDebugLineFragment::hasColumnInfo() const {
  return Flags & LF_HaveColumns;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: FopEvtDisp.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: tra $ $Date: 2001-06-28 11:15:44 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _FOPEVENTDISPATCHER_HXX_
#define _FOPEVENTDISPATCHER_HXX_

#ifndef _COM_SUN_STAR_LANG_EVENTOBJECT_HPP_
#include <com/sun/star/lang/EventObject.hpp>
#endif

//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------
class CFOPEventDispatcher
{
public:

    // dispatches a FilePickerEvent to wherever
    virtual void SAL_CALL helpRequested( ::com::sun::star::lang::EventObject aEvent ) const = 0;
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.178); FILE MERGED 2005/09/05 17:13:42 rt 1.1.178.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: FopEvtDisp.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:49:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _FOPEVENTDISPATCHER_HXX_
#define _FOPEVENTDISPATCHER_HXX_

#ifndef _COM_SUN_STAR_LANG_EVENTOBJECT_HPP_
#include <com/sun/star/lang/EventObject.hpp>
#endif

//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------
class CFOPEventDispatcher
{
public:

    // dispatches a FilePickerEvent to wherever
    virtual void SAL_CALL helpRequested( ::com::sun::star::lang::EventObject aEvent ) const = 0;
};

#endif
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2018 The Apollo 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.
 *****************************************************************************/

/**
 * @file
 **/

#include <string>
#include <vector>

#include "modules/planning/scenarios/traffic_light/unprotected_right_turn/stage_creep.h"

#include "modules/perception/proto/perception_obstacle.pb.h"
#include "modules/perception/proto/traffic_light_detection.pb.h"

#include "cyber/common/log.h"
#include "modules/common/time/time.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/map/pnc_map/path.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_context.h"
#include "modules/planning/common/util/util.h"
#include "modules/planning/scenarios/util/util.h"
#include "modules/planning/tasks/deciders/creep_decider/creep_decider.h"

namespace apollo {
namespace planning {
namespace scenario {
namespace traffic_light {

using apollo::common::TrajectoryPoint;
using apollo::common::time::Clock;
using apollo::hdmap::PathOverlap;
using apollo::perception::TrafficLight;

Stage::StageStatus TrafficLightUnprotectedRightTurnStageCreep::Process(
    const TrajectoryPoint& planning_init_point, Frame* frame) {
  ADEBUG << "stage: Creep";
  CHECK_NOTNULL(frame);

  scenario_config_.CopyFrom(GetContext()->scenario_config);

  if (!config_.enabled()) {
    return FinishStage();
  }

  bool plan_ok = ExecuteTaskOnReferenceLine(planning_init_point, frame);
  if (!plan_ok) {
    AERROR << "TrafficLightUnprotectedRightTurnStageCreep planning error";
  }

  if (GetContext()->current_traffic_light_overlap_ids.size() == 0) {
    return FinishScenario();
  }

  const auto& reference_line_info = frame->reference_line_info().front();

  PathOverlap* traffic_light = nullptr;
  bool traffic_light_all_green = true;
  for (const auto& traffic_light_overlap_id :
       GetContext()->current_traffic_light_overlap_ids) {
    // get overlap along reference line
    PathOverlap* current_traffic_light_overlap =
        scenario::util::GetOverlapOnReferenceLine(reference_line_info,
                                                  traffic_light_overlap_id,
                                                  ReferenceLineInfo::SIGNAL);
    if (!current_traffic_light_overlap) {
      continue;
    }

    // set right_of_way_status
    reference_line_info.SetJunctionRightOfWay(
        current_traffic_light_overlap->start_s, false);

    auto signal_color = frame->GetSignal(traffic_light_overlap_id).color();
    ADEBUG << "traffic_light_overlap_id[" << traffic_light_overlap_id
           << "] start_s[" << current_traffic_light_overlap->start_s
           << "] color[" << signal_color << "]";

    // check on traffic light color
    if (signal_color != TrafficLight::GREEN) {
      traffic_light_all_green = false;
      break;
    }

    traffic_light = current_traffic_light_overlap;
  }

  if (traffic_light_all_green || traffic_light == nullptr) {
    return FinishStage();
  }

  // creep
  const double wait_time =
      Clock::NowInSeconds() - GetContext()->creep_start_time;
  const double timeout_sec = scenario_config_.creep_timeout_sec();
  auto* task = dynamic_cast<CreepDecider*>(FindTask(TaskConfig::CREEP_DECIDER));
  if (task &&
      task->CheckCreepDone(*frame, reference_line_info, traffic_light->end_s,
                           wait_time, timeout_sec)) {
    return FinishStage();
  }

  // set param for PROCEED_WITH_CAUTION_SPEED
  // dynamic_cast<CreepDecider*>(FindTask(TaskConfig::CREEP_DECIDER))
  //    ->SetProceedWithCautionSpeedParam(*frame, reference_line_info,
  //                                      traffic_light.end_s);

  plan_ok = ExecuteTaskOnReferenceLine(planning_init_point, frame);
  if (!plan_ok) {
    AERROR << "TrafficLightUnprotectedRightTurnStageCreep planning error";
  }

  return Stage::RUNNING;
}

Stage::StageStatus
TrafficLightUnprotectedRightTurnStageCreep::FinishScenario() {
  PlanningContext::Instance()->mutable_planning_status()->clear_traffic_light();

  next_stage_ = ScenarioConfig::NO_STAGE;
  return Stage::FINISHED;
}

Stage::StageStatus TrafficLightUnprotectedRightTurnStageCreep::FinishStage() {
  next_stage_ =
      ScenarioConfig::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN_INTERSECTION_CRUISE;
  return Stage::FINISHED;
}

}  // namespace traffic_light
}  // namespace scenario
}  // namespace planning
}  // namespace apollo
<commit_msg>planning: fix CREEP stage<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo 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.
 *****************************************************************************/

/**
 * @file
 **/

#include <string>
#include <vector>

#include "modules/planning/scenarios/traffic_light/unprotected_right_turn/stage_creep.h"

#include "modules/perception/proto/perception_obstacle.pb.h"
#include "modules/perception/proto/traffic_light_detection.pb.h"

#include "cyber/common/log.h"
#include "modules/common/time/time.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/map/pnc_map/path.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_context.h"
#include "modules/planning/common/speed_profile_generator.h"
#include "modules/planning/common/util/util.h"
#include "modules/planning/scenarios/util/util.h"
#include "modules/planning/tasks/deciders/creep_decider/creep_decider.h"

namespace apollo {
namespace planning {
namespace scenario {
namespace traffic_light {

using apollo::common::TrajectoryPoint;
using apollo::common::time::Clock;
using apollo::hdmap::PathOverlap;
using apollo::perception::TrafficLight;

Stage::StageStatus TrafficLightUnprotectedRightTurnStageCreep::Process(
    const TrajectoryPoint& planning_init_point, Frame* frame) {
  ADEBUG << "stage: Creep";
  CHECK_NOTNULL(frame);

  scenario_config_.CopyFrom(GetContext()->scenario_config);

  if (!config_.enabled()) {
    return FinishStage();
  }

  bool plan_ok = ExecuteTaskOnReferenceLine(planning_init_point, frame);
  if (!plan_ok) {
    AERROR << "TrafficLightUnprotectedRightTurnStageCreep planning error";
  }

  if (GetContext()->current_traffic_light_overlap_ids.size() == 0) {
    return FinishScenario();
  }

  const auto& reference_line_info = frame->reference_line_info().front();

  PathOverlap* traffic_light = nullptr;
  bool traffic_light_all_green = true;
  for (const auto& traffic_light_overlap_id :
       GetContext()->current_traffic_light_overlap_ids) {
    // get overlap along reference line
    PathOverlap* current_traffic_light_overlap =
        scenario::util::GetOverlapOnReferenceLine(reference_line_info,
                                                  traffic_light_overlap_id,
                                                  ReferenceLineInfo::SIGNAL);
    if (!current_traffic_light_overlap) {
      continue;
    }

    // set right_of_way_status
    reference_line_info.SetJunctionRightOfWay(
        current_traffic_light_overlap->start_s, false);

    auto signal_color = frame->GetSignal(traffic_light_overlap_id).color();
    ADEBUG << "traffic_light_overlap_id[" << traffic_light_overlap_id
           << "] start_s[" << current_traffic_light_overlap->start_s
           << "] color[" << signal_color << "]";

    // check on traffic light color
    if (signal_color != TrafficLight::GREEN) {
      traffic_light_all_green = false;
      break;
    }

    traffic_light = current_traffic_light_overlap;
  }

  if (traffic_light_all_green || traffic_light == nullptr) {
    return FinishStage();
  }

  // creep
  const double wait_time =
      Clock::NowInSeconds() - GetContext()->creep_start_time;
  const double timeout_sec = scenario_config_.creep_timeout_sec();
  auto* task = dynamic_cast<CreepDecider*>(FindTask(TaskConfig::CREEP_DECIDER));
  if (task == nullptr) {
    AERROR << "task is nullptr";
    return FinishStage();
  }

  double creep_stop_s = traffic_light->end_s +
      task->FindCreepDistance(*frame, reference_line_info);
  const double distance =
      creep_stop_s - reference_line_info.AdcSlBoundary().end_s();
  if (distance <= 0.0) {
    auto& rfl_info = frame->mutable_reference_line_info()->front();
    *(rfl_info.mutable_speed_data()) =
        SpeedProfileGenerator::GenerateFixedDistanceCreepProfile(0.0, 0);
  }

  if (task->CheckCreepDone(*frame, reference_line_info, traffic_light->end_s,
                           wait_time, timeout_sec)) {
    return FinishStage();
  }

  return Stage::RUNNING;
}

Stage::StageStatus
TrafficLightUnprotectedRightTurnStageCreep::FinishScenario() {
  PlanningContext::Instance()->mutable_planning_status()->clear_traffic_light();

  next_stage_ = ScenarioConfig::NO_STAGE;
  return Stage::FINISHED;
}

Stage::StageStatus TrafficLightUnprotectedRightTurnStageCreep::FinishStage() {
  next_stage_ =
      ScenarioConfig::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN_INTERSECTION_CRUISE;
  return Stage::FINISHED;
}

}  // namespace traffic_light
}  // namespace scenario
}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before><commit_msg>Revert "vcl: increment ref in OpenGLSalGraphicsImpl::AcquireContext"<commit_after><|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    CannySegmentationLevelSetImageFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// Software Guide : BeginLatex
//
// \index{itk::CannySegmentationLevelSetImageFilter}
//
// The \doxygen{CannySegmentationLevelSetImageFilter} defines a speed term that
// minimizes distance to Canny edges in an image.  The initial level-set
// model moves through a gradient advection field until it locks onto those edges.
// This filter is more suitable for refining existing segmentations than as a
// region-growing algorithm.
//
// The two terms defined for the \doxygen{CannySegmentationLevelSetImageFilter}
// are the advection term and the propagation term from
// equation~\ref{eqn:LevelSetEquation}.  The advection term is constructed by
// minimizing the squared distance transform from the Canny edges,
//
// \begin{equation}
// \label{eqn:CannySegmentationLevelSetImageFilterAdvection}
// \mbox{min} \int D^2 \Rightarrow D \nabla D
// \end{equation},
//
// where the distance transform $D$ is calculated using a
// \doxygen{DanielssonDistanceMapImageFilter} applied to the output of the
// \doxygen{CannyEdgeDetectionImageFilter}.
//
// For cases where you want to allow for some surface expansion, you may set a
// non-zero value for the propagation term.  The propagation term is simply
// $D$.  As with all ITK level-set segmentation filters, the curvature term
// controls the smoothness of the surface.
//
// \doxygen{CannySegmentationLevelSetImageFilter} expects two inputs.  The
// first is an initial level set in the form of an \doxygen{Image}. The second
// input is the feature image $g$ from which propagation and advection terms
// are calculated.  It is generally a good idea to do some preprocessing of the
// feature image to remove noise.
//
// The following example illustrates the use of the
// \doxygen{CannySegmentationLevelSetImageFilter}.
// Figure~\ref{fig:CannySegmentationLevelSetImageFilterDiagram} shows how the
// image processing pipeline is constructed.  We read two images: the image to
// segment and the image that contains the initial implicit surface.  The goal
// is to refine the initial model from the second input and not to grow a new
// segmentation from seed points.. The \code{feature} image is preprocessed
// with a few iterations of an anisotropic diffusion filter.
//
// \begin{figure} \center
// \includegraphics[width=\textwidth]{CannySegmentationLevelSetImageFilterCollaborationDiagram1.eps}
// \itkcaption[CannySegmentationLevelSetImageFilter collaboration
// diagram]{Collaboration diagram for the CannySegmentationLevelSetImageFilter
// applied to a segmentation task.}
// \label{fig:CannySegmentationLevelSetImageFilterDiagram}
// \end{figure}
//
// Let's start by including the appropriate header file.
//
// Software Guide : EndLatex

#include "itkImage.h"
// Software Guide : BeginCodeSnippet
#include "itkCannySegmentationLevelSetImageFilter.h"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
// Software Guide : EndCodeSnippet
#include "itkFastMarchingImageFilter.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkZeroCrossingImageFilter.h"

int main( int argc, char *argv[] )
{

  if( argc < 9 )
    {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0];
    std::cerr << " InputImage  InitialModel OutputImage";
    std::cerr << " CannyThreshold ";
    std::cerr << " CannyVariance ";
    std::cerr << " AdvectionWeight";
    std::cerr << " InitialModelIsovalue";
    std::cerr << " MaximumIterations" << std::endl;
    return 1;
    }

  //  Software Guide : BeginLatex
  //
  //  We declare the image type using a pixel type and a particular
  //  dimension. In this case we will use 2D \code{float} images.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef   float           InternalPixelType;
  const     unsigned int    Dimension = 2;

  typedef itk::Image< InternalPixelType, Dimension >  InternalImageType;
  // Software Guide : EndCodeSnippet

  typedef unsigned char OutputPixelType;
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
  typedef itk::BinaryThresholdImageFilter<
                        InternalImageType,
                        OutputImageType    >    ThresholdingFilterType;

  ThresholdingFilterType::Pointer thresholder = ThresholdingFilterType::New();

  thresholder->SetUpperThreshold( 10.0 );
  thresholder->SetLowerThreshold( 0.0 );

  thresholder->SetOutsideValue(  0  );
  thresholder->SetInsideValue(  255 );

  typedef  itk::ImageFileReader< InternalImageType > ReaderType;
  typedef  itk::ImageFileWriter<  OutputImageType  > WriterType;

  ReaderType::Pointer reader1 = ReaderType::New();
  ReaderType::Pointer reader2 = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader1->SetFileName( argv[1] );
  reader2->SetFileName( argv[2] );
  writer->SetFileName(  argv[3] );

  //  Software Guide : BeginLatex
  //
  //  The input image will be processed with a few iterations of
  //  feature-preserving diffusion.  We create a filter and set the parameters.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::GradientAnisotropicDiffusionImageFilter< InternalImageType,
    InternalImageType> DiffusionFilterType;
  DiffusionFilterType::Pointer diffusion = DiffusionFilterType::New();
  diffusion->SetNumberOfIterations(5);
  diffusion->SetTimeStep(0.20);
  diffusion->SetConductanceParameter(1.0);
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The following lines define and instantiate a \doxygen{CannySegmentationLevelSetImageFilter}.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef  itk::CannySegmentationLevelSetImageFilter<
                              InternalImageType,
                              InternalImageType >    CannySegmentationLevelSetImageFilterType;

  CannySegmentationLevelSetImageFilterType::Pointer cannySegmentation =
                                     CannySegmentationLevelSetImageFilterType::New();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // As with the other ITK level-set segmentation filters, the terms of the
  // \code{CannySegmentationLevelSetImageFilter} level-set equation can be
  // weighted by scalars.  For this application we will modify the relative
  // weight of the advection term.  The propagation and curvature term weights
  // are set to their defaults of $0$ and $1$, respectively.
  //
  //  \index{itk::CannySegmentationLevelSetImageFilter!SetAdvectionScaling()}
  //  \index{itk::SegmentationLevelSetImageFilter!SetAdvectionScaling()}
  //
  //  Software Guide : EndLatex

  //  Software Guide : BeginCodeSnippet
  cannySegmentation->SetAdvectionScaling( ::atof(argv[6]) );
  cannySegmentation->SetCurvatureScaling( 1.0 );
  cannySegmentation->SetPropagationScaling( 0.0 );
  //  Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The maximum number of iterations is set from the command line.  It may
  //  not be desirable in some applications to run the filter to
  //  convergence.  Only a few iterations may be required.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  cannySegmentation->SetMaximumRMSError( 0.01 );
  cannySegmentation->SetMaximumIterations( ::atoi(argv[8]) );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  There are two parameters in the
  //  \doxygen{CannySegmentationLevelSetImageFilter} to control the behavior of
  //  the Canny edge detection.  The {\it variance} parameter controls the
  //  amount of Gaussian smoothing on the input image.  The {\it threshold}
  //  parameter indicates the lowest allowed value in the output image.
  //  Thresholding is used to suppress Canny edges whose gradient magnitudes
  //  fall below a certain value.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  cannySegmentation->SetThreshold( ::atof(argv[4]) );
  cannySegmentation->SetVariance(  ::atof(argv[5]) );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Finally, it is very important to specify the isovalue of the surface in
  // the initial model input image. In a binary image, for example, the
  // isosurface is found midway between the foreground and background values.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  cannySegmentation->SetIsoSurfaceValue( ::atof(argv[7]) );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The filters are now connected in a pipeline indicated in
  //  Figure~\ref{fig:CannyLevelSetSegmentationCollaborationDiagram}.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  diffusion->SetInput( reader1->GetOutput() );
  cannySegmentation->SetInput( reader2->GetOutput() );
  cannySegmentation->SetFeatureImage( diffusion->GetOutput() );
  thresholder->SetInput( cannySegmentation->GetOutput() );
  writer->SetInput( thresholder->GetOutput() );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Invoking the \code{Update()} method on the writer triggers the
  //  execution of the pipeline.  As usual, the call is placed in a
  //  \code{try/catch} block to handle any exceptions that may be thrown.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  try
    {
      writer->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception caught !" << std::endl;
    std::cerr << excep << std::endl;
    }
  // Software Guide : EndCodeSnippet

  // Print out some useful information
  std::cout << std::endl;
  std::cout << "Max. no. iterations: " << cannySegmentation->GetMaximumIterations() << std::endl;
  std::cout << "Max. RMS error: " << cannySegmentation->GetMaximumRMSError() << std::endl;
  std::cout << std::endl;
  std::cout << "No. elpased iterations: " << cannySegmentation->GetElapsedIterations() << std::endl;
  std::cout << "RMS change: " << cannySegmentation->GetRMSChange() << std::endl;

  //  Software Guide : BeginLatex
  //
  //  We can use this filter to make some subtle refinements to the ventricle
  //  segmentation from the previous example of
  //  \doxygen{ThresholdSegmentationLevelSetImageFilter}.  The application was
  //  run using \code{Insight/Examples/Data/BrainProtonDensitySlice.png} and
  //  \code{Insight/Examples/Data/VentricleModel.png} as inputs, a
  //  \code{threshold} of $7.0$, \code{variance} of $0.1$, \code{advection
  //  weight} of $10.0$, and an initial isosurface value of $127.5$.  One case
  //  was run for $15$ iterations and the second was run to convergence.
  //  Compare the results in the two rightmost images of
  //  figure~\ref{CannySegmentationLevelSetImageFilter} with the ventricle
  //  segmentation from figure~\ref{ThresholdSegmentationLevelSetImageFilter}
  //  shown in the middle.  Jagged edges are straightened and the small spur at
  //  the upper right-hand side of the mask has been removed.
  //
  //  \begin{figure}
  //  \includegraphics[width=0.24\textwidth]{BrainProtonDensitySlice.eps}
  //  \includegraphics[width=0.24\textwidth]{ThresholdSegmentationLevelSetImageFilterVentricle.eps}
  //  \includegraphics[width=0.24\textwidth]{CannySegmentationLevelSetImageFilterVentricle1.eps}
  //  \includegraphics[width=0.24\textwidth]{CannySegmentationLevelSetImageFilterVentricle2.eps}
  //  \itkcaption[Segmentation results of CannyLevelSetImageFilter]{Results of
  //  applying \code{CannySegmentationLevelSetImageFilter} to a prior ventricle
  //  segmentation.  Shown from left to right are the original image, the
  //  prior segmentation of the ventricle from
  //  figure~\ref{ThresholdSegmentationLevelSetImageFilter}, $15$ iterations of
  //  the \code{CannySegmentationLevelSetImageFilter}, and the
  //  \code{CannySegmentationLevelSetImageFilter} run to convergence.}
  //  \label{fig:CannySegmentationLevelSetImageFilter}
  //  \end{figure}
  //
  //  The free parameters of this filter can be adjusted to achieve a wide
  //  range of shape variations from the original model.  Finding the right
  //  parameters for your particular application is usually a process of trial
  //  and error.  As with most ITK level-set segmentation filters, examining
  //  the propagation (speed) and advection images can help the process of
  //  tuning parameters.  These images are available using \code{Set/Get}
  //  methods from the filter after it has been updated.
  //
  //  Software Guide : EndLatex

  return 0;
}
<commit_msg>DOC: Figures reformated for the SoftwareGuide. Code reformated to avoid      overriding margins. References to figure labels fixed.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    CannySegmentationLevelSetImageFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// Software Guide : BeginLatex
//
// \index{itk::CannySegmentationLevelSetImageFilter}
//
// The \doxygen{CannySegmentationLevelSetImageFilter} defines a speed term that
// minimizes distance to Canny edges in an image.  The initial level-set
// model moves through a gradient advection field until it locks onto those edges.
// This filter is more suitable for refining existing segmentations than as a
// region-growing algorithm.
//
// The two terms defined for the \doxygen{CannySegmentationLevelSetImageFilter}
// are the advection term and the propagation term from
// equation~\ref{eqn:LevelSetEquation}.  The advection term is constructed by
// minimizing the squared distance transform from the Canny edges,
//
// \begin{equation}
// \label{eqn:CannySegmentationLevelSetImageFilterAdvection}
// \mbox{min} \int D^2 \Rightarrow D \nabla D
// \end{equation}
//
// where the distance transform $D$ is calculated using a
// \doxygen{DanielssonDistanceMapImageFilter} applied to the output of the
// \doxygen{CannyEdgeDetectionImageFilter}.
//
// For cases where you want to allow for some surface expansion, you may set a
// non-zero value for the propagation term.  The propagation term is simply
// $D$.  As with all ITK level-set segmentation filters, the curvature term
// controls the smoothness of the surface.
//
// \doxygen{CannySegmentationLevelSetImageFilter} expects two inputs.  The
// first is an initial level set in the form of an \doxygen{Image}. The second
// input is the feature image $g$ from which propagation and advection terms
// are calculated.  It is generally a good idea to do some preprocessing of the
// feature image to remove noise.
//
// Figure~\ref{fig:CannySegmentationLevelSetImageFilterDiagram} shows how the
// image processing pipeline is constructed.  We read two images: the image to
// segment and the image that contains the initial implicit surface.  The goal
// is to refine the initial model from the second input and not to grow a new
// segmentation from seed points.. The \code{feature} image is preprocessed
// with a few iterations of an anisotropic diffusion filter.
//
// \begin{figure} \center
// \includegraphics[width=0.9\textwidth]{CannySegmentationLevelSetImageFilterCollaborationDiagram1.eps}
// \itkcaption[CannySegmentationLevelSetImageFilter collaboration
// diagram]{Collaboration diagram for the CannySegmentationLevelSetImageFilter
// applied to a segmentation task.}
// \label{fig:CannySegmentationLevelSetImageFilterDiagram}
// \end{figure}
//
// Let's start by including the appropriate header file.
//
// Software Guide : EndLatex

#include "itkImage.h"
// Software Guide : BeginCodeSnippet
#include "itkCannySegmentationLevelSetImageFilter.h"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
// Software Guide : EndCodeSnippet
#include "itkFastMarchingImageFilter.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkZeroCrossingImageFilter.h"

int main( int argc, char *argv[] )
{

  if( argc < 9 )
    {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0];
    std::cerr << " InputImage  InitialModel OutputImage";
    std::cerr << " CannyThreshold ";
    std::cerr << " CannyVariance ";
    std::cerr << " AdvectionWeight";
    std::cerr << " InitialModelIsovalue";
    std::cerr << " MaximumIterations" << std::endl;
    return 1;
    }

  //  Software Guide : BeginLatex
  //
  //  We declare the image type using a pixel type and a particular
  //  dimension. In this case we will use 2D \code{float} images.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef   float           InternalPixelType;
  const     unsigned int    Dimension = 2;

  typedef itk::Image< InternalPixelType, Dimension >  InternalImageType;
  // Software Guide : EndCodeSnippet

  typedef unsigned char OutputPixelType;
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
  typedef itk::BinaryThresholdImageFilter<
                        InternalImageType,
                        OutputImageType    >    ThresholdingFilterType;

  ThresholdingFilterType::Pointer thresholder = ThresholdingFilterType::New();

  thresholder->SetUpperThreshold( 10.0 );
  thresholder->SetLowerThreshold( 0.0 );

  thresholder->SetOutsideValue(  0  );
  thresholder->SetInsideValue(  255 );

  typedef  itk::ImageFileReader< InternalImageType > ReaderType;
  typedef  itk::ImageFileWriter<  OutputImageType  > WriterType;

  ReaderType::Pointer reader1 = ReaderType::New();
  ReaderType::Pointer reader2 = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader1->SetFileName( argv[1] );
  reader2->SetFileName( argv[2] );
  writer->SetFileName(  argv[3] );

  //  Software Guide : BeginLatex
  //
  //  The input image will be processed with a few iterations of
  //  feature-preserving diffusion.  We create a filter and set the parameters.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::GradientAnisotropicDiffusionImageFilter< InternalImageType,
    InternalImageType> DiffusionFilterType;
  DiffusionFilterType::Pointer diffusion = DiffusionFilterType::New();
  diffusion->SetNumberOfIterations(5);
  diffusion->SetTimeStep(0.20);
  diffusion->SetConductanceParameter(1.0);
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The following lines define and instantiate a \doxygen{CannySegmentationLevelSetImageFilter}.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef  itk::CannySegmentationLevelSetImageFilter<
                              InternalImageType,
                              InternalImageType >
                                CannySegmentationLevelSetImageFilterType;

  CannySegmentationLevelSetImageFilterType::Pointer cannySegmentation =
                                CannySegmentationLevelSetImageFilterType::New();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // As with the other ITK level-set segmentation filters, the terms of the
  // \doxygen{CannySegmentationLevelSetImageFilter} level-set equation can be
  // weighted by scalars.  For this application we will modify the relative
  // weight of the advection term.  The propagation and curvature term weights
  // are set to their defaults of $0$ and $1$, respectively.
  //
  //  \index{itk::CannySegmentationLevelSetImageFilter!SetAdvectionScaling()}
  //  \index{itk::SegmentationLevelSetImageFilter!SetAdvectionScaling()}
  //
  //  Software Guide : EndLatex

  //  Software Guide : BeginCodeSnippet
  cannySegmentation->SetAdvectionScaling( ::atof(argv[6]) );
  cannySegmentation->SetCurvatureScaling( 1.0 );
  cannySegmentation->SetPropagationScaling( 0.0 );
  //  Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The maximum number of iterations is set from the command line.  It may
  //  not be desirable in some applications to run the filter to
  //  convergence.  Only a few iterations may be required.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  cannySegmentation->SetMaximumRMSError( 0.01 );
  cannySegmentation->SetMaximumIterations( ::atoi(argv[8]) );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  There are two parameters in the
  //  \doxygen{CannySegmentationLevelSetImageFilter} to control the behavior of
  //  the Canny edge detection.  The {\it variance} parameter controls the
  //  amount of Gaussian smoothing on the input image.  The {\it threshold}
  //  parameter indicates the lowest allowed value in the output image.
  //  Thresholding is used to suppress Canny edges whose gradient magnitudes
  //  fall below a certain value.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  cannySegmentation->SetThreshold( ::atof(argv[4]) );
  cannySegmentation->SetVariance(  ::atof(argv[5]) );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Finally, it is very important to specify the isovalue of the surface in
  // the initial model input image. In a binary image, for example, the
  // isosurface is found midway between the foreground and background values.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  cannySegmentation->SetIsoSurfaceValue( ::atof(argv[7]) );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The filters are now connected in a pipeline indicated in
  //  Figure~\ref{fig:CannySegmentationLevelSetImageFilterDiagram}.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  diffusion->SetInput( reader1->GetOutput() );
  cannySegmentation->SetInput( reader2->GetOutput() );
  cannySegmentation->SetFeatureImage( diffusion->GetOutput() );
  thresholder->SetInput( cannySegmentation->GetOutput() );
  writer->SetInput( thresholder->GetOutput() );
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Invoking the \code{Update()} method on the writer triggers the
  //  execution of the pipeline.  As usual, the call is placed in a
  //  \code{try/catch} block to handle any exceptions that may be thrown.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  try
    {
      writer->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception caught !" << std::endl;
    std::cerr << excep << std::endl;
    }
  // Software Guide : EndCodeSnippet

  // Print out some useful information
  std::cout << std::endl;
  std::cout << "Max. no. iterations: " << cannySegmentation->GetMaximumIterations() << std::endl;
  std::cout << "Max. RMS error: " << cannySegmentation->GetMaximumRMSError() << std::endl;
  std::cout << std::endl;
  std::cout << "No. elpased iterations: " << cannySegmentation->GetElapsedIterations() << std::endl;
  std::cout << "RMS change: " << cannySegmentation->GetRMSChange() << std::endl;

  //  Software Guide : BeginLatex
  //
  //  We can use this filter to make some subtle refinements to the ventricle
  //  segmentation from the previous example of
  //  \doxygen{ThresholdSegmentationLevelSetImageFilter}.  The application was
  //  run using \code{Insight/Examples/Data/BrainProtonDensitySlice.png} and
  //  \code{Insight/Examples/Data/VentricleModel.png} as inputs, a
  //  \code{threshold} of $7.0$, \code{variance} of $0.1$, \code{advection
  //  weight} of $10.0$, and an initial isosurface value of $127.5$.  One case
  //  was run for $15$ iterations and the second was run to convergence.
  //  Compare the results in the two rightmost images of
  //  Figure~\ref{fig:CannySegmentationLevelSetImageFilter} with the ventricle
  //  segmentation from Figure~\ref{fig:ThresholdSegmentationLevelSetImageFilter}
  //  shown in the middle.  Jagged edges are straightened and the small spur at
  //  the upper right-hand side of the mask has been removed.
  //
  //  \begin{figure}
  //  \includegraphics[width=0.24\textwidth]{BrainProtonDensitySlice.eps}
  //  \includegraphics[width=0.24\textwidth]{ThresholdSegmentationLevelSetImageFilterVentricle.eps}
  //  \includegraphics[width=0.24\textwidth]{CannySegmentationLevelSetImageFilterVentricle1.eps}
  //  \includegraphics[width=0.24\textwidth]{CannySegmentationLevelSetImageFilterVentricle2.eps}
  //  \itkcaption[Segmentation results of CannyLevelSetImageFilter]{Results of
  //  applying \code{CannySegmentationLevelSetImageFilter} to a prior ventricle
  //  segmentation.  Shown from left to right are the original image, the
  //  prior segmentation of the ventricle from
  //  figure~\ref{ThresholdSegmentationLevelSetImageFilter}, $15$ iterations of
  //  the \code{CannySegmentationLevelSetImageFilter}, and the
  //  \code{CannySegmentationLevelSetImageFilter} run to convergence.}
  //  \label{fig:CannySegmentationLevelSetImageFilter}
  //  \end{figure}
  //
  //  The free parameters of this filter can be adjusted to achieve a wide
  //  range of shape variations from the original model.  Finding the right
  //  parameters for your particular application is usually a process of trial
  //  and error.  As with most ITK level-set segmentation filters, examining
  //  the propagation (speed) and advection images can help the process of
  //  tuning parameters.  These images are available using \code{Set/Get}
  //  methods from the filter after it has been updated.
  //
  //  Software Guide : EndLatex

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <RosettaTorch/ActionEncoder.hpp>

namespace RosettaTorch
{
torch::Tensor ActionEncoder::ActionToTensor(const Game& game,
                                            const Generic::ActionEncode& action)
{
    // vector shape: [4 + 13 * 5 = 69]
    // [ONE_HOT_TASKID #4]
    // [SOURCE: [ONE_HOT_PLACE_INFO #3] [ONE_HOT_INDEX #10]]
    // [TARGET: [...] #4]
    torch::Tensor tensor = torch::empty(ActionTensorSize, torch::kInt8);

    // Write ont-hot encoded TaskID
    for (size_t i = 0; i < TaskIDSize; ++i)
    {
        if (action.taskID == TaskIDs[i])
        {
            tensor[i] = 1;
        }
        else
        {
            tensor[i] = 0;
        }
    }

    auto fill_zero = [&](size_t start) {
        for (size_t i = 0; i < EntityEncodeSize; ++i)
        {
            tensor[start + i] = 0;
        }
    };

    auto write = [&](size_t start, Entity* entity) {
        // Initialize
        fill_zero(start);
        if (entity == nullptr)
        {
            return;
        }

        // If entity is on the hand of current player
        if (entity->zone->GetType() == ZoneType::HAND)
        {
            tensor[start + CurrentHandOffset] = 1;
            tensor[start + TargetPlaceSize + entity->zonePos] = 1;
        }
        // If entity is on the board of current player
        else if (entity->zone->GetType() == ZoneType::PLAY)
        {
            // If entity is on the field of current player
            if (entity->owner == &game.GetCurrentPlayer())
            {
                tensor[start + CurrentFieldOffset] = 1;
                tensor[start + TargetPlaceSize + entity->zonePos] = 1;
            }
            // If entity is on the field of other player
            else if (entity->owner == &game.GetOpponentPlayer())
            {
                tensor[start + OpponentFieldOffset] = 1;
                tensor[start + TargetPlaceSize + entity->zonePos] = 1;
            }
        }
    };

    // Write source
    write(TaskIDSize, action.source);

    // Write target
    for (size_t i = 0; i < NumTarget; ++i)
    {
        write(TaskIDSize + (i + 1) * EntityEncodeSize, action.target[i]);
    }

    return tensor;
}
}  // namespace RosettaTorch<commit_msg>refactor: Integrate duplicate code by code review<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <RosettaTorch/ActionEncoder.hpp>

namespace RosettaTorch
{
torch::Tensor ActionEncoder::ActionToTensor(const Game& game,
                                            const Generic::ActionEncode& action)
{
    // vector shape: [4 + 13 * 5 = 69]
    // [ONE_HOT_TASKID #4]
    // [SOURCE: [ONE_HOT_PLACE_INFO #3] [ONE_HOT_INDEX #10]]
    // [TARGET: [...] #4]
    torch::Tensor tensor = torch::empty(ActionTensorSize, torch::kInt8);

    // Write ont-hot encoded TaskID
    for (size_t i = 0; i < TaskIDSize; ++i)
    {
        if (action.taskID == TaskIDs[i])
        {
            tensor[i] = 1;
        }
        else
        {
            tensor[i] = 0;
        }
    }

    auto fill_zero = [&](size_t start) {
        for (size_t i = 0; i < EntityEncodeSize; ++i)
        {
            tensor[start + i] = 0;
        }
    };

    auto write = [&](size_t start, Entity* entity) {
        // Initialize
        fill_zero(start);
        if (entity == nullptr)
        {
            return;
        }

        // If entity is on the hand of current player
        if (entity->zone->GetType() == ZoneType::HAND)
        {
            tensor[start + CurrentHandOffset] = 1;
            tensor[start + TargetPlaceSize + entity->zonePos] = 1;
        }
        // If entity is on the board of current player
        else if (entity->zone->GetType() == ZoneType::PLAY)
        {
            // If entity is on the field of current player
            if (entity->owner == &game.GetCurrentPlayer())
            {
                tensor[start + CurrentFieldOffset] = 1;
            }
            // If entity is on the field of other player
            else
            {
                tensor[start + OpponentFieldOffset] = 1;
            }

            tensor[start + TargetPlaceSize + entity->zonePos] = 1;
        }
    };

    // Write source
    write(TaskIDSize, action.source);

    // Write target
    for (size_t i = 0; i < NumTarget; ++i)
    {
        write(TaskIDSize + (i + 1) * EntityEncodeSize, action.target[i]);
    }

    return tensor;
}
}  // namespace RosettaTorch<|endoftext|>


<commit_before><commit_msg>Http cache: dump the transaction and active entry key to check that they are not the same.<commit_after><|endoftext|>


<commit_before><commit_msg>Http Cache: Enable some checks to track a low volume crash.<commit_after><|endoftext|>


<commit_before>#include "gtest/gtest.h"

#include "tests_helpers.hxx"
#include "rectangle.hxx"
#include "optimal_rectangle_packing.hxx"
#include "rectangle_containment_solver.hxx"
#include "solution_to_string.hxx"

using namespace packing;

class OptimalRectanglePackingTests : public testing::Test {
protected:
  void check(const std::vector<Rectangle> & input,
             int expectedArea)
  {
    auto solution = OptimalRectanglePacking(input).compute();

    EXPECT_EQ(expectedArea, solution.boxSize.computeArea())
      << solutionToString(solution.boxSize,
                          solution.rectangles,
                          solution.rectanglePositions);
  }
};

TEST_F(OptimalRectanglePackingTests, SiteExample)
{
  auto input = {
    Rectangle(8, 8, 1),
    Rectangle(4, 3, 2),
    Rectangle(4, 3, 3)
  };
  check(input, 88);
}

TEST_F(OptimalRectanglePackingTests, Square5)
{
  check(createDecrementingSquares(5), 5*12);
}

TEST_F(OptimalRectanglePackingTests, Square9)
{
  check(createDecrementingSquares(9), 15*20);
}

TEST_F(OptimalRectanglePackingTests, Constant100)
{
  check(createSameRectangles(100), 200);
}

TEST_F(OptimalRectanglePackingTests, Square10)
{
  check(createDecrementingSquares(10), 15*27);
}

TEST_F(OptimalRectanglePackingTests, Rectangle10)
{
  check(createDecrementingRectangles(10), 17*26);
}
<commit_msg>Changed tests to 14 squares and rectangles<commit_after>#include "gtest/gtest.h"

#include "tests_helpers.hxx"
#include "rectangle.hxx"
#include "optimal_rectangle_packing.hxx"
#include "rectangle_containment_solver.hxx"
#include "solution_to_string.hxx"

using namespace packing;

class OptimalRectanglePackingTests : public testing::Test {
protected:
  void check(const std::vector<Rectangle> & input,
             int expectedArea)
  {
    auto solution = OptimalRectanglePacking(input).compute();

    EXPECT_EQ(expectedArea, solution.boxSize.computeArea())
      << solutionToString(solution.boxSize,
                          solution.rectangles,
                          solution.rectanglePositions);
  }
};

TEST_F(OptimalRectanglePackingTests, SiteExample)
{
  auto input = {
    Rectangle(8, 8, 1),
    Rectangle(4, 3, 2),
    Rectangle(4, 3, 3)
  };
  check(input, 88);
}

TEST_F(OptimalRectanglePackingTests, Square5)
{
  check(createDecrementingSquares(5), 5*12);
}

TEST_F(OptimalRectanglePackingTests, Square9)
{
  check(createDecrementingSquares(9), 15*20);
}

TEST_F(OptimalRectanglePackingTests, Constant100)
{
  check(createSameRectangles(100), 200);
}

TEST_F(OptimalRectanglePackingTests, Square14)
{
  check(createDecrementingSquares(14), 23*45);
}

TEST_F(OptimalRectanglePackingTests, Rectangle14)
{
  check(createDecrementingRectangles(14), 28*40);
}
<|endoftext|>


<commit_before>#include <cmath>
#include "gtest/gtest.h"
#include "math_utils/math_functions.h"
#include "random.h"

TEST(BinomialDistribution, real_theory) {
  double p = 0.5;
  double p_complement = 1.0 - p;
  int n = 10;
  const int COUNT = 100000;
  cuhksz::BinomialDistribution binodist(n, p);
  int bucket[11];
  for (int i = 0; i < 11; i++) bucket[i] = 0;
  for (int i = 0; i < COUNT; i++) {
    bucket[binodist.next()] += 1;
  }
  double error_sum = 0;
  for (int i = 0; i < 11; i++) {
    double real = double(bucket[i]) / COUNT;
    double theory =
        cuhksz::binomial(n, i) * std::pow(p, i) * std::pow(p_complement, n - i);
    error_sum += std::abs(real - theory) / theory;
  }
  EXPECT_LT(error_sum / 11, 0.05);
}
<commit_msg>fix bug with binomaildistribution test<commit_after>#include <cmath>
#include "gtest/gtest.h"
#include "math_utils/math_functions.h"
#include "random.h"

TEST(BinomialDistribution, real_theory) {
  double p = 0.5;
  double p_complement = 1.0 - p;
  int n = 10;
  const int COUNT = 100000;
  cuhksz::BinomialDistribution binodist(n, p);
  int bucket[11];
  for (int i = 0; i < 11; i++) bucket[i] = 0;
  for (int i = 0; i < COUNT; i++) {
    bucket[binodist.next()] += 1;
  }
  double error_sum = 0;
  for (int i = 0; i < 11; i++) {
    double real = double(bucket[i]) / COUNT;
    double theory =
        cuhksz::binomial(n, i) * std::pow(p, i) * std::pow(p_complement, n - i);
    error_sum += std::abs(real - theory) / theory;
  }
  EXPECT_LT(error_sum / 11, 0.06);
}
<|endoftext|>


<commit_before>/**
 * @file CameraMatrix.cpp
 *
 * Definition of class CameraMatrix
 */

#include "CameraMatrix.h"

#include "Messages/Representations.pb.h"
#include <google/protobuf/io/zero_copy_stream_impl.h>

#include <Tools/CameraGeometry.h>
#include <Tools/DataConversion.h>

using namespace naoth;

void CameraMatrix::print(std::ostream& stream) const
{
  stream << "x-angle [deg] = " << Math::toDegrees(rotation.getXAngle()) << std::endl;
  stream << "y-angle [deg] = " << Math::toDegrees(rotation.getYAngle()) << std::endl;
  stream << "z-angle [deg] = " << Math::toDegrees(rotation.getZAngle()) << std::endl;
  stream << "x-translation [mm] = " << translation.x << std::endl;
  stream << "y-translation [mm] = " << translation.y << std::endl;
  stream << "z-translation [mm] = " << translation.z << std::endl;
  stream << "valid = " << valid << std::endl;
  stream << "timestamp = " << timestamp << std::endl;
}//end print

void Serializer<CameraMatrix>::serialize(const CameraMatrix& representation, std::ostream& stream)
{
  naothmessages::CameraMatrix msg;

  msg.set_valid(representation.valid);
  msg.set_timestamp(representation.timestamp);
  naoth::DataConversion::toMessage(representation, *(msg.mutable_pose()));

  google::protobuf::io::OstreamOutputStream buf(&stream);
  msg.SerializeToZeroCopyStream(&buf);
}//end serialize

void Serializer<CameraMatrix>::deserialize(std::istream& stream, CameraMatrix& representation)
{
  naothmessages::CameraMatrix msg;
  google::protobuf::io::IstreamInputStream buf(&stream);
  msg.ParseFromZeroCopyStream(&buf);

  if(msg.has_timestamp()) {
    representation.timestamp = msg.timestamp();
  }
  if(msg.has_valid()) {
    representation.valid = msg.valid();
  }
  naoth::DataConversion::fromMessage(msg.pose(), representation);
}//end deserialize
<commit_msg>fix line endings<commit_after>/**
 * @file CameraMatrix.cpp
 *
 * Definition of class CameraMatrix
 */

#include "CameraMatrix.h"

#include "Messages/Representations.pb.h"
#include <google/protobuf/io/zero_copy_stream_impl.h>

#include <Tools/CameraGeometry.h>
#include <Tools/DataConversion.h>

using namespace naoth;

void CameraMatrix::print(std::ostream& stream) const
{
  stream << "x-angle [deg] = " << Math::toDegrees(rotation.getXAngle()) << std::endl;
  stream << "y-angle [deg] = " << Math::toDegrees(rotation.getYAngle()) << std::endl;
  stream << "z-angle [deg] = " << Math::toDegrees(rotation.getZAngle()) << std::endl;
  stream << "x-translation [mm] = " << translation.x << std::endl;
  stream << "y-translation [mm] = " << translation.y << std::endl;
  stream << "z-translation [mm] = " << translation.z << std::endl;
  stream << "valid = " << valid << std::endl;
  stream << "timestamp = " << timestamp << std::endl;
}//end print

void Serializer<CameraMatrix>::serialize(const CameraMatrix& representation, std::ostream& stream)
{
  naothmessages::CameraMatrix msg;

  msg.set_valid(representation.valid);
  msg.set_timestamp(representation.timestamp);
  naoth::DataConversion::toMessage(representation, *(msg.mutable_pose()));

  google::protobuf::io::OstreamOutputStream buf(&stream);
  msg.SerializeToZeroCopyStream(&buf);
}//end serialize

void Serializer<CameraMatrix>::deserialize(std::istream& stream, CameraMatrix& representation)
{
  naothmessages::CameraMatrix msg;
  google::protobuf::io::IstreamInputStream buf(&stream);
  msg.ParseFromZeroCopyStream(&buf);

  if(msg.has_timestamp()) {
    representation.timestamp = msg.timestamp();
  }
  if(msg.has_valid()) {
    representation.valid = msg.valid();
  }
  naoth::DataConversion::fromMessage(msg.pose(), representation);
}//end deserialize
<|endoftext|>


<commit_before><commit_msg>Bug #95298#: ExportField - set pointer correct<commit_after><|endoftext|>