<commit_before>// Copyright (c) 2017 Franka Emika GmbH
// Use of this source code is governed by the Apache-2.0 license, see LICENSE
#include <franka_gripper/franka_gripper.h>

#include <cmath>
#include <functional>
#include <thread>

#include <ros/node_handle.h>

#include <franka/exception.h>
#include <franka/gripper_state.h>
#include <franka_gripper/GraspAction.h>
#include <franka_gripper/HomingAction.h>
#include <franka_gripper/MoveAction.h>
#include <franka_gripper/StopAction.h>

namespace franka_gripper {

bool updateGripperState(const franka::Gripper& gripper, franka::GripperState* state) {
  try {
    *state = gripper.readOnce();
  } catch (const franka::Exception& ex) {
    ROS_ERROR_STREAM("GripperServer: Exception reading gripper state: " << ex.what());
    return false;
  }
  return true;
}

void gripperCommandExecuteCallback(
    const franka::Gripper& gripper,
    double default_epsilon_inner,
    double default_epsilon_outer,
    double default_speed,
    actionlib::SimpleActionServer<control_msgs::GripperCommandAction>* action_server,
    const control_msgs::GripperCommandGoalConstPtr& goal) {
  std::function<bool()> gripper_command_handler = [=, &gripper]() {
    franka::GripperState state = gripper.readOnce();
    if (goal->command.position > state.max_width || goal->command.position < 0.0) {
      ROS_ERROR_STREAM("GripperServer: Commanding out of range width! max_width = "
                       << state.max_width << " command = " << goal->command.position);
      return false;
    }
    if (goal->command.position >= state.width) {
      return gripper.move(goal->command.position, default_speed);
    }
    return gripper.grasp(goal->command.position, default_epsilon_inner, default_epsilon_outer,
                         default_speed, goal->command.max_effort);
  };

  try {
    if (gripper_command_handler()) {
      franka::GripperState state;
      if (updateGripperState(gripper, &state)) {
        control_msgs::GripperCommandResult result;
        result.effort = 0.0;
        result.position = state.width;
        result.reached_goal = static_cast<decltype(result.reached_goal)>(true);
        result.stalled = static_cast<decltype(result.stalled)>(false);
        action_server->setSucceeded(result);
        return;
      }
    }
  } catch (const franka::Exception& ex) {
    ROS_ERROR_STREAM("" << ex.what());
  }
  action_server->setAborted();
}

bool move(const franka::Gripper& gripper, const MoveGoalConstPtr& goal) {
  return gripper.move(goal->width, goal->speed);
}

bool homing(const franka::Gripper& gripper, const HomingGoalConstPtr& /*goal*/) {
  return gripper.homing();
}

bool stop(const franka::Gripper& gripper, const StopGoalConstPtr& /*goal*/) {
  return gripper.stop();
}

bool grasp(const franka::Gripper& gripper, const GraspGoalConstPtr& goal) {
  return gripper.grasp(goal->width, goal->epsilon_inner, goal->epsilon_outer, goal->speed,
                       goal->force);
}

}  // namespace franka_gripper
<commit_msg>Adapted grasp epsilon to use Gripper::GraspEpsilon<commit_after>// Copyright (c) 2017 Franka Emika GmbH
// Use of this source code is governed by the Apache-2.0 license, see LICENSE
#include <franka_gripper/franka_gripper.h>

#include <cmath>
#include <functional>
#include <thread>

#include <ros/node_handle.h>

#include <franka/exception.h>
#include <franka/gripper_state.h>
#include <franka_gripper/GraspAction.h>
#include <franka_gripper/HomingAction.h>
#include <franka_gripper/MoveAction.h>
#include <franka_gripper/StopAction.h>

namespace franka_gripper {

bool updateGripperState(const franka::Gripper& gripper, franka::GripperState* state) {
  try {
    *state = gripper.readOnce();
  } catch (const franka::Exception& ex) {
    ROS_ERROR_STREAM("GripperServer: Exception reading gripper state: " << ex.what());
    return false;
  }
  return true;
}

void gripperCommandExecuteCallback(
    const franka::Gripper& gripper,
    double default_epsilon_inner,
    double default_epsilon_outer,
    double default_speed,
    actionlib::SimpleActionServer<control_msgs::GripperCommandAction>* action_server,
    const control_msgs::GripperCommandGoalConstPtr& goal) {
  std::function<bool()> gripper_command_handler = [=, &gripper]() {
    franka::GripperState state = gripper.readOnce();
    if (goal->command.position > state.max_width || goal->command.position < 0.0) {
      ROS_ERROR_STREAM("GripperServer: Commanding out of range width! max_width = "
                       << state.max_width << " command = " << goal->command.position);
      return false;
    }
    if (goal->command.position >= state.width) {
      return gripper.move(goal->command.position, default_speed);
    }
    franka::Gripper::GraspEpsilon epsilon{.inner = default_epsilon_inner,
                                          .outer = default_epsilon_outer};
    return gripper.grasp(goal->command.position, epsilon, default_speed, goal->command.max_effort);
  };

  try {
    if (gripper_command_handler()) {
      franka::GripperState state;
      if (updateGripperState(gripper, &state)) {
        control_msgs::GripperCommandResult result;
        result.effort = 0.0;
        result.position = state.width;
        result.reached_goal = static_cast<decltype(result.reached_goal)>(true);
        result.stalled = static_cast<decltype(result.stalled)>(false);
        action_server->setSucceeded(result);
        return;
      }
    }
  } catch (const franka::Exception& ex) {
    ROS_ERROR_STREAM("" << ex.what());
  }
  action_server->setAborted();
}

bool move(const franka::Gripper& gripper, const MoveGoalConstPtr& goal) {
  return gripper.move(goal->width, goal->speed);
}

bool homing(const franka::Gripper& gripper, const HomingGoalConstPtr& /*goal*/) {
  return gripper.homing();
}

bool stop(const franka::Gripper& gripper, const StopGoalConstPtr& /*goal*/) {
  return gripper.stop();
}

bool grasp(const franka::Gripper& gripper, const GraspGoalConstPtr& goal) {
  franka::Gripper::GraspEpsilon epsilon{.inner = goal->epsilon_inner, .outer = goal->epsilon_outer};
  return gripper.grasp(goal->width, epsilon, goal->speed, goal->force);
}

}  // namespace franka_gripper
<|endoftext|>


<commit_before>#include "Character.h"

CCharacter::CCharacter(void):m_CharacterSprite(NULL)
{
	AnimationImageInfo idleAnimationImageInfo = {2, L"idle",{10.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(IDLE,idleAnimationImageInfo));

	AnimationImageInfo walkAnimationImageInfo = {2, L"walk",{20.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(WALK,walkAnimationImageInfo));

	AnimationImageInfo attackAnimationImageInfo = {2, L"attack",{10.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(ATTACK,attackAnimationImageInfo));

	AnimationImageInfo dieAnimationImageInfo = {2, L"die",{10.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(DIE,dieAnimationImageInfo));

	m_AnimationFrameTime = 0.f;

	TransState(IDLE);
	m_LogLabel = NNLabel::Create( L"Normal Label", L" ", 35.f );
	m_LogLabel->SetPosition(50.f,50.f);
	AddChild(m_LogLabel);

	//NNAudioSystem::GetInstance()->AddEffectSound( "Effect", L"Sound/effect.wav" );
	//NNAudioSystem::GetInstance()->AddEffectSound( "Effect1", L"Sound/effect1.mp3" );

}

CCharacter::~CCharacter(void)
{
}

void CCharacter::TransState(CharacterState state)
{
	m_CharacterState = state;
	m_AnimationFrameTime = 0;
	m_NowFrame = 0;
	AnimationImageInfo nowAnimationImageInfo = m_AnimationImageInfo.find(m_CharacterState)->second;
	if( m_CharacterSprite != NULL)
	{
		RemoveChild(m_CharacterSprite);
	}
	WCHAR buff[1024];
	swprintf_s(buff,L"Sprite/%s_%d.png",nowAnimationImageInfo.imagePrefix.c_str(),m_NowFrame);
	std::wstring framePath = buff;//L"Sprite/" + nowAnimationImageInfo.imagePrefix + "_";
	m_CharacterSprite = NNSprite::Create(framePath);
	m_CharacterSprite->SetCenter(m_CharacterSprite->GetImageWidth()/2.f, m_CharacterSprite->GetImageHeight()/2.f);
	AddChild(m_CharacterSprite);
}

void CCharacter::Update( float dTime)
{

	//Animation With m_State
	AnimationImageInfo nowAnimationImageInfo = m_AnimationImageInfo.find(m_CharacterState)->second;

	//Calculate 'Now Frame' With integration dtime
	m_AnimationFrameTime += dTime;
	bool isFrameChange = false;
	while(nowAnimationImageInfo.frameDelay[m_NowFrame] < m_AnimationFrameTime)
	{
		m_AnimationFrameTime -= nowAnimationImageInfo.frameDelay[m_NowFrame];
		m_NowFrame = (m_NowFrame+1)%nowAnimationImageInfo.totalFrameCount;
		isFrameChange = true;
	}
	if(isFrameChange == true)
	{
		RemoveChild(m_CharacterSprite);
		WCHAR buff[1024];
		swprintf_s(buff,L"Sprite/%s_%d.png",nowAnimationImageInfo.imagePrefix.c_str(),m_NowFrame);
		std::wstring framePath = buff;
		m_CharacterSprite = NNSprite::Create(framePath);
		m_CharacterSprite->SetCenter(m_CharacterSprite->GetImageWidth()/2.f, m_CharacterSprite->GetImageHeight()/2.f);
		AddChild(m_CharacterSprite);
	}

	//Check Moving Input, and set Position to d
	if ( NNInputSystem::GetInstance()->GetKeyState( 'A' ) == KEY_DOWN  ||
		NNInputSystem::GetInstance()->GetKeyState( 'A' ) == KEY_PRESSED)
	{
		//Left
		SetPosition( GetPosition() + NNPoint( cos((m_CharacterSprite->GetRotation() + -90.f)/180.f*3.14f), sin((m_CharacterSprite->GetRotation() -90.f)/180.f*3.14f)) * dTime * 100.f );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( 'D' ) == KEY_DOWN  ||
		NNInputSystem::GetInstance()->GetKeyState( 'D' ) == KEY_PRESSED)
	{
		//Right
		SetPosition( GetPosition() + NNPoint( cos((m_CharacterSprite->GetRotation() + +90.f)/180.f*3.14f), sin((m_CharacterSprite->GetRotation() +90.f)/180.f*3.14f)) * dTime * 100.f );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( 'W' ) == KEY_DOWN  ||
		NNInputSystem::GetInstance()->GetKeyState( 'W' ) == KEY_PRESSED)
	{
		//UP
		SetPosition( GetPosition() + NNPoint( cos((m_CharacterSprite->GetRotation())/180.f*3.14f), sin((m_CharacterSprite->GetRotation())/180.f*3.14f)) * dTime * 100.f );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( 'S' ) == KEY_DOWN  ||
		NNInputSystem::GetInstance()->GetKeyState( 'S' ) == KEY_PRESSED)
	{
		//Down
		SetPosition( GetPosition() + NNPoint( cos((m_CharacterSprite->GetRotation() + 180.f)/180.f*3.14f), sin((m_CharacterSprite->GetRotation() + 180.f)/180.f*3.14f)) * dTime * 100.f );
	}

	if ( NNInputSystem::GetInstance()->GetKeyState( '1' ) == KEY_DOWN )
	{
		TransState(WALK);
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '2' ) == KEY_DOWN )
	{
		TransState(IDLE);
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '3' ) == KEY_DOWN )
	{
		TransState(ATTACK);
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '4' ) == KEY_DOWN )
	{
		TransState(DIE);
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '5' ) == KEY_DOWN )
	{
//		NNAudioSystem::GetInstance()->PlayEffectSound( "Effect" );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '6' ) == KEY_DOWN )
{
	//	NNAudioSystem::GetInstance()->PlayEffectSound( "Effect1" );
	}
	//Change Image By now Frame.
	NNPoint mousePoint = NNInputSystem::GetInstance()->GetMousePosition();
	WCHAR buff[1024];
	swprintf_s(buff,L"%f / %f",mousePoint.GetX(),m_CharacterSprite->GetRotation());//mousePoint.GetY());
	m_LogLabel->SetString(buff);
	m_CharacterSprite->SetRotation(atan2f(mousePoint.GetY() - 300.f, mousePoint.GetX() - 400.f) * 180.0f / 3.14f);
}
void CCharacter::Render()
{
	NNObject::Render();
}<commit_msg>숫자키 7로 hihi'라는 메시지 서버와 에코<commit_after>#include "Character.h"
#include "Packet.h"
#include "NNNetworkSystem.h"

CCharacter::CCharacter(void):m_CharacterSprite(NULL)
{
	AnimationImageInfo idleAnimationImageInfo = {2, L"idle",{10.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(IDLE,idleAnimationImageInfo));

	AnimationImageInfo walkAnimationImageInfo = {2, L"walk",{20.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(WALK,walkAnimationImageInfo));

	AnimationImageInfo attackAnimationImageInfo = {2, L"attack",{10.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(ATTACK,attackAnimationImageInfo));

	AnimationImageInfo dieAnimationImageInfo = {2, L"die",{10.f,10.f}};
	m_AnimationImageInfo.insert( std::map< CharacterState, AnimationImageInfo >::value_type(DIE,dieAnimationImageInfo));

	m_AnimationFrameTime = 0.f;

	TransState(IDLE);
	m_LogLabel = NNLabel::Create( L"Normal Label", L" ", 35.f );
	m_LogLabel->SetPosition(50.f,50.f);
	AddChild(m_LogLabel);

	//NNAudioSystem::GetInstance()->AddEffectSound( "Effect", L"Sound/effect.wav" );
	//NNAudioSystem::GetInstance()->AddEffectSound( "Effect1", L"Sound/effect1.mp3" );

}

CCharacter::~CCharacter(void)
{
}

void CCharacter::TransState(CharacterState state)
{
	m_CharacterState = state;
	m_AnimationFrameTime = 0;
	m_NowFrame = 0;
	AnimationImageInfo nowAnimationImageInfo = m_AnimationImageInfo.find(m_CharacterState)->second;
	if( m_CharacterSprite != NULL)
	{
		RemoveChild(m_CharacterSprite);
	}
	WCHAR buff[1024];
	swprintf_s(buff,L"Sprite/%s_%d.png",nowAnimationImageInfo.imagePrefix.c_str(),m_NowFrame);
	std::wstring framePath = buff;//L"Sprite/" + nowAnimationImageInfo.imagePrefix + "_";
	m_CharacterSprite = NNSprite::Create(framePath);
	m_CharacterSprite->SetCenter(m_CharacterSprite->GetImageWidth()/2.f, m_CharacterSprite->GetImageHeight()/2.f);
	AddChild(m_CharacterSprite);
}

void CCharacter::Update( float dTime)
{

	//Animation With m_State
	AnimationImageInfo nowAnimationImageInfo = m_AnimationImageInfo.find(m_CharacterState)->second;

	//Calculate 'Now Frame' With integration dtime
	m_AnimationFrameTime += dTime;
	bool isFrameChange = false;
	while(nowAnimationImageInfo.frameDelay[m_NowFrame] < m_AnimationFrameTime)
	{
		m_AnimationFrameTime -= nowAnimationImageInfo.frameDelay[m_NowFrame];
		m_NowFrame = (m_NowFrame+1)%nowAnimationImageInfo.totalFrameCount;
		isFrameChange = true;
	}
	if(isFrameChange= true)
	{
		RemoveChild(m_CharacterSprite);
		WCHAR buff[1024];
		swprintf_s(buff,L"Sprite/%s_%d.png",nowAnimationImageInfo.imagePrefix.c_str(),m_NowFrame);
		std::wstring framePath = buff;
		m_CharacterSprite = NNSprite::Create(framePath);
		m_CharacterSprite->SetCenter(m_CharacterSprite->GetImageWidth()/2.f, m_CharacterSprite->GetImageHeight()/2.f);
		AddChild(m_CharacterSprite);
	}

	//Check Moving Input, and set Position to d
	if ( NNInputSystem::GetInstance()->GetKeyState( 'A' ) == KEY_DOWN  ||
		NNInputSystem::GetInstance()->GetKeyState( 'A' ) == KEY_PRESSED)
	{
		//Left
		SetPosition( GetPosition() + NNPoint( cos((m_CharacterSprite->GetRotation() + -90.f)/180.f*3.14f), sin((m_CharacterSprite->GetRotation() -90.f)/180.f*3.14f)) * dTime * 100.f );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( 'D' ) == KEY_DOWN  ||
		NNInputSystem::GetInstance()->GetKeyState( 'D' ) == KEY_PRESSED)
	{
		//Right
		SetPosition( GetPosition() + NNPoint( cos((m_CharacterSprite->GetRotation() + +90.f)/180.f*3.14f), sin((m_CharacterSprite->GetRotation() +90.f)/180.f*3.14f)) * dTime * 100.f );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( 'W' ) == KEY_DOWN  ||
		NNInputSystem::GetInstance()->GetKeyState( 'W' ) == KEY_PRESSED)
	{
		//UP
		SetPosition( GetPosition() + NNPoint( cos((m_CharacterSprite->GetRotation())/180.f*3.14f), sin((m_CharacterSprite->GetRotation())/180.f*3.14f)) * dTime * 100.f );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( 'S' ) == KEY_DOWN  ||
		NNInputSystem::GetInstance()->GetKeyState( 'S' ) == KEY_PRESSED)
	{
		//Down
		SetPosition( GetPosition() + NNPoint( cos((m_CharacterSprite->GetRotation() + 180.f)/180.f*3.14f), sin((m_CharacterSprite->GetRotation() + 180.f)/180.f*3.14f)) * dTime * 100.f );
	}

	if ( NNInputSystem::GetInstance()->GetKeyState( '1' ) == KEY_DOWN )
	{
		TransState(WALK);
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '2' ) == KEY_DOWN )
	{
		TransState(IDLE);
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '3' ) == KEY_DOWN )
	{
		TransState(ATTACK);
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '4' ) == KEY_DOWN )
	{
		TransState(DIE);
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '5' ) == KEY_DOWN )
	{
//		NNAudioSystem::GetInstance()->PlayEffectSound( "Effect" );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '6' ) == KEY_DOWN )
{
	//	NNAudioSystem::GetInstance()->PlayEffectSound( "Effect1" );
	}
	if ( NNInputSystem::GetInstance()->GetKeyState( '7' ) == KEY_DOWN )
	{
		ChatBroadcastRequest CBR = ChatBroadcastRequest();
		strcpy_s(CBR.m_Chat,"hihi");
		NNNetworkSystem::GetInstance()->Send(&CBR);
	}
	//Change Image By now Frame.
	NNPoint mousePoint = NNInputSystem::GetInstance()->GetMousePosition();
	WCHAR buff[1024];
	swprintf_s(buff,L"%f / %f",mousePoint.GetX(),m_CharacterSprite->GetRotation());//mousePoint.GetY());
	m_LogLabel->SetString(buff);
	m_CharacterSprite->SetCenter(m_CharacterSprite->GetImageWidth()/2.f,m_CharacterSprite->GetImageHeight()/2.f);
	m_CharacterSprite->SetRotation(atan2f(mousePoint.GetY() - 300.f, mousePoint.GetX() - 400.f) * 180.0f / 3.14f);
}
void CCharacter::Render()
{
	NNObject::Render();
}<|endoftext|>


<commit_before>
#include "GameUISet.h"
#include "NNApplication.h"

GameUISet::GameUISet()
{
	m_FPSLabel = NNLabel::Create( L"", L" ", 20 );
	AddChild( m_FPSLabel );

	ZeroMemory( m_FPSLabelBuff, sizeof(m_FPSLabelBuff) );
}
GameUISet::~GameUISet()
{

}

void GameUISet::Render()
{
	NNUISet::Render();
}
void GameUISet::Update( float dTime )
{
	NNUISet::Update( dTime );

	swprintf_s( m_FPSLabelBuff, L"%d", (int)NNApplication::GetInstance()->GetFPS() );
	m_FPSLabel->SetString( m_FPSLabelBuff );
}<commit_msg>@ gameUI changed( playerUI -> gameUI)<commit_after>
#include "GameUISet.h"
#include "NNApplication.h"

GameUISet::GameUISet()
{
	m_TypeSkillCooltime = 5;
	m_UserSkillCooltime = 10;

	float width = (float)NNApplication::GetInstance()->GetScreenWidth();
	float height = (float)NNApplication::GetInstance()->GetScreenHeight();

	m_FPSLabel = NNLabel::Create( L"", L" ", 20 );
	AddChild( m_FPSLabel );

	m_UserSkillBarEffect = NNSprite::Create( L"Sprite/SkillBarEffect.jpg" );
	m_UserSkillBarEffect->SetCenter( m_UserSkillBarEffect->GetImageWidth()/2.f, m_UserSkillBarEffect->GetImageHeight()/2.f );
	m_UserSkillBarEffect->SetPosition( width/2.f - 40, height/2.f + 200 );
	AddChild( m_UserSkillBarEffect );

	m_UserSkillBarEffect->SetVisible(true);

	m_TypeSkillBarEffect = NNSprite::Create( L"Sprite/SkillBarEffect.jpg" );
	m_TypeSkillBarEffect->SetCenter( m_TypeSkillBarEffect->GetImageWidth()/2.f, m_TypeSkillBarEffect->GetImageHeight()/2.f );
	m_TypeSkillBarEffect->SetPosition( width/2.f + 40, height/2.f + 200 );
	AddChild( m_TypeSkillBarEffect );

	m_TypeSkillBarEffect->SetVisible(true);

	m_UserSkillUI = NNSprite::Create( L"Sprite/UserSkillUI_0.png" );
	m_UserSkillUI->SetCenter( m_UserSkillUI->GetImageWidth()/2.f, m_UserSkillUI->GetImageHeight()/2.f );
	m_UserSkillUI->SetPosition( width/2.f + 40, height/2.f + 200 );
	AddChild( m_UserSkillUI );

	m_UserSkillTimer = NNLabel::Create( L"20", L" ", 40.f );
	m_UserSkillTimer->SetCenter( m_UserSkillUI->GetCenterX(), m_UserSkillUI->GetCenterY() );
	m_UserSkillTimer->SetPosition( width/2.f + 40, height/2.f + 200 );
	m_UserSkillTimer->SetRGBA(255,255,255,1);
	AddChild( m_UserSkillTimer );

	m_TypeSkillUI = NNSprite::Create( L"Sprite/TypeSkillUI_0.png" );
	m_TypeSkillUI->SetCenter( m_TypeSkillUI->GetImageWidth()/2.f, m_TypeSkillUI->GetImageHeight()/2.f );
	m_TypeSkillUI->SetPosition( width/2.f - 40, height/2.f + 200 );
	AddChild( m_TypeSkillUI );

	m_TypeSkillTimer = NNLabel::Create( L"5", L" ", 40.f );
	m_TypeSkillTimer->SetCenter( m_TypeSkillUI->GetCenterX(), m_TypeSkillUI->GetCenterY() );
	m_TypeSkillTimer->SetPosition( width/2.f - 40, height/2.f + 200 );
	m_TypeSkillTimer->SetRGBA(255,255,255,1);
	AddChild( m_TypeSkillTimer );

	ZeroMemory( m_FPSLabelBuff, sizeof(m_FPSLabelBuff) );
}
GameUISet::~GameUISet()
{

}

void GameUISet::Render()
{
	NNUISet::Render();
}
void GameUISet::Update( float dTime )
{
	NNUISet::Update( dTime );

	swprintf_s( m_FPSLabelBuff, L"%d", (int)NNApplication::GetInstance()->GetFPS() );
	m_FPSLabel->SetString( m_FPSLabelBuff );

	m_TypeSkillUI->SetOpacity( m_TypeSkillCooltime/10 );
	m_UserSkillUI->SetOpacity( m_TypeSkillCooltime/20 );
}<|endoftext|>


<commit_before>// Copyright (c) 2019 PaddlePaddle 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 "paddle/fluid/framework/ir/identity_scale_op_clean_pass.h"
#include <string>
#include "paddle/fluid/framework/ir/graph_pattern_detector.h"

namespace paddle {
namespace framework {
namespace ir {

std::unique_ptr<ir::Graph> IdentityScaleOpCleanPass::ApplyImpl(
    std::unique_ptr<ir::Graph> graph) const {
  FusePassBase::Init("identity_scale_op_clean", graph.get());

  // pre_op -> scale_in -> scale_op -> scale_out
  // ->
  // pre_op -> scale_out
  GraphPatternDetector detector;
  auto pre_op = detector.mutable_pattern()->NewNode("pre_op")->assert_is_op();
  auto scale_in = detector.mutable_pattern()
                      ->NewNode("scale_in")
                      ->assert_is_op_input("scale")
                      ->AsIntermediate();
  auto scale_op = detector.mutable_pattern()
                      ->NewNode("scale_fuse")
                      ->assert_is_op("scale")
                      ->assert_op_attr<float>("scale", 1.)
                      ->assert_op_attr<float>("bias", 0.);
  auto scale_out = detector.mutable_pattern()
                       ->NewNode("scale_out")
                       ->assert_is_op_output("scale");

  pre_op->LinksTo({scale_in});
  scale_op->LinksFrom({scale_in}).LinksTo({scale_out});

  GraphPatternDetector::handle_t handler = [&](
      const GraphPatternDetector::subgraph_t& subgraph, Graph* graph) {
    Node* scale_op_var = subgraph.at(scale_op);
    Node* scale_in_var = subgraph.at(scale_in);
    Node* scale_out_var = subgraph.at(scale_out);
    Node* pre_op_var = subgraph.at(pre_op);
    // Link pre_op directly to scale_out
    const std::string scale_in_name = scale_in_var->Name();
    const std::string scale_out_name = scale_out_var->Name();
    // Remove links in graph
    GraphSafeRemoveNodes(graph, {scale_in_var, scale_op_var});
    // Modify proto message
    auto* pre_op_desc = pre_op_var->Op();
    for (auto& parameter : *pre_op_desc->Proto()->mutable_outputs()) {
      auto* arguments = parameter.mutable_arguments();
      auto it = std::find(arguments->begin(), arguments->end(), scale_in_name);
      PADDLE_ENFORCE(it != arguments->end());
      *it = scale_out_name;
    }

    IR_NODE_LINK_TO(pre_op_var, scale_out_var);
  };

  detector(graph.get(), handler);
  return graph;
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(identity_scale_op_clean_pass,
              paddle::framework::ir::IdentityScaleOpCleanPass);
<commit_msg>fix scale cleaner (#15742)<commit_after>// Copyright (c) 2019 PaddlePaddle 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 "paddle/fluid/framework/ir/identity_scale_op_clean_pass.h"
#include <string>
#include "paddle/fluid/framework/ir/graph_pattern_detector.h"

namespace paddle {
namespace framework {
namespace ir {

std::unique_ptr<ir::Graph> IdentityScaleOpCleanPass::ApplyImpl(
    std::unique_ptr<ir::Graph> graph) const {
  FusePassBase::Init("identity_scale_op_clean", graph.get());

  // pre_op -> scale_in -> scale_op -> scale_out
  // ->
  // pre_op -> scale_out
  GraphPatternDetector detector;
  auto pre_op = detector.mutable_pattern()->NewNode("pre_op")->assert_is_op();
  auto scale_in = detector.mutable_pattern()
                      ->NewNode("scale_in")
                      ->assert_is_op_input("scale")
                      ->AsIntermediate();
  auto scale_op = detector.mutable_pattern()
                      ->NewNode("scale_fuse")
                      ->assert_is_op("scale")
                      ->assert_op_attr<float>("scale", 1.)
                      ->assert_op_attr<float>("bias", 0.);
  auto scale_out =
      detector.mutable_pattern()
          ->NewNode("scale_out")
          ->assert_is_op_output("scale")
          // scale's output var should has only one consumer, or it can't be
          // removed.
          ->assert_more([](Node* x) { return x->outputs.size() == 1UL; });

  pre_op->LinksTo({scale_in});
  scale_op->LinksFrom({scale_in}).LinksTo({scale_out});

  GraphPatternDetector::handle_t handler = [&](
      const GraphPatternDetector::subgraph_t& subgraph, Graph* graph) {
    Node* scale_op_var = subgraph.at(scale_op);
    Node* scale_in_var = subgraph.at(scale_in);
    Node* scale_out_var = subgraph.at(scale_out);
    Node* pre_op_var = subgraph.at(pre_op);
    // Link pre_op directly to scale_out
    const std::string scale_in_name = scale_in_var->Name();
    const std::string scale_out_name = scale_out_var->Name();
    // Remove links in graph
    GraphSafeRemoveNodes(graph, {scale_in_var, scale_op_var});
    // Modify proto message
    auto* pre_op_desc = pre_op_var->Op();
    for (auto& parameter : *pre_op_desc->Proto()->mutable_outputs()) {
      auto* arguments = parameter.mutable_arguments();
      auto it = std::find(arguments->begin(), arguments->end(), scale_in_name);
      PADDLE_ENFORCE(it != arguments->end());
      *it = scale_out_name;
    }

    IR_NODE_LINK_TO(pre_op_var, scale_out_var);
  };

  detector(graph.get(), handler);
  return graph;
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(identity_scale_op_clean_pass,
              paddle::framework::ir::IdentityScaleOpCleanPass);
<|endoftext|>


<commit_before>//
//    FILE: dht.cpp
//  AUTHOR: Rob Tillaart
// VERSION: 0.1.14
// PURPOSE: DHT Temperature & Humidity Sensor library for Arduino
//     URL: http://arduino.cc/playground/Main/DHTLib
//
// HISTORY:
// 0.1.14 replace digital read with faster (~3x) code => more robust low MHz machines.
// 0.1.13 fix negative temperature
// 0.1.12 support DHT33 and DHT44 initial version
// 0.1.11 renamed DHTLIB_TIMEOUT
// 0.1.10 optimized faster WAKEUP + TIMEOUT
// 0.1.09 optimize size: timeout check + use of mask
// 0.1.08 added formula for timeout based upon clockspeed
// 0.1.07 added support for DHT21
// 0.1.06 minimize footprint (2012-12-27)
// 0.1.05 fixed negative temperature bug (thanks to Roseman)
// 0.1.04 improved readability of code using DHTLIB_OK in code
// 0.1.03 added error values for temp and humidity when read failed
// 0.1.02 added error codes
// 0.1.01 added support for Arduino 1.0, fixed typos (31/12/2011)
// 0.1.00 by Rob Tillaart (01/04/2011)
//
// inspired by DHT11 library
//
// Released to the public domain
//

#include "dht.h"

/////////////////////////////////////////////////////
//
// PUBLIC
//

// return values:
// DHTLIB_OK
// DHTLIB_ERROR_CHECKSUM
// DHTLIB_ERROR_TIMEOUT
int dht::read11(uint8_t pin)
{
    // READ VALUES
    int rv = _readSensor(pin, DHTLIB_DHT11_WAKEUP);
    if (rv != DHTLIB_OK)
    {
        humidity    = DHTLIB_INVALID_VALUE; // invalid value, or is NaN prefered?
        temperature = DHTLIB_INVALID_VALUE; // invalid value
        return rv;
    }

    // CONVERT AND STORE
    humidity    = bits[0];  // bits[1] == 0;
    temperature = bits[2];  // bits[3] == 0;

    // TEST CHECKSUM
    // bits[1] && bits[3] both 0
    uint8_t sum = bits[0] + bits[2];
    if (bits[4] != sum) return DHTLIB_ERROR_CHECKSUM;

    return DHTLIB_OK;
}

// return values:
// DHTLIB_OK
// DHTLIB_ERROR_CHECKSUM
// DHTLIB_ERROR_TIMEOUT
int dht::read(uint8_t pin)
{
    // READ VALUES
    int rv = _readSensor(pin, DHTLIB_DHT_WAKEUP);
    if (rv != DHTLIB_OK)
    {
        humidity    = DHTLIB_INVALID_VALUE;  // invalid value, or is NaN prefered?
        temperature = DHTLIB_INVALID_VALUE;  // invalid value
        return rv; // propagate error value
    }

    // CONVERT AND STORE
    humidity = word(bits[0], bits[1]) * 0.1;
    temperature = word(bits[2] & 0x7F, bits[3]) * 0.1;
    if (bits[2] & 0x80)  // negative temperature
    {
        temperature = -temperature;
    }

    // TEST CHECKSUM
    uint8_t sum = bits[0] + bits[1] + bits[2] + bits[3];
    if (bits[4] != sum)
    {
        return DHTLIB_ERROR_CHECKSUM;
    }
    return DHTLIB_OK;
}

/////////////////////////////////////////////////////
//
// PRIVATE
//

// return values:
// DHTLIB_OK
// DHTLIB_ERROR_TIMEOUT
int dht::_readSensor(uint8_t pin, uint8_t wakeupDelay)
{
    // INIT BUFFERVAR TO RECEIVE DATA
    uint8_t mask = 128;
    uint8_t idx = 0;

    // replace digitalRead() with Direct Port Reads.
    // reduces footprint ~100 bytes => portability issue?
    // direct port read is about 3x faster
	uint8_t bit = digitalPinToBitMask(pin);
	uint8_t port = digitalPinToPort(pin);
    volatile uint8_t *PIR = portInputRegister(port);

    // EMPTY BUFFER
    for (uint8_t i = 0; i < 5; i++) bits[i] = 0;

    // REQUEST SAMPLE
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW); // T-be
    delay(wakeupDelay);
    digitalWrite(pin, HIGH);   // T-go
    delayMicroseconds(40);
    pinMode(pin, INPUT);

    // GET ACKNOWLEDGE or TIMEOUT
    uint16_t loopCntLOW = DHTLIB_TIMEOUT;
    while ((*PIR & bit) == LOW )  // T-rel
    {
        if (--loopCntLOW == 0) return DHTLIB_ERROR_TIMEOUT;
    }

    uint16_t loopCntHIGH = DHTLIB_TIMEOUT;
    while ((*PIR & bit) != LOW )  // T-reh
    {
        if (--loopCntHIGH == 0) return DHTLIB_ERROR_TIMEOUT;
    }

    // READ THE OUTPUT - 40 BITS => 5 BYTES
    for (uint8_t i = 40; i != 0; i--)
    {
        loopCntLOW = DHTLIB_TIMEOUT;
        while ((*PIR & bit) == LOW )
        {
            if (--loopCntLOW == 0) return DHTLIB_ERROR_TIMEOUT;
        }

        uint32_t t = micros();

        loopCntHIGH = DHTLIB_TIMEOUT;
        while ((*PIR & bit) != LOW )
        {
            if (--loopCntHIGH == 0) return DHTLIB_ERROR_TIMEOUT;
        }

        if ((micros() - t) > 40)
        {
            bits[idx] |= mask;
        }
        mask >>= 1;
        if (mask == 0)   // next byte?
        {
            mask = 128;
            idx++;
        }
    }
    pinMode(pin, OUTPUT);
    digitalWrite(pin, HIGH);

    return DHTLIB_OK;
}
//
// END OF FILE
//<commit_msg>Dont set DHT22 data pin as output at end of poll.<commit_after>//
//    FILE: dht.cpp
//  AUTHOR: Rob Tillaart
// VERSION: 0.1.14
// PURPOSE: DHT Temperature & Humidity Sensor library for Arduino
//     URL: http://arduino.cc/playground/Main/DHTLib
//
// HISTORY:
// 0.1.14 replace digital read with faster (~3x) code => more robust low MHz machines.
// 0.1.13 fix negative temperature
// 0.1.12 support DHT33 and DHT44 initial version
// 0.1.11 renamed DHTLIB_TIMEOUT
// 0.1.10 optimized faster WAKEUP + TIMEOUT
// 0.1.09 optimize size: timeout check + use of mask
// 0.1.08 added formula for timeout based upon clockspeed
// 0.1.07 added support for DHT21
// 0.1.06 minimize footprint (2012-12-27)
// 0.1.05 fixed negative temperature bug (thanks to Roseman)
// 0.1.04 improved readability of code using DHTLIB_OK in code
// 0.1.03 added error values for temp and humidity when read failed
// 0.1.02 added error codes
// 0.1.01 added support for Arduino 1.0, fixed typos (31/12/2011)
// 0.1.00 by Rob Tillaart (01/04/2011)
//
// inspired by DHT11 library
//
// Released to the public domain
//

#include "dht.h"

/////////////////////////////////////////////////////
//
// PUBLIC
//

// return values:
// DHTLIB_OK
// DHTLIB_ERROR_CHECKSUM
// DHTLIB_ERROR_TIMEOUT
int dht::read11(uint8_t pin)
{
    // READ VALUES
    int rv = _readSensor(pin, DHTLIB_DHT11_WAKEUP);
    if (rv != DHTLIB_OK)
    {
        humidity    = DHTLIB_INVALID_VALUE; // invalid value, or is NaN prefered?
        temperature = DHTLIB_INVALID_VALUE; // invalid value
        return rv;
    }

    // CONVERT AND STORE
    humidity    = bits[0];  // bits[1] == 0;
    temperature = bits[2];  // bits[3] == 0;

    // TEST CHECKSUM
    // bits[1] && bits[3] both 0
    uint8_t sum = bits[0] + bits[2];
    if (bits[4] != sum) return DHTLIB_ERROR_CHECKSUM;

    return DHTLIB_OK;
}

// return values:
// DHTLIB_OK
// DHTLIB_ERROR_CHECKSUM
// DHTLIB_ERROR_TIMEOUT
int dht::read(uint8_t pin)
{
    // READ VALUES
    int rv = _readSensor(pin, DHTLIB_DHT_WAKEUP);
    if (rv != DHTLIB_OK)
    {
        humidity    = DHTLIB_INVALID_VALUE;  // invalid value, or is NaN prefered?
        temperature = DHTLIB_INVALID_VALUE;  // invalid value
        return rv; // propagate error value
    }

    // CONVERT AND STORE
    humidity = word(bits[0], bits[1]) * 0.1;
    temperature = word(bits[2] & 0x7F, bits[3]) * 0.1;
    if (bits[2] & 0x80)  // negative temperature
    {
        temperature = -temperature;
    }

    // TEST CHECKSUM
    uint8_t sum = bits[0] + bits[1] + bits[2] + bits[3];
    if (bits[4] != sum)
    {
        return DHTLIB_ERROR_CHECKSUM;
    }
    return DHTLIB_OK;
}

/////////////////////////////////////////////////////
//
// PRIVATE
//

// return values:
// DHTLIB_OK
// DHTLIB_ERROR_TIMEOUT
int dht::_readSensor(uint8_t pin, uint8_t wakeupDelay)
{
    // INIT BUFFERVAR TO RECEIVE DATA
    uint8_t mask = 128;
    uint8_t idx = 0;

    // replace digitalRead() with Direct Port Reads.
    // reduces footprint ~100 bytes => portability issue?
    // direct port read is about 3x faster
	uint8_t bit = digitalPinToBitMask(pin);
	uint8_t port = digitalPinToPort(pin);
    volatile uint8_t *PIR = portInputRegister(port);

    // EMPTY BUFFER
    for (uint8_t i = 0; i < 5; i++) bits[i] = 0;

    // REQUEST SAMPLE
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW); // T-be
    delay(wakeupDelay);
    digitalWrite(pin, HIGH);   // T-go
    delayMicroseconds(40);
    pinMode(pin, INPUT);

    // GET ACKNOWLEDGE or TIMEOUT
    uint16_t loopCntLOW = DHTLIB_TIMEOUT;
    while ((*PIR & bit) == LOW )  // T-rel
    {
        if (--loopCntLOW == 0) return DHTLIB_ERROR_TIMEOUT;
    }

    uint16_t loopCntHIGH = DHTLIB_TIMEOUT;
    while ((*PIR & bit) != LOW )  // T-reh
    {
        if (--loopCntHIGH == 0) return DHTLIB_ERROR_TIMEOUT;
    }

    // READ THE OUTPUT - 40 BITS => 5 BYTES
    for (uint8_t i = 40; i != 0; i--)
    {
        loopCntLOW = DHTLIB_TIMEOUT;
        while ((*PIR & bit) == LOW )
        {
            if (--loopCntLOW == 0) return DHTLIB_ERROR_TIMEOUT;
        }

        uint32_t t = micros();

        loopCntHIGH = DHTLIB_TIMEOUT;
        while ((*PIR & bit) != LOW )
        {
            if (--loopCntHIGH == 0) return DHTLIB_ERROR_TIMEOUT;
        }

        if ((micros() - t) > 40)
        {
            bits[idx] |= mask;
        }
        mask >>= 1;
        if (mask == 0)   // next byte?
        {
            mask = 128;
            idx++;
        }
    }

    return DHTLIB_OK;
}
//
// END OF FILE
//
<|endoftext|>


<commit_before>// RSXGL - Graphics library for the PS3 GPU.
//
// Copyright (c) 2011 Alexander Betts (alex.betts@gmail.com)
//
// get.cc - Implement glGet*() functions.

#include "rsxgl_context.h"

#include <GL3/gl3.h>

#if defined(GLAPI)
#undef GLAPI
#endif
#define GLAPI extern "C"

GLAPI void APIENTRY
glGetBooleanv (GLenum pname, GLboolean *params)
{
}

GLAPI void APIENTRY
glGetDoublev (GLenum pname, GLdouble *params)
{
}

GLAPI void APIENTRY
glGetFloatv (GLenum pname, GLfloat *params)
{
}

GLAPI void APIENTRY
glGetIntegerv (GLenum pname, GLint *params)
{
}

GLAPI void APIENTRY
glGetInteger64v (GLenum pname, GLint64 *params)
{
}
<commit_msg>Implemented glGetString functions.<commit_after>// RSXGL - Graphics library for the PS3 GPU.
//
// Copyright (c) 2011 Alexander Betts (alex.betts@gmail.com)
//
// get.cc - Implement glGet*() functions.

#include <GL3/gl3.h>

#include "rsxgl_context.h"
#include "error.h"

#if defined(GLAPI)
#undef GLAPI
#endif
#define GLAPI extern "C"

GLAPI void APIENTRY
glGetBooleanv (GLenum pname, GLboolean *params)
{
}

GLAPI void APIENTRY
glGetDoublev (GLenum pname, GLdouble *params)
{
}

GLAPI void APIENTRY
glGetFloatv (GLenum pname, GLfloat *params)
{
}

GLAPI void APIENTRY
glGetIntegerv (GLenum pname, GLint *params)
{
}

GLAPI void APIENTRY
glGetInteger64v (GLenum pname, GLint64 *params)
{
}

GLAPI const GLubyte * APIENTRY
glGetString (GLenum name)
{
  if(name == GL_VENDOR) {
    RSXGL_NOERROR((const GLubyte *)"RSXGL");
  }
  else if(name == GL_RENDERER) {
    RSXGL_NOERROR((const GLubyte *)"NV40");
  }
  else if(name == GL_VERSION) {
    RSXGL_NOERROR((const GLubyte *)"3.1");
  }
  else if(name == GL_SHADING_LANGUAGE_VERSION) {
    RSXGL_NOERROR((const GLubyte *)"1.30");
  }
  else if(name == GL_EXTENSIONS) {
    RSXGL_NOERROR((const GLubyte *)"");
  }
  else {
    RSXGL_ERROR(GL_INVALID_ENUM,0);
  }
}

GLAPI const GLubyte * APIENTRY
glGetStringi (GLenum name, GLuint index)
{
  if(name == GL_EXTENSIONS) {
    RSXGL_ERROR(GL_INVALID_VALUE,0);
  }
  else {
    RSXGL_ERROR(GL_INVALID_ENUM,0);
  }
}
<|endoftext|>


<commit_before>/*
 * StepQueue.cpp
 *
 *  Created on: Jan 20, 2015
 *      Author: Péter Fankhauser
 *   Institute: ETH Zurich, Autonomous Systems Lab
 */

#include "free_gait_core/step/StepQueue.hpp"

// STD
#include <stdexcept>

// Roco
#include <roco/log/log_messages.hpp>

namespace free_gait {

StepQueue::StepQueue()
    : active_(false),
      hasSwitchedStep_(false),
      hasStartedStep_(false)
{
  previousStep_.reset();
}

StepQueue::~StepQueue()
{
}

StepQueue::StepQueue(const StepQueue& other)
    : queue_(other.queue_),
      active_(other.active_)
{
  if (other.previousStep_) previousStep_ = std::move(other.previousStep_->clone());
}

void StepQueue::add(const Step& step)
{
  queue_.push_back(step);
}

void StepQueue::add(const std::vector<Step> steps)
{
  std::deque<Step>::iterator iterator = queue_.end();
  queue_.insert(iterator, steps.begin(), steps.end());
}

bool StepQueue::advance(double dt)
{
  // Check if empty.
  hasSwitchedStep_ = false;
  hasStartedStep_ = false;
  if (queue_.empty()) {
    active_ = false;
    return true;
  }

  // Special treatment of first step of queue.
  if (!active_) {
    active_ = true;
    hasSwitchedStep_ = true;
    return true;
  }

  // Check if step is updated (multi-threading).
  if (!queue_.front().isUpdated()) {
    if (queue_.front().update()) {
      hasStartedStep_ = true;
    } else {
      return true;
    }
  }

  // Advance current step.
  if (!queue_.front().advance(dt)) {
    // Step finished.
    previousStep_ = std::move(std::unique_ptr<Step>(new Step(queue_.front())));
    queue_.pop_front();
    if (queue_.empty()) {
      // End reached.
      active_ = false;
      return true;
    }
    hasSwitchedStep_ = true;
  }

  return true;
}

bool StepQueue::hasSwitchedStep() const
{
  return hasSwitchedStep_;
}

bool StepQueue::hasStartedStep() const
{
  return hasStartedStep_;
}

bool StepQueue::active() const
{
  if (empty()) return false;
  return queue_.front().isUpdated();
}

bool StepQueue::empty() const
{
  return queue_.empty();
}

void StepQueue::clearNextSteps()
{
  if (empty()) return;
  queue_.erase(queue_.begin() + 1, queue_.end());
}

void StepQueue::clear()
{
  previousStep_.reset();
  queue_.clear();
}

const Step& StepQueue::getCurrentStep() const
{
  if (empty()) throw std::out_of_range("StepQueue::getCurrentStep(): No steps in queue!");
  return queue_.front();
}

Step& StepQueue::getCurrentStep()
{
  if (empty()) throw std::out_of_range("StepQueue::getCurrentStep(): No steps in queue!");
  return queue_.front();
}

void StepQueue::replaceCurrentStep(const Step& step)
{
  queue_.pop_front();
  queue_.push_front(step);
}

const Step& StepQueue::getNextStep() const
{
  if (size() <= 1) throw std::out_of_range("StepQueue::getNextStep(): No next step in queue!");
  auto iterator = queue_.begin() + 1;
  return *iterator;
}

const std::deque<Step>& StepQueue::getQueue() const
{
  return queue_;
}

bool StepQueue::previousStepExists() const
{
 return (bool)previousStep_;
}

const Step& StepQueue::getPreviousStep() const
{
  if (!previousStep_) throw std::out_of_range("StepQueue::getPreviousStep(): No previous step available!");
  return *previousStep_;
}

std::deque<Step>::size_type StepQueue::size() const
{
  return queue_.size();
}

} /* namespace */
<commit_msg>Fixes #1.<commit_after>/*
 * StepQueue.cpp
 *
 *  Created on: Jan 20, 2015
 *      Author: Péter Fankhauser
 *   Institute: ETH Zurich, Autonomous Systems Lab
 */

#include "free_gait_core/step/StepQueue.hpp"

// STD
#include <stdexcept>

// Roco
#include <roco/log/log_messages.hpp>

namespace free_gait {

StepQueue::StepQueue()
    : active_(false),
      hasSwitchedStep_(false),
      hasStartedStep_(false)
{
  previousStep_.reset();
}

StepQueue::~StepQueue()
{
}

StepQueue::StepQueue(const StepQueue& other)
    : queue_(other.queue_),
      active_(other.active_)
{
  if (other.previousStep_) previousStep_ = std::move(other.previousStep_->clone());
}

void StepQueue::add(const Step& step)
{
  queue_.push_back(step);
}

void StepQueue::add(const std::vector<Step> steps)
{
  std::deque<Step>::iterator iterator = queue_.end();
  queue_.insert(iterator, steps.begin(), steps.end());
}

bool StepQueue::advance(double dt)
{
  // Check if empty.
  hasSwitchedStep_ = false;
  hasStartedStep_ = false;
  if (queue_.empty()) {
    active_ = false;
    return true;
  }

  // Special treatment of first step of queue.
  if (!active_) {
    active_ = true;
    hasSwitchedStep_ = true;
    return true;
  }

  // Check if step is updated (multi-threading).
  if (!queue_.front().isUpdated()) {
    if (queue_.front().update()) {
      hasStartedStep_ = true;
    } else {
      return true;
    }
  }

  // Advance current step.
  if (!queue_.front().advance(dt)) {
    // Step finished.
    previousStep_ = std::move(std::unique_ptr<Step>(new Step(queue_.front())));
    queue_.pop_front();
    if (queue_.empty()) {
      // End reached.
      active_ = false;
      hasStartedStep_ = false;
      return true;
    }
    hasSwitchedStep_ = true;
  }

  return true;
}

bool StepQueue::hasSwitchedStep() const
{
  return hasSwitchedStep_;
}

bool StepQueue::hasStartedStep() const
{
  return hasStartedStep_;
}

bool StepQueue::active() const
{
  if (empty()) return false;
  return queue_.front().isUpdated();
}

bool StepQueue::empty() const
{
  return queue_.empty();
}

void StepQueue::clearNextSteps()
{
  if (empty()) return;
  queue_.erase(queue_.begin() + 1, queue_.end());
}

void StepQueue::clear()
{
  previousStep_.reset();
  queue_.clear();
}

const Step& StepQueue::getCurrentStep() const
{
  if (empty()) throw std::out_of_range("StepQueue::getCurrentStep(): No steps in queue!");
  return queue_.front();
}

Step& StepQueue::getCurrentStep()
{
  if (empty()) throw std::out_of_range("StepQueue::getCurrentStep(): No steps in queue!");
  return queue_.front();
}

void StepQueue::replaceCurrentStep(const Step& step)
{
  queue_.pop_front();
  queue_.push_front(step);
}

const Step& StepQueue::getNextStep() const
{
  if (size() <= 1) throw std::out_of_range("StepQueue::getNextStep(): No next step in queue!");
  auto iterator = queue_.begin() + 1;
  return *iterator;
}

const std::deque<Step>& StepQueue::getQueue() const
{
  return queue_;
}

bool StepQueue::previousStepExists() const
{
 return (bool)previousStep_;
}

const Step& StepQueue::getPreviousStep() const
{
  if (!previousStep_) throw std::out_of_range("StepQueue::getPreviousStep(): No previous step available!");
  return *previousStep_;
}

std::deque<Step>::size_type StepQueue::size() const
{
  return queue_.size();
}

} /* namespace */
<|endoftext|>


<commit_before>#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/CheckerRegistry.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"

using namespace clang;
using namespace ento;

namespace {
class MainCallChecker : public Checker < check::PreStmt<CallExpr> > {
  mutable OwningPtr<BugType> BT;

public:
  void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
};
} // end anonymous namespace

void MainCallChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
  const ProgramStateRef state = C.getState();
  const LocationContext *LC = C.getLocationContext();
  const Expr *Callee = CE->getCallee();
  const FunctionDecl *FD = state->getSVal(Callee, LC).getAsFunctionDecl();

  if (!FD)
    return;

  // Get the name of the callee.
  IdentifierInfo *II = FD->getIdentifier();
  if (!II)   // if no identifier, not a simple C function
    return;

  if (II->isStr("main")) {
    ExplodedNode *N = C.generateSink();
    if (!N)
      return;

    if (!BT)
      BT.reset(new BugType("call to main", "example analyzer plugin"));

    BugReport *report = new BugReport(*BT, BT->getName(), N);
    report->addRange(Callee->getSourceRange());
    C.EmitReport(report);
  }
}

// Register plugin!
extern "C"
void clang_registerCheckers (CheckerRegistry &registry) {
  registry.addChecker<MainCallChecker>("example.MainCallChecker", "Disallows calls to functions called main");
}

extern "C"
const char clang_analyzerAPIVersionString[] = CLANG_ANALYZER_API_VERSION_STRING;
<commit_msg>analyzer-plugin/MainCallChecker.cpp: Fixup corresponding to r167275.<commit_after>#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/CheckerRegistry.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"

using namespace clang;
using namespace ento;

namespace {
class MainCallChecker : public Checker < check::PreStmt<CallExpr> > {
  mutable OwningPtr<BugType> BT;

public:
  void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
};
} // end anonymous namespace

void MainCallChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
  const ProgramStateRef state = C.getState();
  const LocationContext *LC = C.getLocationContext();
  const Expr *Callee = CE->getCallee();
  const FunctionDecl *FD = state->getSVal(Callee, LC).getAsFunctionDecl();

  if (!FD)
    return;

  // Get the name of the callee.
  IdentifierInfo *II = FD->getIdentifier();
  if (!II)   // if no identifier, not a simple C function
    return;

  if (II->isStr("main")) {
    ExplodedNode *N = C.generateSink();
    if (!N)
      return;

    if (!BT)
      BT.reset(new BugType("call to main", "example analyzer plugin"));

    BugReport *report = new BugReport(*BT, BT->getName(), N);
    report->addRange(Callee->getSourceRange());
    C.emitReport(report);
  }
}

// Register plugin!
extern "C"
void clang_registerCheckers (CheckerRegistry &registry) {
  registry.addChecker<MainCallChecker>("example.MainCallChecker", "Disallows calls to functions called main");
}

extern "C"
const char clang_analyzerAPIVersionString[] = CLANG_ANALYZER_API_VERSION_STRING;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013, Timothy Stack
 *
 * 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 Timothy Stack 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 REGENTS 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 REGENTS 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.
 *
 * @file lnav_config.cc
 */

#include "config.h"

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#include "lnav_config.hh"

using namespace std;

string dotlnav_path(const char *sub)
{
    string retval;
    char * home;

    home = getenv("HOME");
    if (home) {
        char hpath[PATH_MAX];

        snprintf(hpath, sizeof(hpath), "%s/.lnav/%s", home, sub);
        retval = hpath;
    }
    else {
        retval = sub;
    }

    return retval;
}

bool check_experimental(const char *feature_name)
{
    const char *env_value = getenv("LNAV_EXP");

    assert(feature_name != NULL);

    if (env_value && strcasestr(env_value, feature_name)) {
        return true;
    }

    return false;
}

void ensure_dotlnav(void)
{
    string path = dotlnav_path("");

    if (!path.empty()) {
        mkdir(path.c_str(), 0755);
    }
}
<commit_msg>[build] oops...<commit_after>/**
 * Copyright (c) 2013, Timothy Stack
 *
 * 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 Timothy Stack 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 REGENTS 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 REGENTS 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.
 *
 * @file lnav_config.cc
 */

#include "config.h"

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#include "lnav_config.hh"

using namespace std;

string dotlnav_path(const char *sub)
{
    string retval;
    char * home;

    home = getenv("HOME");
    if (home) {
        char hpath[2048];

        snprintf(hpath, sizeof(hpath), "%s/.lnav/%s", home, sub);
        retval = hpath;
    }
    else {
        retval = sub;
    }

    return retval;
}

bool check_experimental(const char *feature_name)
{
    const char *env_value = getenv("LNAV_EXP");

    assert(feature_name != NULL);

    if (env_value && strcasestr(env_value, feature_name)) {
        return true;
    }

    return false;
}

void ensure_dotlnav(void)
{
    string path = dotlnav_path("");

    if (!path.empty()) {
        mkdir(path.c_str(), 0755);
    }
}
<|endoftext|>


<commit_before>/*
 *
 *      Copyright (c) 2010 <iBotics -- www.sdibotics.org>
 *      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 Stingray, iBotics nor the names of its
 *        contributors may be used to endorse or promote products derived from
 *        this software without specific prior written permission.
 *
 *      THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *      "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *      LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *      A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *      OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *      SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *      LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *      DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *      THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *      (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *      OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "locomotion_module/locomotion_module.h"

int main(int argc, char **argv)
{
  // Set up ROS.
  ros::init(argc, argv, "locom");
  ros::NodeHandle nh;

  // Create a new NodeExample object.
  LocomotionModule *locomotion_module = new LocomotionModule();

  // Set up a dynamic reconfigure server.
  // Do this before parameter server, else some of the parameter server
  // values can be overwritten.
  dynamic_reconfigure::Server<locomotion_module::locomotionModuleConfig> dr_srv;
  dynamic_reconfigure::Server<locomotion_module::locomotionModuleConfig>::CallbackType cb;
  cb = boost::bind(&LocomotionModule::configCallback, locomotion_module, _1, _2);
  dr_srv.setCallback(cb);

  // Declare variables that can be modified by launch file or command line.

  // Initialize node parameters from launch file or command line.
  // Use a private node handle so that multiple instances of the node can be run simultaneously
  // while using different parameters.
  //ros::NodeHandle pnh("~");
  //pnh.param("r", locomotion_module->r_, .1);

  ROS_INFO("r %f",locomotion_module->r_);
  // Create a publisher and name the topic.
  //use floats
  locomotion_module->pub_left = nh.advertise<std_msgs::Float32>("velLeft", 10);
  locomotion_module->pub_right = nh.advertise<std_msgs::Float32>("velRight", 10);

  ros::Subscriber sub_message = nh.subscribe("cmd_vel", 1000, &LocomotionModule::messageCallback, locomotion_module);
  ros::spin();
  // Main loop.
  // while (nh.ok())
  // {
  //   // Publish the message. Do this in the callback for subscribing?

  //   ros::spinOnce();
  //   //r.sleep();
  // }

  return 0;
} // end main()
<commit_msg>while loop<commit_after>/*
 *
 *      Copyright (c) 2010 <iBotics -- www.sdibotics.org>
 *      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 Stingray, iBotics nor the names of its
 *        contributors may be used to endorse or promote products derived from
 *        this software without specific prior written permission.
 *
 *      THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *      "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *      LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *      A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *      OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *      SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *      LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *      DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *      THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *      (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *      OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "locomotion_module/locomotion_module.h"

int main(int argc, char **argv)
{
  // Set up ROS.
  ros::init(argc, argv, "locom");
  ros::NodeHandle nh;

  // Create a new NodeExample object.
  LocomotionModule *locomotion_module = new LocomotionModule();

  // Set up a dynamic reconfigure server.
  // Do this before parameter server, else some of the parameter server
  // values can be overwritten.
  dynamic_reconfigure::Server<locomotion_module::locomotionModuleConfig> dr_srv;
  dynamic_reconfigure::Server<locomotion_module::locomotionModuleConfig>::CallbackType cb;
  cb = boost::bind(&LocomotionModule::configCallback, locomotion_module, _1, _2);
  dr_srv.setCallback(cb);

  // Declare variables that can be modified by launch file or command line.

  // Initialize node parameters from launch file or command line.
  // Use a private node handle so that multiple instances of the node can be run simultaneously
  // while using different parameters.
  //ros::NodeHandle pnh("~");
  //pnh.param("r", locomotion_module->r_, .1);

  ROS_INFO("r %f",locomotion_module->r_);
  // Create a publisher and name the topic.
  //use floats
  locomotion_module->pub_left = nh.advertise<std_msgs::Float32>("velLeft", 10);
  locomotion_module->pub_right = nh.advertise<std_msgs::Float32>("velRight", 10);

  ros::Subscriber sub_message = nh.subscribe("cmd_vel", 1000, &LocomotionModule::messageCallback, locomotion_module);
  //ros::spin();
  // Main loop.
   while (nh.ok())
   {
  //   // Publish the message. Do this in the callback for subscribing?
     ROS_INFO("R is %f",locomotion_module->r_);
     ros::spinOnce();
  //   //r.sleep();
   }

  return 0;
} // end main()
<|endoftext|>


<commit_before>/** @file
    @brief Wrapper for a vrpn_Tracker_VideoBasedHMDTracker

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Internal Includes
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/PluginKit/TrackerInterfaceC.h>

// Generated JSON header file
#include "com_osvr_VideoBasedHMDTracker_json.h"

// Library/third-party includes
#include <opencv2/core/core.hpp> // for basic OpenCV types
#include <opencv2/core/operations.hpp>
#include <opencv2/highgui/highgui.hpp> // for image capture
#include <opencv2/imgproc/imgproc.hpp> // for image scaling

#include <boost/noncopyable.hpp>

// Standard includes
#include <iostream>
#include <sstream>

// Anonymous namespace to avoid symbol collision
namespace {

class VideoBasedHMDTracker : boost::noncopyable {
  public:
      VideoBasedHMDTracker(OSVR_PluginRegContext ctx, int cameraNum = 0, int channel = 0)
          : m_camera(cameraNum), m_channel(channel) {

        /// Create the initialization options
        OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);

        // Configure the tracker interface.
        osvrDeviceTrackerConfigure(opts, &m_tracker);

        /// Come up with a device name
        std::ostringstream os;
        os << "TrackedCamera" << cameraNum << "_" << channel;

        /// Create an asynchronous (threaded) device
        m_dev.initAsync(ctx, os.str(), opts);

        /// Send JSON descriptor
        m_dev.sendJsonDescriptor(
            com_osvr_VideoBasedHMDTracker_json);

        /// Register update callback
        m_dev.registerUpdateCallback(this);
      }

    OSVR_ReturnCode update() {
        if (!m_camera.isOpened()) {
            // Couldn't open the camera.  Failing silently for now. Maybe the
            // camera will be plugged back in later.
            return OSVR_RETURN_SUCCESS;
        }

        // Trigger a camera grab.
        bool grabbed = m_camera.grab();
        if (!grabbed) {
            // No frame available.
            return OSVR_RETURN_SUCCESS;
        }
        bool retrieved = m_camera.retrieve(m_frame, m_channel);
        if (!retrieved) {
            return OSVR_RETURN_FAILURE;
        }

        // Keep track of when we got the image, since that is our
        // best estimate for when the tracker was at the specified
        // pose.
        OSVR_TimeValue timestamp;
        osvrTimeValueGetNow(&timestamp);

        // Compute the pose of the HMD w.r.t. the camera frame of reference.
        OSVR_PoseState pose;
        osvrPose3SetIdentity(&pose);
        // XXX Compute pose here.

        /// Report the new pose, time-stamped with the time we
        // received the image from the camera.
        osvrDeviceTrackerSendPoseTimestamped(m_dev, m_tracker,
            &pose, 0, &timestamp);
        return OSVR_RETURN_SUCCESS;
    }

  private:
    osvr::pluginkit::DeviceToken m_dev;
    OSVR_TrackerDeviceInterface m_tracker;
    cv::VideoCapture m_camera;
    int m_channel;
    cv::Mat m_frame;
    cv::Mat m_scaledFrame;
};

class HardwareDetection {
  public:
    HardwareDetection() : m_found(false) {}

    OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {
        if (m_found) {
            return OSVR_RETURN_SUCCESS;
        }

        {
            // Autodetect camera
            cv::VideoCapture cap(0);
            if (!cap.isOpened()) {
                // Failed to find camera
                return OSVR_RETURN_FAILURE;
            }
        }

        m_found = true;

        /// Create our device object, passing the context, and register
        /// the function to call
        osvr::pluginkit::registerObjectForDeletion(ctx, new VideoBasedHMDTracker(ctx));

        return OSVR_RETURN_SUCCESS;
    }

  private:
    /// @brief Have we found our device yet? (this limits the plugin to one
    /// instance)
    bool m_found;
};
} // namespace

OSVR_PLUGIN(com_osvr_VideoBasedHMDTracker) {
    osvr::pluginkit::PluginContext context(ctx);

    /// Register a detection callback function object.
    context.registerHardwareDetectCallback(new HardwareDetection());

    return OSVR_RETURN_SUCCESS;
}

<commit_msg>Added debugging window displaying video so I can figure out when the formatting for the Oculus camera is set correctly.<commit_after>/** @file
    @brief Wrapper for a vrpn_Tracker_VideoBasedHMDTracker

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Internal Includes
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/PluginKit/TrackerInterfaceC.h>

// Generated JSON header file
#include "com_osvr_VideoBasedHMDTracker_json.h"

// Library/third-party includes
#include <opencv2/core/core.hpp> // for basic OpenCV types
#include <opencv2/core/operations.hpp>
#include <opencv2/highgui/highgui.hpp> // for image capture
#include <opencv2/imgproc/imgproc.hpp> // for image scaling

#include <boost/noncopyable.hpp>

// Standard includes
#include <iostream>
#include <sstream>

#define VBHMD_DEBUG

// Anonymous namespace to avoid symbol collision
namespace {

class VideoBasedHMDTracker : boost::noncopyable {
  public:
      VideoBasedHMDTracker(OSVR_PluginRegContext ctx, int cameraNum = 0, int channel = 0)
          : m_camera(cameraNum), m_channel(channel) {

        /// Create the initialization options
        OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);

        // Configure the tracker interface.
        osvrDeviceTrackerConfigure(opts, &m_tracker);

        /// Come up with a device name
        std::ostringstream os;
        os << "TrackedCamera" << cameraNum << "_" << channel;

        /// Create an asynchronous (threaded) device
        m_dev.initAsync(ctx, os.str(), opts);

        /// Send JSON descriptor
        m_dev.sendJsonDescriptor(
            com_osvr_VideoBasedHMDTracker_json);

        /// Register update callback
        m_dev.registerUpdateCallback(this);
      }

    OSVR_ReturnCode update() {
        if (!m_camera.isOpened()) {
            // Couldn't open the camera.  Failing silently for now. Maybe the
            // camera will be plugged back in later.
            return OSVR_RETURN_SUCCESS;
        }

        // Trigger a camera grab.
        bool grabbed = m_camera.grab();
        if (!grabbed) {
            // No frame available.
            return OSVR_RETURN_SUCCESS;
        }
        bool retrieved = m_camera.retrieve(m_frame, m_channel);
        if (!retrieved) {
            return OSVR_RETURN_FAILURE;
        }

        // Keep track of when we got the image, since that is our
        // best estimate for when the tracker was at the specified
        // pose.
        OSVR_TimeValue timestamp;
        osvrTimeValueGetNow(&timestamp);

#ifdef VBHMD_DEBUG
        if (m_camera.isOpened()) {
            cv::imshow("Debug window", m_frame);
            cv::waitKey(1);
        }
#endif

        // Compute the pose of the HMD w.r.t. the camera frame of reference.
        OSVR_PoseState pose;
        osvrPose3SetIdentity(&pose);
        // XXX Compute pose here.

        /// Report the new pose, time-stamped with the time we
        // received the image from the camera.
        osvrDeviceTrackerSendPoseTimestamped(m_dev, m_tracker,
            &pose, 0, &timestamp);
        return OSVR_RETURN_SUCCESS;
    }

  private:
    osvr::pluginkit::DeviceToken m_dev;
    OSVR_TrackerDeviceInterface m_tracker;
    cv::VideoCapture m_camera;
    int m_channel;
    cv::Mat m_frame;
    cv::Mat m_scaledFrame;
};

class HardwareDetection {
  public:
    HardwareDetection() : m_found(false) {}

    OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {
        if (m_found) {
            return OSVR_RETURN_SUCCESS;
        }

        {
            // Autodetect camera.  This needs to have the same
            // parameter as the constructor for the VideoBasedHMDTracker
            // class above or else it will not be looking for the
            // same camera.  This instance of the camera will auto-
            // delete itself when this block finishes, so should
            // close the camera -- leaving it to be opened again
            // in the constructor.
            cv::VideoCapture cap(0);
            if (!cap.isOpened()) {
                // Failed to find camera
                return OSVR_RETURN_FAILURE;
            }
        }
        m_found = true;

        /// Create our device object, passing the context.
        osvr::pluginkit::registerObjectForDeletion(ctx, new VideoBasedHMDTracker(ctx));

        return OSVR_RETURN_SUCCESS;
    }

  private:
    /// @brief Have we found our device yet? (this limits the plugin to one
    /// instance, so that only one tracker will use this camera.)
    bool m_found;
};
} // namespace

OSVR_PLUGIN(com_osvr_VideoBasedHMDTracker) {
    osvr::pluginkit::PluginContext context(ctx);

    /// Register a detection callback function object.
    context.registerHardwareDetectCallback(new HardwareDetection());

    return OSVR_RETURN_SUCCESS;
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * 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 <cmath>

#include <android/log.h>
#include <android_native_app_glue.h>

#include <pio/gpio.h>
#include <pio/peripheral_manager_client.h>

#include "AndroidSystemProperties.h"

const int BLINK_INTERVAL_MS = 1000;
const char* TAG = "blink";

#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
#define ASSERT(cond, ...) if (!(cond)) { __android_log_assert(#cond, TAG, __VA_ARGS__);}

void android_main(android_app* app) {
    app_dummy(); // prevent native-app-glue to be stripped.

    AndroidSystemProperties systemProperties(app->activity);
    const char* LED_GPIO;
    if (systemProperties.getBuildDevice() == "rpi3") {
        LED_GPIO = "BCM6";
    } else {
        LOGE("unsupported device: %s", systemProperties.getBuildDevice().c_str());
        return;
    }

    APeripheralManagerClient* client = APeripheralManagerClient_new();
    ASSERT(client, "failed to open peripheral manager client");
    AGpio* gpio;
    APeripheralManagerClient_openGpio(client, LED_GPIO, &gpio);
    ASSERT(gpio, "failed to open GPIO: %s", LED_GPIO);
    int result = AGpio_setDirection(gpio, AGPIO_DIRECTION_OUT_INITIALLY_LOW);
    ASSERT(result == 0, "failed to set direction for GPIO: %s", LED_GPIO);

    while (!app->destroyRequested) {
        int gpioValue;
        if (AGpio_getValue(gpio, &gpioValue) < 0) {
            LOGE("failed to get value for GPIO: %s", LED_GPIO);
            continue; // retry immediately
        }
        if (AGpio_setValue(gpio, !gpioValue) < 0) {
            LOGE("failed to set value for GPIO: %s", LED_GPIO);
            continue; // retry immediately
        }
        android_poll_source* source;
        // wait for at most BLINK_INTERVAL_MS.
        // proper control loop implementation would also account for the time spent handling
        // lifecycle and input events.
        int pollResult = ALooper_pollOnce(BLINK_INTERVAL_MS, NULL, NULL, (void**)&source);
        if (pollResult >= 0) {
            if (source != NULL) {
                // forward event to native-app-glue to handle lifecycle and input event
                // and update `app` state.
                source->process(app, source);
            }
        }
    }
    AGpio_delete(gpio);
    APeripheralManagerClient_delete(client);
}
<commit_msg>sample-nativepio/blink: fix error handling<commit_after>/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * 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 <cmath>

#include <android/log.h>
#include <android_native_app_glue.h>

#include <pio/gpio.h>
#include <pio/peripheral_manager_client.h>

#include "AndroidSystemProperties.h"

const char* TAG = "blink";
const int BLINK_INTERVAL_MS = 1000;

#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
#define ASSERT(cond, ...) if (!(cond)) { __android_log_assert(#cond, TAG, __VA_ARGS__);}

void android_main(android_app* app) {
    app_dummy(); // prevent native-app-glue to be stripped.

    AndroidSystemProperties systemProperties(app->activity);
    const char* LED_GPIO;
    if (systemProperties.getBuildDevice() == "rpi3") {
        LED_GPIO = "BCM6";
    } else {
        LOGE("unsupported device: %s", systemProperties.getBuildDevice().c_str());
        return;
    }

    APeripheralManagerClient* client = APeripheralManagerClient_new();
    ASSERT(client, "failed to open peripheral manager client");
    AGpio* gpio;
    APeripheralManagerClient_openGpio(client, LED_GPIO, &gpio);
    ASSERT(gpio, "failed to open GPIO: %s", LED_GPIO);
    int result = AGpio_setDirection(gpio, AGPIO_DIRECTION_OUT_INITIALLY_LOW);
    ASSERT(result == 0, "failed to set direction for GPIO: %s", LED_GPIO);

    while (!app->destroyRequested) {
        int gpioValue;
        if (AGpio_getValue(gpio, &gpioValue) != 0) {
            LOGE("failed to get value for GPIO: %s", LED_GPIO);
            continue; // retry immediately
        }
        if (AGpio_setValue(gpio, !gpioValue) != 0) {
            LOGE("failed to set value for GPIO: %s", LED_GPIO);
            continue; // retry immediately
        }
        android_poll_source* source;
        // wait for at most BLINK_INTERVAL_MS.
        // proper control loop implementation would also account for the time spent handling
        // lifecycle and input events.
        int pollResult = ALooper_pollOnce(BLINK_INTERVAL_MS, NULL, NULL, (void**)&source);
        if (pollResult >= 0) {
            if (source != NULL) {
                // forward event to native-app-glue to handle lifecycle and input event
                // and update `app` state.
                source->process(app, source);
            }
        }
    }
    AGpio_delete(gpio);
    APeripheralManagerClient_delete(client);
}
<|endoftext|>


<commit_before>/* Copyright (c) 2020 PaddlePaddle 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 "paddle/fluid/operators/amp/update_loss_scaling_op.h"
#include <cstring>
#include <string>
#include <vector>
#include "paddle/fluid/framework/op_registry.h"

namespace paddle {
namespace operators {

class UpdateLossScalingOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    OP_INOUT_CHECK(ctx->HasInputs("X"), "Input", "X", "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasInput("FoundInfinite"), "Input", "FoundInfinite",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasInput("PrevLossScaling"), "Input", "PrevLossScaling",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasInput("InGoodSteps"), "Input", "InGoodSteps",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasInput("InBadSteps"), "Input", "InBadSteps",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasOutputs("Out"), "Output", "Out",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasOutput("LossScaling"), "Output", "LossScaling",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasOutput("OutGoodSteps"), "Output", "OutGoodSteps",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasOutput("OutBadSteps"), "Output", "OutBadSteps",
                   "update_loss_scaling");
    auto x_dims = ctx->GetInputsDim("X");
    ctx->SetOutputsDim("Out", x_dims);
    ctx->SetOutputDim("LossScaling", {1});
    ctx->SetOutputDim("OutGoodSteps", {1});
    ctx->SetOutputDim("OutBadSteps", {1});
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "PrevLossScaling"),
        ctx.device_context());
  }
};

class UpdateLossScalingOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "(Tensors) The input tensors of update_loss_scaling operator.")
        .AsDuplicable();
    AddInput("FoundInfinite",
             "(Tensor) 1-dim tensor, contains a bool scalar, which indicates "
             "whether there is any infinite gradient.");
    AddInput("PrevLossScaling",
             "(Tensor) 1-dim tensor, previous loss scaling.");
    AddInput("InGoodSteps",
             "(Tensor) 1-dim tensor, accumulates good steps in which all "
             "gradients are finite.");
    AddInput("InBadSteps",
             "(Tensor) 1-dim tensor, accumulates bad steps in which some "
             "gradients are infinite.");
    AddOutput("Out",
              "(Tensors) The output tensor of update_loss_scaling operator.")
        .AsDuplicable();
    AddOutput("LossScaling", "(Tensor) 1-dim tensor, updated loss scaling.");
    AddOutput("OutGoodSteps", "(Tensor) 1-dim tensor, pdated good steps.");
    AddOutput("OutBadSteps", "(Tensor) 1-dim tensor, updated bad steps.");
    AddAttr<int>("incr_every_n_steps",
                 "A value represents increasing loss scaling every n "
                 "consecutive steps with finite gradients.");
    AddAttr<int>("decr_every_n_nan_or_inf",
                 "A value represents decreasing loss scaling every n "
                 "accumulated steps with nan or inf gradients.");
    AddAttr<float>("incr_ratio",
                   "The multiplier to use when increasing the loss scaling.")
        .AddCustomChecker([](float incr_ratio) {
          PADDLE_ENFORCE_EQ(incr_ratio > 1.0f, true,
                            platform::errors::InvalidArgument(
                                "'incr_ratio' should be greater than 1, but "
                                "the received is %f",
                                incr_ratio));
        });
    AddAttr<float>(
        "decr_ratio",
        "The less-than-one-multiplier to use when decreasing loss scaling.")
        .AddCustomChecker([](float decr_ratio) {
          PADDLE_ENFORCE_EQ(decr_ratio > 0.0f && decr_ratio < 1.0f, true,
                            platform::errors::InvalidArgument(
                                "'incr_ratio' should be between 0 and 1, but "
                                "the received is %f",
                                decr_ratio));
        });
    AddComment(R"DOC(
Update loss scaling according to overall gradients. If all gradients is
finite after incr_every_n_steps, loss scaling will increase by incr_ratio.
Otherwise, loss scaling will decrease by decr_ratio after
decr_every_n_nan_or_inf steps and each step some gradients are infinite.

)DOC");
  }
};

template <typename T>
class UpdateLossScalingFunctor<platform::CPUDeviceContext, T> {
 public:
  void operator()(const platform::CPUDeviceContext& ctx,
                  const bool* found_inf_data, const T* pre_loss_scaling_data,
                  const int* good_in_data, const int* bad_in_data,
                  const int incr_every_n_steps,
                  const int decr_every_n_nan_or_inf, const float incr_ratio,
                  const float decr_ratio, T* updated_loss_scaling_data,
                  int* good_out_data, int* bad_out_data) const {
    Update<T>(found_inf_data, pre_loss_scaling_data, good_in_data, bad_in_data,
              incr_every_n_steps, decr_every_n_nan_or_inf, incr_ratio,
              decr_ratio, updated_loss_scaling_data, good_out_data,
              bad_out_data);
  }
};

template <typename T>
class LazyZeroInputs<platform::CPUDeviceContext, T> {
 public:
  void operator()(const platform::CPUDeviceContext& dev_ctx,
                  const bool* found_inf_data,
                  const std::vector<const framework::Tensor*>& xs,
                  const std::vector<framework::Tensor*>& outs) const {
    if (*found_inf_data) {
      VLOG(1) << "-- UpdateLossScaling: Infinite values are found in grads. --";
      for (size_t i = 0; i < xs.size(); ++i) {
        auto* out = outs[i];
        T* out_data = out->mutable_data<T>(dev_ctx.GetPlace());
        int num = out->numel();
        std::memset(out_data, 0, num * sizeof(T));
      }
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
using CPU = paddle::platform::CPUDeviceContext;

REGISTER_OPERATOR(
    update_loss_scaling, ops::UpdateLossScalingOp,
    ops::UpdateLossScalingOpMaker,
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);

REGISTER_OP_CPU_KERNEL(update_loss_scaling,
                       ops::UpdateLossScalingKernel<CPU, float>,
                       ops::UpdateLossScalingKernel<CPU, double>);
<commit_msg>fix error message showing in UpdateLossScalingOp (#27596)<commit_after>/* Copyright (c) 2020 PaddlePaddle 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 "paddle/fluid/operators/amp/update_loss_scaling_op.h"
#include <cstring>
#include <string>
#include <vector>
#include "paddle/fluid/framework/op_registry.h"

namespace paddle {
namespace operators {

class UpdateLossScalingOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    OP_INOUT_CHECK(ctx->HasInputs("X"), "Input", "X", "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasInput("FoundInfinite"), "Input", "FoundInfinite",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasInput("PrevLossScaling"), "Input", "PrevLossScaling",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasInput("InGoodSteps"), "Input", "InGoodSteps",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasInput("InBadSteps"), "Input", "InBadSteps",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasOutputs("Out"), "Output", "Out",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasOutput("LossScaling"), "Output", "LossScaling",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasOutput("OutGoodSteps"), "Output", "OutGoodSteps",
                   "update_loss_scaling");
    OP_INOUT_CHECK(ctx->HasOutput("OutBadSteps"), "Output", "OutBadSteps",
                   "update_loss_scaling");
    auto x_dims = ctx->GetInputsDim("X");
    ctx->SetOutputsDim("Out", x_dims);
    ctx->SetOutputDim("LossScaling", {1});
    ctx->SetOutputDim("OutGoodSteps", {1});
    ctx->SetOutputDim("OutBadSteps", {1});
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "PrevLossScaling"),
        ctx.device_context());
  }
};

class UpdateLossScalingOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "(Tensors) The input tensors of update_loss_scaling operator.")
        .AsDuplicable();
    AddInput("FoundInfinite",
             "(Tensor) 1-dim tensor, contains a bool scalar, which indicates "
             "whether there is any infinite gradient.");
    AddInput("PrevLossScaling",
             "(Tensor) 1-dim tensor, previous loss scaling.");
    AddInput("InGoodSteps",
             "(Tensor) 1-dim tensor, accumulates good steps in which all "
             "gradients are finite.");
    AddInput("InBadSteps",
             "(Tensor) 1-dim tensor, accumulates bad steps in which some "
             "gradients are infinite.");
    AddOutput("Out",
              "(Tensors) The output tensor of update_loss_scaling operator.")
        .AsDuplicable();
    AddOutput("LossScaling", "(Tensor) 1-dim tensor, updated loss scaling.");
    AddOutput("OutGoodSteps", "(Tensor) 1-dim tensor, pdated good steps.");
    AddOutput("OutBadSteps", "(Tensor) 1-dim tensor, updated bad steps.");
    AddAttr<int>("incr_every_n_steps",
                 "A value represents increasing loss scaling every n "
                 "consecutive steps with finite gradients.");
    AddAttr<int>("decr_every_n_nan_or_inf",
                 "A value represents decreasing loss scaling every n "
                 "accumulated steps with nan or inf gradients.");
    AddAttr<float>("incr_ratio",
                   "The multiplier to use when increasing the loss scaling.")
        .AddCustomChecker([](float incr_ratio) {
          PADDLE_ENFORCE_EQ(incr_ratio > 1.0f, true,
                            platform::errors::InvalidArgument(
                                "'incr_ratio' should be greater than 1, but "
                                "the received is %f",
                                incr_ratio));
        });
    AddAttr<float>(
        "decr_ratio",
        "The less-than-one-multiplier to use when decreasing loss scaling.")
        .AddCustomChecker([](float decr_ratio) {
          PADDLE_ENFORCE_EQ(decr_ratio > 0.0f && decr_ratio < 1.0f, true,
                            platform::errors::InvalidArgument(
                                "'decr_ratio' should be between 0 and 1, but "
                                "the received is %f",
                                decr_ratio));
        });
    AddComment(R"DOC(
Update loss scaling according to overall gradients. If all gradients is
finite after incr_every_n_steps, loss scaling will increase by incr_ratio.
Otherwise, loss scaling will decrease by decr_ratio after
decr_every_n_nan_or_inf steps and each step some gradients are infinite.

)DOC");
  }
};

template <typename T>
class UpdateLossScalingFunctor<platform::CPUDeviceContext, T> {
 public:
  void operator()(const platform::CPUDeviceContext& ctx,
                  const bool* found_inf_data, const T* pre_loss_scaling_data,
                  const int* good_in_data, const int* bad_in_data,
                  const int incr_every_n_steps,
                  const int decr_every_n_nan_or_inf, const float incr_ratio,
                  const float decr_ratio, T* updated_loss_scaling_data,
                  int* good_out_data, int* bad_out_data) const {
    Update<T>(found_inf_data, pre_loss_scaling_data, good_in_data, bad_in_data,
              incr_every_n_steps, decr_every_n_nan_or_inf, incr_ratio,
              decr_ratio, updated_loss_scaling_data, good_out_data,
              bad_out_data);
  }
};

template <typename T>
class LazyZeroInputs<platform::CPUDeviceContext, T> {
 public:
  void operator()(const platform::CPUDeviceContext& dev_ctx,
                  const bool* found_inf_data,
                  const std::vector<const framework::Tensor*>& xs,
                  const std::vector<framework::Tensor*>& outs) const {
    if (*found_inf_data) {
      VLOG(1) << "-- UpdateLossScaling: Infinite values are found in grads. --";
      for (size_t i = 0; i < xs.size(); ++i) {
        auto* out = outs[i];
        T* out_data = out->mutable_data<T>(dev_ctx.GetPlace());
        int num = out->numel();
        std::memset(out_data, 0, num * sizeof(T));
      }
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
using CPU = paddle::platform::CPUDeviceContext;

REGISTER_OPERATOR(
    update_loss_scaling, ops::UpdateLossScalingOp,
    ops::UpdateLossScalingOpMaker,
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);

REGISTER_OP_CPU_KERNEL(update_loss_scaling,
                       ops::UpdateLossScalingKernel<CPU, float>,
                       ops::UpdateLossScalingKernel<CPU, double>);
<|endoftext|>