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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkVersorTransformOptimizerTest.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.

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

#include <itkVersorTransformOptimizer.h>
#include <itkVector.h>
#include <itkVersor.h>
#include <itkCovariantVector.h>
#include <itkVersorTransform.h>

/**
 *  The objectif function is the scalar product:
 *
 *  f( V ) = < A, V(B) >
 *
 *  where:
 *
 *    V  is a Versor representing a rotation
 *    A  is a vector
 *    B  is another vector
 *
 *  the vector A = [ 0 0 1 ]
 *  the vector B = [ 0 1 0 ]
 *
 *  the Versor solution should be: V = [ k1 0 0 k2 ]
 *
 *        k1 = sin( 45 degrees )
 *        k2 = cos( 45 degrees )
 *
 */
class CostFunction : public itk::LightObject
{
public:

  typedef CostFunction Self;
  typedef itk::LightObject  Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  typedef itk::VersorTransform<double>    TransformType;

  itkNewMacro( Self );

  enum { SpaceDimension = 3 };

  typedef itk::Versor< double >                    ParametersType;
  typedef ParametersType::VectorType               AxisType;

  typedef itk::CovariantVector< double,
                                SpaceDimension >   DerivativeType;
  typedef itk::Vector< double,  SpaceDimension >   VectorType;

  typedef double MeasureType;

  CostFunction()
  {
    m_Transform = TransformType::New();
  }

  const ParametersType & GetParameters(void) const
    {
    return m_Parameters;
    }

  const MeasureType & GetValue( const ParametersType & parameters ) const
  {

    VectorType A;
    VectorType B;

    A[0] = 0;
    A[1] = 0;
    A[2] = 1;

    B[0] = 0;
    B[1] = 1;
    B[2] = 0;

    m_Parameters = parameters;

    m_Transform->SetRotation( m_Parameters );

    const VectorType C = m_Transform->TransformVector( B );

    m_Measure = A * C;

    return m_Measure;

  }

  const DerivativeType & GetDerivative(
                     const ParametersType & parameters ) const
  {

    const MeasureType baseValue =  this->GetValue( parameters );

    ParametersType versorX;
    ParametersType versorY;
    ParametersType versorZ;

    const double deltaAngle = 0.00175; // in radians = about 0.1 degree

    versorX.SetRotationAroundX( deltaAngle );
    versorY.SetRotationAroundY( deltaAngle );
    versorZ.SetRotationAroundZ( deltaAngle );

    const MeasureType turnXValue = this->GetValue( parameters * versorX );
    const MeasureType turnYValue = this->GetValue( parameters * versorY );
    const MeasureType turnZValue = this->GetValue( parameters * versorZ );

    m_Derivative[0] = ( turnXValue - baseValue ) / deltaAngle;
    m_Derivative[1] = ( turnYValue - baseValue ) / deltaAngle;
    m_Derivative[2] = ( turnZValue - baseValue ) / deltaAngle;

    return m_Derivative;
  }

private:

  mutable   TransformType::Pointer  m_Transform;

  mutable   ParametersType          m_Parameters;
  mutable   MeasureType             m_Measure;
  mutable   DerivativeType          m_Derivative;

};

int main()
{
  std::cout << "VersorTransform Optimizer Test ";
  std::cout << std::endl << std::endl;

  typedef  itk::VersorTransformOptimizer< CostFunction >  OptimizerType;

  // Declaration of a itkOptimizer
  OptimizerType::Pointer  itkOptimizer = OptimizerType::New();

  // Declaration of the CostFunction adaptor
  CostFunction::Pointer costFunction = CostFunction::New();

  itkOptimizer->SetCostFunction( costFunction );

  typedef CostFunction::ParametersType    ParametersType;

  typedef OptimizerType::TransformType   TransformType;
  typedef TransformType::ParametersType  TransformParametersType;

  // We start with a null rotation
  ParametersType  initialRotation;
  ParametersType::VectorType axis;

  axis = 1.0f, 0.0f, 0.0f;

  ParametersType::ValueType angle = 0.0f;

  initialRotation.Set( axis, angle );

  itkOptimizer->MaximizeOn();
  itkOptimizer->SetGradientMagnitudeTolerance( 1e-15 );
  itkOptimizer->SetMaximumStepLength( 0.1745 ); // About 10 deegres
  itkOptimizer->SetMinimumStepLength( 1e-9 );
  itkOptimizer->SetNumberOfIterations( 300 );

  itkOptimizer->SetInitialPosition( initialRotation );
  itkOptimizer->StartOptimization();

  ParametersType finalPosition;
  finalPosition = costFunction->GetParameters();
  std::cout << "Solution        = (" << finalPosition << ")" << std::endl;

  //
  // check results to see if it is within range
  //
  bool pass = true;

  // True versor
  ParametersType trueParameters;
  ParametersType::VectorType trueAxis;
  ParametersType::ValueType  trueAngle;
  trueAxis  = 1.0f, 0.0f, 0.0f;
  trueAngle = 2.0 * atan( 1.0f );

  trueParameters.Set( trueAxis, trueAngle );

  std::cout << "True Parameters = " << trueParameters << std::endl;
  for( unsigned int j = 0; j < 2; j++ )
    {
    ParametersType ratio = finalPosition * trueParameters.GetReciprocal();
    const ParametersType::ValueType cosHalfAngle = ratio.GetW();
    const ParametersType::ValueType cosHalfAngleSquare =
                                            cosHalfAngle * cosHalfAngle;
    if( cosHalfAngleSquare < 0.95 )
      {
      pass = false;
      break;
      }
    }

  if( !pass )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;

}

<commit_msg>ERR: bad initialization.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkVersorTransformOptimizerTest.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.

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

#include <itkVersorTransformOptimizer.h>
#include <itkVector.h>
#include <itkVersor.h>
#include <itkCovariantVector.h>
#include <itkVersorTransform.h>

/**
 *  The objectif function is the scalar product:
 *
 *  f( V ) = < A, V(B) >
 *
 *  where:
 *
 *    V  is a Versor representing a rotation
 *    A  is a vector
 *    B  is another vector
 *
 *  the vector A = [ 0 0 1 ]
 *  the vector B = [ 0 1 0 ]
 *
 *  the Versor solution should be: V = [ k1 0 0 k2 ]
 *
 *        k1 = sin( 45 degrees )
 *        k2 = cos( 45 degrees )
 *
 */
class CostFunction : public itk::LightObject
{
public:

  typedef CostFunction Self;
  typedef itk::LightObject  Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  typedef itk::VersorTransform<double>    TransformType;

  itkNewMacro( Self );

  enum { SpaceDimension = 3 };

  typedef itk::Versor< double >                    ParametersType;
  typedef ParametersType::VectorType               AxisType;

  typedef itk::CovariantVector< double,
                                SpaceDimension >   DerivativeType;
  typedef itk::Vector< double,  SpaceDimension >   VectorType;

  typedef double MeasureType;

  CostFunction()
  {
    m_Transform = TransformType::New();
  }

  const ParametersType & GetParameters(void) const
    {
    return m_Parameters;
    }

  const MeasureType & GetValue( const ParametersType & parameters ) const
  {

    VectorType A;
    VectorType B;

    A[0] = 0;
    A[1] = 0;
    A[2] = 1;

    B[0] = 0;
    B[1] = 1;
    B[2] = 0;

    m_Parameters = parameters;

    m_Transform->SetRotation( m_Parameters );

    const VectorType C = m_Transform->TransformVector( B );

    m_Measure = A * C;

    return m_Measure;

  }

  const DerivativeType & GetDerivative(
                     const ParametersType & parameters ) const
  {

    const MeasureType baseValue =  this->GetValue( parameters );

    ParametersType versorX;
    ParametersType versorY;
    ParametersType versorZ;

    const double deltaAngle = 0.00175; // in radians = about 0.1 degree

    versorX.SetRotationAroundX( deltaAngle );
    versorY.SetRotationAroundY( deltaAngle );
    versorZ.SetRotationAroundZ( deltaAngle );

    const MeasureType turnXValue = this->GetValue( parameters * versorX );
    const MeasureType turnYValue = this->GetValue( parameters * versorY );
    const MeasureType turnZValue = this->GetValue( parameters * versorZ );

    m_Derivative[0] = ( turnXValue - baseValue ) / deltaAngle;
    m_Derivative[1] = ( turnYValue - baseValue ) / deltaAngle;
    m_Derivative[2] = ( turnZValue - baseValue ) / deltaAngle;

    return m_Derivative;
  }

private:

  mutable   TransformType::Pointer  m_Transform;

  mutable   ParametersType          m_Parameters;
  mutable   MeasureType             m_Measure;
  mutable   DerivativeType          m_Derivative;

};

int main()
{
  std::cout << "VersorTransform Optimizer Test ";
  std::cout << std::endl << std::endl;

  typedef  itk::VersorTransformOptimizer< CostFunction >  OptimizerType;

  // Declaration of a itkOptimizer
  OptimizerType::Pointer  itkOptimizer = OptimizerType::New();

  // Declaration of the CostFunction adaptor
  CostFunction::Pointer costFunction = CostFunction::New();

  itkOptimizer->SetCostFunction( costFunction );

  typedef CostFunction::ParametersType    ParametersType;

  typedef OptimizerType::TransformType   TransformType;
  typedef TransformType::ParametersType  TransformParametersType;

  // We start with a null rotation
  ParametersType  initialRotation;
  ParametersType::VectorType axis;
  axis[0] = 1.0f;
  axis[1] = 0.0f;
  axis[2] = 0.0f;
  ParametersType::ValueType angle = 0.0f;

  initialRotation.Set( axis, angle );

  itkOptimizer->MaximizeOn();
  itkOptimizer->SetGradientMagnitudeTolerance( 1e-15 );
  itkOptimizer->SetMaximumStepLength( 0.1745 ); // About 10 deegres
  itkOptimizer->SetMinimumStepLength( 1e-9 );
  itkOptimizer->SetNumberOfIterations( 300 );

  itkOptimizer->SetInitialPosition( initialRotation );
  itkOptimizer->StartOptimization();

  ParametersType finalPosition;
  finalPosition = costFunction->GetParameters();
  std::cout << "Solution        = (" << finalPosition << ")" << std::endl;

  //
  // check results to see if it is within range
  //
  bool pass = true;

  // True versor
  ParametersType trueParameters;
  ParametersType::VectorType trueAxis;
  ParametersType::ValueType  trueAngle;
  trueAxis  = 1.0f, 0.0f, 0.0f;
  trueAngle = 2.0 * atan( 1.0f );

  trueParameters.Set( trueAxis, trueAngle );

  std::cout << "True Parameters = " << trueParameters << std::endl;
  for( unsigned int j = 0; j < 2; j++ )
    {
    ParametersType ratio = finalPosition * trueParameters.GetReciprocal();
    const ParametersType::ValueType cosHalfAngle = ratio.GetW();
    const ParametersType::ValueType cosHalfAngleSquare =
                                            cosHalfAngle * cosHalfAngle;
    if( cosHalfAngleSquare < 0.95 )
      {
      pass = false;
      break;
      }
    }

  if( !pass )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;

}

<|endoftext|>


<commit_before>#include "Neohuman.h"
#include <iostream>

#include "BWEM/bwem.h"

using namespace BWAPI;
using namespace Filter;

using namespace BWEM;
using namespace BWEM::BWAPI_ext;
using namespace BWEM::utils;

#define MIN(a, b) (((a) < (b) ? (a) : (b)))
#define MAX(a, b) (((a) < (b) ? (b) : (a)))

#define SATRUATION_RADIUS 350
#define WORKERAGGRORADIUS 200

#define SHOWTHINGS

namespace { auto & BWEMMap = Map::Instance(); }

bool Neohuman::doBuild(Unit u, UnitType building, TilePosition at) {
	_buildingQueue.push_back(Triple<int, UnitType, TilePosition>{u->getID(), building, at});
}

std::pair <int, int> Neohuman::getQueuedResources() {
	std::pair <int, int> resources;
	for (auto &o : _buildingQueue)
		resources.first  += o.second.mineralPrice(),
		resources.second += o.second.gasPrice();
	return resources;
}

std::pair <int, int> Neohuman::getSpendableResources() {
	std::pair <int, int> result = { Broodwar->self()->minerals(), Broodwar->self()->gas() };
	auto queued = this->getQueuedResources();
	result.first -= queued.first, result.second -= queued.second;
	return result;
}

void Neohuman::onStart() {
	Broodwar << "The map is totally not " << Broodwar->mapName() << "!" << std::endl;

	//Broodwar->enableFlag(Flag::UserInput);

	// Uncomment the following line and the bot will know about everything through the fog of war (cheat).
	//Broodwar->enableFlag(Flag::CompleteMapInformation);

	// Set the command optimization level so that common commands can be grouped
	// and reduce the bot's APM (Actions Per Minute).
	Broodwar->setCommandOptimizationLevel(2);

	// Check if this is a replay
	if (!Broodwar->isReplay()) {
		if (Broodwar->enemy())
			Broodwar << "The matchup is me (" << Broodwar->self()->getRace() << ") vs " << Broodwar->enemy()->getRace() << std::endl;
	}

	BWEMMap.Initialize();
	BWEMMap.EnableAutomaticPathAnalysis();

}

void Neohuman::onEnd(bool didWin) {
	// Called when the game ends
	if (didWin) {

	} else {

	}
}

int Neohuman::randint(int min, int max) {
	std::uniform_int_distribution<int> dist(min, max);
	return dist(_rand);
}

template <typename T>
T Neohuman::randele(std::vector <T> &v) {
	return v[randint(0, v.size())];
}

void Neohuman::onFrame() {
	// Called once every game frame
	int constructingLine = 0;
	int availableMinerals = Broodwar->self()->minerals();

#ifdef SHOWTHINGS

	// Display the game frame rate as text in the upper left area of the screen
	Broodwar->drawTextScreen(200, 0,  "FPS: %d", Broodwar->getFPS());
	Broodwar->drawTextScreen(200, 12, "Average FPS: %f", Broodwar->getAverageFPS());
	Broodwar->drawTextScreen(200, 24, "I want %d more supply (%d queued, %d in production)", _wantedExtraSupply, _queuedSupply, _supplyBeingMade);
	Broodwar->drawTextScreen(200, 36, "I have %d barracks!", _nBarracks);

#endif

	try {
		//BWEM::utils::gridMapExample(BWEMMap);
		//BWEM::utils::drawMap(BWEMMap);
	} catch (const std::exception & e) {
		Broodwar << "EXCEPTION: " << e.what() << std::endl;
	}

	// Return if the game is a replay or is paused
	if (Broodwar->isReplay() || Broodwar->isPaused() || !Broodwar->self())
		return;

	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->exists() && u->isBeingConstructed()) {
			Broodwar->drawTextScreen(0, constructingLine, "%s", u->getType().c_str());
			constructingLine += 12;
		}
	}

#ifdef SHOWTHINGS

	// Show worker info
	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->getType().isResourceDepot()) {
			Broodwar->drawCircleMap(u->getPosition(), SATRUATION_RADIUS, Colors::Blue);
			auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
			auto refineries = u->getUnitsInRadius(SATRUATION_RADIUS, (IsRefinery));
			auto gasGeysers = u->getUnitsInRadius(SATRUATION_RADIUS);
			auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
			Broodwar->drawTextMap(u->getPosition() + Position(0, 30), "%cWorkers: %d/%d", Text::White, workers.size(), 2*mineralFields.size());
		}
	}

#endif

	// Prevent spamming by only running our onFrame once every number of latency frames.
	// Latency frames are the number of frames before commands are processed.
	if (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0)
		return;

	_supplyBeingMade = 0;
	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->isConstructing() && u->getType().getRace().getSupplyProvider() == u->getType())
			_supplyBeingMade += 8;
	}

	availableMinerals -= 100*_queuedSupply/8;

	if (Broodwar->elapsedTime() - _timeLastQueuedSupply > 5) {
		_queuedSupply = 0;
		_timeLastQueuedSupply = Broodwar->elapsedTime();
	}

	_nSupplyOverhead = 2 + MAX((Broodwar->self()->supplyUsed() - 10) / 8, 0);
	_wantedExtraSupply = (Broodwar->self()->supplyUsed() - (Broodwar->self()->supplyTotal() + _supplyBeingMade + _queuedSupply)) / 2 + _nSupplyOverhead;

	_nBarracks = 0;
	for (auto &u : Broodwar->self()->getUnits()) {
		// If a cc is under construction
		if (u->isConstructing() && u->getType() == u->getType().getRace().getCenter() && _isExpanding)
			availableMinerals += 400;
		// If a barracks is under construction
		if (u->isConstructing() && u->getType() == UnitTypes::Terran_Barracks && _isBuildingBarracks)
			availableMinerals += 150;

		if (u->getType() == UnitTypes::Terran_Barracks) {
			++_nBarracks;
		}
	}

	if (_isExpanding) {
		availableMinerals -= 400;
	}

	if (_isBuildingBarracks) {
		availableMinerals -= 150;
	}

	// Check if supply should be increased
	if (_wantedExtraSupply > 0 && availableMinerals >= 100 && Broodwar->self()->supplyTotal() < 400) {
		// Find unit to build our supply!
		for (auto &unit : Broodwar->self()->getUnits()) {
			if (unit->exists() && unit->isGatheringMinerals() && unit->isMoving() && !unit->isCarryingMinerals()) {
				// We have found our candidate!
				auto supplyType = unit->getType().getRace().getSupplyProvider();
				auto buildPos = Broodwar->getBuildLocation(supplyType, unit->getTilePosition());

				if (unit->build(supplyType, buildPos)) {
					_queuedSupply += 8;
					_timeLastQueuedSupply = Broodwar->elapsedTime();
					break;
				}
			}
		}
	}

	if (availableMinerals >= 150 && !_isBuildingBarracks && _nBarracks < 20) {
		// Build barracks!
		for (auto &u : Broodwar->self()->getUnits()) {
			if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
				auto buildingType = UnitTypes::Terran_Barracks;
				auto buildingPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());

				if (u->build(buildingType, buildingPos)) {
					_isBuildingBarracks = true;
					availableMinerals -= 150;
					break;
				}
			}
		}
	}

	/*if (!_isExpanding && availableMinerals >= 400){
		// Expand!
		for (auto &u : Broodwar->self()->getUnits()) {
			if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
				// Builder found!
				auto buildingType = u->getType().getRace().getCenter();
				auto buildPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());

				if (u->build(buildingType, buildPos)) {
					_isExpanding = true;
					availableMinerals -= 400;
					break;
				}
			}
		}
	}*/

	// Iterate through all the units that we own
	for (auto &u : Broodwar->self()->getUnits()) {
		// Ignore the unit if it no longer exists
		// Make sure to include this block when handling any Unit pointer!
		if (!u->exists())
			continue;

		// Ignore the unit if it has one of the following status ailments
		if (u->isLockedDown() || u->isMaelstrommed() || u->isStasised())
			continue;

		// Ignore the unit if it is in one of the following states
		if (u->isLoaded() || !u->isPowered() || u->isStuck())
			continue;

		// Ignore the unit if it is incomplete or busy constructing
		if (!u->isCompleted() || u->isConstructing())
			continue;

		// If the unit is a worker unit
		if (u->getType().isWorker()) {
			auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking, WORKERAGGRORADIUS);
			if (enemyUnit)
				u->attack(enemyUnit);

			// if our worker is idle
			if (u->isIdle()) {
				// Order workers carrying a resource to return them to the center,
				// otherwise find a mineral patch to harvest.
				if (u->isCarryingGas() || u->isCarryingMinerals())
					u->returnCargo();

				else if (!u->getPowerUp()) {
					// Probably need to set up some better logic for this
					auto preferredMiningLocation = u->getClosestUnit(IsMineralField);
					u->gather(preferredMiningLocation);
				}
			}
		} else if (u->getType().isResourceDepot()) {
			auto nearbyGeysers = u->getUnitsInRadius(SATRUATION_RADIUS, (GetType == UnitTypes::Resource_Vespene_Geyser));
			if (u->isIdle()) {
				auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
				if (nWorkers >= 70)
					continue;
				auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
				if (workers.size() < mineralFields.size() * 2 && availableMinerals >= 50) {
					if (u->train(u->getType().getRace().getWorker())) {
						Position pos = u->getPosition();
						Error lastErr = Broodwar->getLastError();
						Broodwar->registerEvent([pos, lastErr](Game*){ Broodwar->drawTextMap(pos + Position(0, -10), "%c%s", Text::Red, lastErr.c_str()); },   // action
							nullptr,    // condition
							Broodwar->getLatencyFrames());  // frames to run
					} else {
						availableMinerals -= 50;
					}
				}
			}
		} else if (u->getType() == UnitTypes::Terran_Barracks) {
			if (u->isIdle() && availableMinerals >= 50)
				if (!u->train(UnitTypes::Terran_Marine))
					availableMinerals -= 50;
		} else if (u->getType() == UnitTypes::Terran_Marine && Broodwar->getFrameCount() % 20 == 0) {
			auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking);
			if (enemyUnit) {
				u->attack(enemyUnit->getPosition());
				continue;
			}
			enemyUnit = u->getClosestUnit(IsEnemy);
			if (enemyUnit) {
				u->attack(enemyUnit->getPosition());
				continue;
			}
			auto closestMarine = u->getClosestUnit(GetType == UnitTypes::Terran_Marine);
			if (closestMarine) {
				auto walk = u->getPosition() - closestMarine->getPosition();
				u->move(u->getPosition() + walk);
			}
		}
	}
}

void Neohuman::onSendText(std::string text) {
	Broodwar->sendText("%s", text.c_str());
}

void Neohuman::onReceiveText(Player player, std::string text) {
	Broodwar << player->getName() << " said \"" << text << "\"" << std::endl;
}

void Neohuman::onPlayerLeft(Player player) {
	Broodwar->sendText("Goodbye %s!", player->getName().c_str());
}

void Neohuman::onNukeDetect(Position target) {
	if (target) {
		Broodwar << "Nuclear Launch Detected at " << target << std::endl;
	} else {
		Broodwar->sendText("Where's the nuke?");
	}
	// You can also retrieve all the nuclear missile targets using Broodwar->getNukeDots()!
}

void Neohuman::onUnitDiscover(Unit unit) {
}

void Neohuman::onUnitEvade(Unit unit) {
}

void Neohuman::onUnitShow(Unit unit) {
}

void Neohuman::onUnitHide(Unit unit) {
}

void Neohuman::onUnitCreate(Unit unit) {
}

void Neohuman::onUnitDestroy(Unit unit) {
}

void Neohuman::onUnitMorph(Unit unit) {
	this->onUnitComplete(unit);
}

void Neohuman::onUnitRenegade(Unit unit){
}

void Neohuman::onSaveGame(std::string gameName){
}

void Neohuman::onUnitComplete(Unit unit){
	if (unit->getType() == unit->getType().getRace().getCenter())
		_isExpanding = false;
	if (unit->getType() == UnitTypes::Terran_Barracks)
		_isBuildingBarracks = false;
}
<commit_msg>Worker logic<commit_after>#include "Neohuman.h"
#include <iostream>

#include "BWEM/bwem.h"

using namespace BWAPI;
using namespace Filter;

using namespace BWEM;
using namespace BWEM::BWAPI_ext;
using namespace BWEM::utils;

#define MIN(a, b) (((a) < (b) ? (a) : (b)))
#define MAX(a, b) (((a) < (b) ? (b) : (a)))

#define SATRUATION_RADIUS 350
#define WORKERAGGRORADIUS 200

#define SHOWTHINGS

namespace { auto & BWEMMap = Map::Instance(); }

bool Neohuman::doBuild(Unit u, UnitType building, TilePosition at) {
	_buildingQueue.push_back(Triple<int, UnitType, TilePosition>{u->getID(), building, at});
}

std::pair <int, int> Neohuman::getQueuedResources() {
	std::pair <int, int> resources;
	for (auto &o : _buildingQueue)
		resources.first  += o.second.mineralPrice(),
		resources.second += o.second.gasPrice();
	return resources;
}

std::pair <int, int> Neohuman::getSpendableResources() {
	std::pair <int, int> result = { Broodwar->self()->minerals(), Broodwar->self()->gas() };
	auto queued = this->getQueuedResources();
	result.first -= queued.first, result.second -= queued.second;
	return result;
}

void Neohuman::onStart() {
	Broodwar << "The map is totally not " << Broodwar->mapName() << "!" << std::endl;

	//Broodwar->enableFlag(Flag::UserInput);

	// Uncomment the following line and the bot will know about everything through the fog of war (cheat).
	//Broodwar->enableFlag(Flag::CompleteMapInformation);

	// Set the command optimization level so that common commands can be grouped
	// and reduce the bot's APM (Actions Per Minute).
	Broodwar->setCommandOptimizationLevel(2);

	// Check if this is a replay
	if (!Broodwar->isReplay()) {
		if (Broodwar->enemy())
			Broodwar << "The matchup is me (" << Broodwar->self()->getRace() << ") vs " << Broodwar->enemy()->getRace() << std::endl;
	}

	BWEMMap.Initialize();
	BWEMMap.EnableAutomaticPathAnalysis();

}

void Neohuman::onEnd(bool didWin) {
	// Called when the game ends
	if (didWin) {

	} else {

	}
}

int Neohuman::randint(int min, int max) {
	std::uniform_int_distribution<int> dist(min, max);
	return dist(_rand);
}

template <typename T>
T Neohuman::randele(std::vector <T> &v) {
	return v[randint(0, v.size())];
}

void Neohuman::onFrame() {
	// Called once every game frame
	int constructingLine = 0;
	int availableMinerals = Broodwar->self()->minerals();

#ifdef SHOWTHINGS

	// Display the game frame rate as text in the upper left area of the screen
	Broodwar->drawTextScreen(200, 0,  "FPS: %d", Broodwar->getFPS());
	Broodwar->drawTextScreen(200, 12, "Average FPS: %f", Broodwar->getAverageFPS());
	Broodwar->drawTextScreen(200, 24, "I want %d more supply (%d queued, %d in production)", _wantedExtraSupply, _queuedSupply, _supplyBeingMade);
	Broodwar->drawTextScreen(200, 36, "I have %d barracks!", _nBarracks);

#endif

	try {
		//BWEM::utils::gridMapExample(BWEMMap);
		//BWEM::utils::drawMap(BWEMMap);
	} catch (const std::exception & e) {
		Broodwar << "EXCEPTION: " << e.what() << std::endl;
	}

	// Return if the game is a replay or is paused
	if (Broodwar->isReplay() || Broodwar->isPaused() || !Broodwar->self())
		return;

	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->exists() && u->isBeingConstructed()) {
			Broodwar->drawTextScreen(0, constructingLine, "%s", u->getType().c_str());
			constructingLine += 12;
		}
	}

#ifdef SHOWTHINGS

	// Show worker info
	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->getType().isResourceDepot()) {
			Broodwar->drawCircleMap(u->getPosition(), SATRUATION_RADIUS, Colors::Blue);
			auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
			auto refineries = u->getUnitsInRadius(SATRUATION_RADIUS, (IsRefinery));
			auto gasGeysers = u->getUnitsInRadius(SATRUATION_RADIUS);
			auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
			Broodwar->drawTextMap(u->getPosition() + Position(0, 30), "%cWorkers: %d/%d", Text::White, workers.size(), 2*mineralFields.size());
		}
	}

#endif

	// Prevent spamming by only running our onFrame once every number of latency frames.
	// Latency frames are the number of frames before commands are processed.
	if (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0)
		return;

	_supplyBeingMade = 0;
	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->isConstructing() && u->getType().getRace().getSupplyProvider() == u->getType())
			_supplyBeingMade += 8;
	}

	availableMinerals -= 100*_queuedSupply/8;

	if (Broodwar->elapsedTime() - _timeLastQueuedSupply > 5) {
		_queuedSupply = 0;
		_timeLastQueuedSupply = Broodwar->elapsedTime();
	}

	_nSupplyOverhead = 2 + MAX((Broodwar->self()->supplyUsed() - 10) / 8, 0);
	_wantedExtraSupply = (Broodwar->self()->supplyUsed() - (Broodwar->self()->supplyTotal() + _supplyBeingMade + _queuedSupply)) / 2 + _nSupplyOverhead;

	_nBarracks = 0;
	for (auto &u : Broodwar->self()->getUnits()) {
		// If a cc is under construction
		if (u->isConstructing() && u->getType() == u->getType().getRace().getCenter() && _isExpanding)
			availableMinerals += 400;
		// If a barracks is under construction
		if (u->isConstructing() && u->getType() == UnitTypes::Terran_Barracks && _isBuildingBarracks)
			availableMinerals += 150;

		if (u->getType() == UnitTypes::Terran_Barracks) {
			++_nBarracks;
		}
	}

	if (_isExpanding) {
		availableMinerals -= 400;
	}

	if (_isBuildingBarracks) {
		availableMinerals -= 150;
	}

	int nWorkers = 0;
	for (auto &u : Broodwar->getAllUnits()) {
		if (u->getType() == u->getType().getRace().getWorker() && u->getPlayer() == Broodwar->self()) {
			++nWorkers;
		}
	}

	// Check if supply should be increased
	if (_wantedExtraSupply > 0 && availableMinerals >= 100 && Broodwar->self()->supplyTotal() < 400) {
		// Find unit to build our supply!
		for (auto &unit : Broodwar->self()->getUnits()) {
			if (unit->exists() && unit->isGatheringMinerals() && unit->isMoving() && !unit->isCarryingMinerals()) {
				// We have found our candidate!
				auto supplyType = unit->getType().getRace().getSupplyProvider();
				auto buildPos = Broodwar->getBuildLocation(supplyType, unit->getTilePosition());

				if (unit->build(supplyType, buildPos)) {
					_queuedSupply += 8;
					_timeLastQueuedSupply = Broodwar->elapsedTime();
					break;
				}
			}
		}
	}

	if (availableMinerals >= 150 && !_isBuildingBarracks && _nBarracks < 20) {
		// Build barracks!
		for (auto &u : Broodwar->self()->getUnits()) {
			if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
				auto buildingType = UnitTypes::Terran_Barracks;
				auto buildingPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());

				if (u->build(buildingType, buildingPos)) {
					_isBuildingBarracks = true;
					availableMinerals -= 150;
					break;
				}
			}
		}
	}

	/*if (!_isExpanding && availableMinerals >= 400){
		// Expand!
		for (auto &u : Broodwar->self()->getUnits()) {
			if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
				// Builder found!
				auto buildingType = u->getType().getRace().getCenter();
				auto buildPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());

				if (u->build(buildingType, buildPos)) {
					_isExpanding = true;
					availableMinerals -= 400;
					break;
				}
			}
		}
	}*/

	// Iterate through all the units that we own
	for (auto &u : Broodwar->self()->getUnits()) {
		// Ignore the unit if it no longer exists
		// Make sure to include this block when handling any Unit pointer!
		if (!u->exists())
			continue;

		// Ignore the unit if it has one of the following status ailments
		if (u->isLockedDown() || u->isMaelstrommed() || u->isStasised())
			continue;

		// Ignore the unit if it is in one of the following states
		if (u->isLoaded() || !u->isPowered() || u->isStuck())
			continue;

		// Ignore the unit if it is incomplete or busy constructing
		if (!u->isCompleted() || u->isConstructing())
			continue;

		// If the unit is a worker unit
		if (u->getType().isWorker()) {
			auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking, WORKERAGGRORADIUS);
			if (enemyUnit)
				u->attack(enemyUnit);

			// if our worker is idle
			if (u->isIdle()) {
				// Order workers carrying a resource to return them to the center,
				// otherwise find a mineral patch to harvest.
				if (u->isCarryingGas() || u->isCarryingMinerals())
					u->returnCargo();

				else if (!u->getPowerUp()) {
					// Probably need to set up some better logic for this
					auto preferredMiningLocation = u->getClosestUnit(IsMineralField);
					u->gather(preferredMiningLocation);
				}
			}
		} else if (u->getType().isResourceDepot()) {
			auto nearbyGeysers = u->getUnitsInRadius(SATRUATION_RADIUS, (GetType == UnitTypes::Resource_Vespene_Geyser));
			if (u->isIdle()) {
				auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
				if (nWorkers >= 70)
					continue;
				auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
				if (workers.size() < mineralFields.size() * 2 && availableMinerals >= 50) {
					if (u->train(u->getType().getRace().getWorker())) {
						Position pos = u->getPosition();
						Error lastErr = Broodwar->getLastError();
						Broodwar->registerEvent([pos, lastErr](Game*){ Broodwar->drawTextMap(pos + Position(0, -10), "%c%s", Text::Red, lastErr.c_str()); },   // action
							nullptr,    // condition
							Broodwar->getLatencyFrames());  // frames to run
					} else {
						availableMinerals -= 50;
					}
				}
			}
		} else if (u->getType() == UnitTypes::Terran_Barracks) {
			if (u->isIdle() && availableMinerals >= 50)
				if (!u->train(UnitTypes::Terran_Marine))
					availableMinerals -= 50;
		} else if (u->getType() == UnitTypes::Terran_Marine && Broodwar->getFrameCount() % 20 == 0) {
			auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking);
			if (enemyUnit) {
				u->attack(enemyUnit->getPosition());
				continue;
			}
			enemyUnit = u->getClosestUnit(IsEnemy);
			if (enemyUnit) {
				u->attack(enemyUnit->getPosition());
				continue;
			}
			auto closestMarine = u->getClosestUnit(GetType == UnitTypes::Terran_Marine);
			if (closestMarine) {
				auto walk = u->getPosition() - closestMarine->getPosition();
				u->move(u->getPosition() + walk);
			}
		}
	}
}

void Neohuman::onSendText(std::string text) {
	Broodwar->sendText("%s", text.c_str());
}

void Neohuman::onReceiveText(Player player, std::string text) {
	Broodwar << player->getName() << " said \"" << text << "\"" << std::endl;
}

void Neohuman::onPlayerLeft(Player player) {
	Broodwar->sendText("Goodbye %s!", player->getName().c_str());
}

void Neohuman::onNukeDetect(Position target) {
	if (target) {
		Broodwar << "Nuclear Launch Detected at " << target << std::endl;
	} else {
		Broodwar->sendText("Where's the nuke?");
	}
	// You can also retrieve all the nuclear missile targets using Broodwar->getNukeDots()!
}

void Neohuman::onUnitDiscover(Unit unit) {
}

void Neohuman::onUnitEvade(Unit unit) {
}

void Neohuman::onUnitShow(Unit unit) {
}

void Neohuman::onUnitHide(Unit unit) {
}

void Neohuman::onUnitCreate(Unit unit) {
}

void Neohuman::onUnitDestroy(Unit unit) {
}

void Neohuman::onUnitMorph(Unit unit) {
	this->onUnitComplete(unit);
}

void Neohuman::onUnitRenegade(Unit unit){
}

void Neohuman::onSaveGame(std::string gameName){
}

void Neohuman::onUnitComplete(Unit unit){
	if (unit->getType() == unit->getType().getRace().getCenter())
		_isExpanding = false;
	if (unit->getType() == UnitTypes::Terran_Barracks)
		_isBuildingBarracks = false;
}
<|endoftext|>


<commit_before>#include <Servo.h>
#include <Arduino.h>
#include "PicoRobo.h"
//====================================================================================================================
//Parameter
//====================================================================================================================
#define SERV_NUM 4                  //number of servo for array
#define FRAME 20                    //interval time from current step to next step: 20msecc

int current_angle[SERV_NUM];
int target_angle[SERV_NUM+1];
float rotating_angle[SERV_NUM];      //rotating angle on each frame: calcurated by (target_angle - current_angle)/number of steps
int servo_trim[SERV_NUM];            //trim to adjust each servo motors's angle to center

Servo servo[SERV_NUM];
#define CENTER 4
#define RIGHT 5
#define LEFT 6
#define NECK 7
#define DELAY 50

//====================================================================================================================
//Servo Method
//====================================================================================================================
void PicoRobo::initServo(){

  //attach pins to each servo
  servo[0].attach(CENTER);
  servo[1].attach(RIGHT);
  servo[2].attach(LEFT);
  servo[3].attach(NECK);

  //set trim
  int tmp_trim[SERV_NUM]={0,0,0,0};      //set trim to each servo
  for(int i=0;i<SERV_NUM;i++){
    servo_trim[i]=tmp_trim[i];
  }

  //rotate all servos to center position
  setCenterToServo();
}

void PicoRobo::setCenterToServo(){
  for(int i=0;i<SERV_NUM;i++){
    servo[i].write(90 + servo_trim[i]);
    current_angle[i] = 0;
    target_angle[i] = 0;
  }
}

//move to next position
void PicoRobo::moveToNextPosition(){

  //check limit
   for(int i=0;i<SERV_NUM;i++){
     if(target_angle[i]>90){
       target_angle[i]=90;
     }else if(target_angle[i]<-90){
       target_angle[i]=-90;
     }
   }

  int numberOfStep = target_angle[SERV_NUM]/FRAME;    //total number of steps to move to next position

  for(int i=0;i<SERV_NUM;i++){
    rotating_angle[i]=((float)target_angle[i]-(float)current_angle[i])/(float)numberOfStep;
  }

  int next_timing = millis() + FRAME;
  int current_time;
  float tmp_angle[SERV_NUM];

  for(int i=0;i<SERV_NUM;i++){
    tmp_angle[i]=(float)current_angle[i];
  }

  while(numberOfStep){
    current_time=millis();
    if(current_time>next_timing){
      for(int i=0;i<SERV_NUM;i++){
        tmp_angle[i] += rotating_angle[i];
        current_angle[i] = (int)tmp_angle[i];
        servo[i].write(current_angle[i]+servo_trim[i]+90);
      }
      next_timing = next_timing + FRAME;
      numberOfStep--;
    }
  }
  //adjust current_angle
  for(int i=0;i<SERV_NUM;i++){
    current_angle[i] = target_angle[i];
    servo[i].write(current_angle[i]+servo_trim[i]+90);
  }
}

//call moveToNextPosition() method continuously
void PicoRobo::playMotion(int motion[][SERV_NUM+1], int numberOfMotion){
  for(int i=0;i<numberOfMotion;i++){
    for(int j=0;j<SERV_NUM+1;j++){
      target_angle[j]=motion[i][j];
    }
    moveToNextPosition();
  }
}
<commit_msg>Introducing a seperate limit for every servo<commit_after>#include <Servo.h>
#include <Arduino.h>
#include "PicoRobo.h"
//====================================================================================================================
//Parameter
//====================================================================================================================
#define SERV_NUM 4                  //number of servo for array
#define FRAME 20                    //interval time from current step to next step: 20msecc

int current_angle[SERV_NUM];
int target_angle[SERV_NUM+1];
float rotating_angle[SERV_NUM];      //rotating angle on each frame: calcurated by (target_angle - current_angle)/number of steps
int servo_trim[SERV_NUM];            //trim to adjust each servo motors's angle to center
int servo_limit[SERV_NUM];           //limit to prevent each motor going to bad places

Servo servo[SERV_NUM];
#define CENTER 4
#define RIGHT 5
#define LEFT 6
#define NECK 7
#define DELAY 50

//====================================================================================================================
//Servo Method
//====================================================================================================================
void PicoRobo::initServo(){

  //attach pins to each servo
  servo[0].attach(CENTER);
  servo[1].attach(RIGHT);
  servo[2].attach(LEFT);
  servo[3].attach(NECK);

  //set trim
  int tmp_trim[SERV_NUM]={0,-4,3,0};      //set trim to each servo
  int tmp_limit[SERV_NUM]={40,15,15,75};      //set trim to each servo

  for(int i=0;i<SERV_NUM;i++){
    servo_trim[i]=tmp_trim[i];
    servo_limit[i]=tmp_limit[i];
  }

  //rotate all servos to center position
  setCenterToServo();
}

void PicoRobo::setCenterToServo(){
  for(int i=0;i<SERV_NUM;i++){
    servo[i].write(90 + servo_trim[i]);
    current_angle[i] = 0;
    target_angle[i] = 0;
  }
}

//move to next position
void PicoRobo::moveToNextPosition(){

  //check limit
   for(int i=0;i<SERV_NUM;i++){
     if(target_angle[i]>servo_limit[i]){
       target_angle[i]=servo_limit[i];
     }else if(target_angle[i]<-servo_limit[i]){
       target_angle[i]=-servo_limit[i];
     }
   }

  int numberOfStep = target_angle[SERV_NUM]/FRAME;    //total number of steps to move to next position

  for(int i=0;i<SERV_NUM;i++){
    rotating_angle[i]=((float)target_angle[i]-(float)current_angle[i])/(float)numberOfStep;
  }

  int next_timing = millis() + FRAME;
  int current_time;
  float tmp_angle[SERV_NUM];

  for(int i=0;i<SERV_NUM;i++){
    tmp_angle[i]=(float)current_angle[i];
  }

  while(numberOfStep){
    current_time=millis();
    if(current_time>next_timing){
      for(int i=0;i<SERV_NUM;i++){
        tmp_angle[i] += rotating_angle[i];
        current_angle[i] = (int)tmp_angle[i];
        servo[i].write(current_angle[i]+servo_trim[i]+90);
      }
      next_timing = next_timing + FRAME;
      numberOfStep--;
    }
  }
  //adjust current_angle
  for(int i=0;i<SERV_NUM;i++){
    current_angle[i] = target_angle[i];
    servo[i].write(current_angle[i]+servo_trim[i]+90);
  }
}

//call moveToNextPosition() method continuously
void PicoRobo::playMotion(int motion[][SERV_NUM+1], int numberOfMotion){
  for(int i=0;i<numberOfMotion;i++){
    for(int j=0;j<SERV_NUM+1;j++){
      target_angle[j]=motion[i][j];
    }
    moveToNextPosition();
  }
}
<|endoftext|>


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

#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "googleurl/src/gurl.h"
#include "net/base/mock_host_resolver.h"

using chrome::kHttpScheme;
using chrome::kStandardSchemeSeparator;

namespace {

const char kTestUrlHostname[] = "www.example.com";

}  // namespace

// A fake version of ProfileSyncService used for testing.
class FakeProfileSyncService : public ProfileSyncService {
 public:
  // The |username_after_login| parameter determines what this fake
  // ProfileSyncService will set the username to when ShowLoginDialog is called.
  FakeProfileSyncService(const std::string& initial_username,
                         const std::string& username_after_login) :
      username_(ASCIIToUTF16(initial_username)),
      username_after_login_(username_after_login),
      observer_(NULL) {}

  virtual ~FakeProfileSyncService() {
    EXPECT_TRUE(observer_ == NULL);
  }

  // Overrides of virtual methods in ProfileSyncService.
  virtual string16 GetAuthenticatedUsername() const {
    return username_;
  }
  virtual void ShowLoginDialog(gfx::NativeWindow) {
    EXPECT_TRUE(observer_ != NULL);
    username_ = ASCIIToUTF16(username_after_login_);
    observer_->OnStateChanged();
  }
  virtual bool SetupInProgress() const {
    return false;
  }
  virtual void AddObserver(ProfileSyncServiceObserver* observer) {
    EXPECT_TRUE(observer_ == NULL);
    observer_ = observer;
  }
  virtual void RemoveObserver(ProfileSyncServiceObserver* observer) {
    EXPECT_TRUE(observer == observer_);
    observer_ = NULL;
  }

 private:
  string16 username_;
  std::string username_after_login_;
  ProfileSyncServiceObserver* observer_;
};

class ExtensionWebstorePrivateBrowserTest : public ExtensionBrowserTest {
 public:
  ExtensionWebstorePrivateBrowserTest() {
    test_url_base_ = std::string() + kHttpScheme + kStandardSchemeSeparator +
                     kTestUrlHostname;
  }

  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL, test_url_base_);
  }

  // This generates a regular test server url pointing to a test file at
  // |relative_path|, but replaces the hostname with kTestUrlHostname so that
  // we get the webstore private APIs injected (this happens because of the
  // command line switch we added in SetupCommandLine).
  GURL GetUrl(const std::string& relative_path) {
    GURL base_url = test_server()->GetURL(
        "files/extensions/webstore_private/" + relative_path);
    GURL::Replacements replacements;
    std::string replacement_host = std::string(kTestUrlHostname);
    replacements.SetHostStr(replacement_host);
    return base_url.ReplaceComponents(replacements);
  }

  void RunLoginTest(const std::string& relative_path,
                    const std::string& initial_login,
                    const std::string& login_result) {
    FakeProfileSyncService sync_service(initial_login, login_result);
    WebstorePrivateApi::SetTestingProfileSyncService(&sync_service);
    ExtensionTestMessageListener listener("success", false);
    GURL url = GetUrl(relative_path);
    ui_test_utils::NavigateToURL(browser(), url);
    EXPECT_TRUE(listener.WaitUntilSatisfied());
    WebstorePrivateApi::SetTestingProfileSyncService(NULL);
  }

 protected:
  std::string test_url_base_;
};

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBrowserTest, BrowserLogin) {
  host_resolver()->AddRule(kTestUrlHostname, "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  RunLoginTest("browser_login/expect_nonempty.html", "foo@bar.com", "");
  RunLoginTest("browser_login/prompt_no_preferred.html", "", "");
  RunLoginTest("browser_login/prompt_preferred.html", "", "foo@bar.com");
  RunLoginTest("browser_login/prompt_already_logged_in_error.html",
               "foo@bar.com",
               "foo@bar.com");
}
<commit_msg>Disable failing test while I investigate it.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "googleurl/src/gurl.h"
#include "net/base/mock_host_resolver.h"

using chrome::kHttpScheme;
using chrome::kStandardSchemeSeparator;

namespace {

const char kTestUrlHostname[] = "www.example.com";

}  // namespace

// A fake version of ProfileSyncService used for testing.
class FakeProfileSyncService : public ProfileSyncService {
 public:
  // The |username_after_login| parameter determines what this fake
  // ProfileSyncService will set the username to when ShowLoginDialog is called.
  FakeProfileSyncService(const std::string& initial_username,
                         const std::string& username_after_login) :
      username_(ASCIIToUTF16(initial_username)),
      username_after_login_(username_after_login),
      observer_(NULL) {}

  virtual ~FakeProfileSyncService() {
    EXPECT_TRUE(observer_ == NULL);
  }

  // Overrides of virtual methods in ProfileSyncService.
  virtual string16 GetAuthenticatedUsername() const {
    return username_;
  }
  virtual void ShowLoginDialog(gfx::NativeWindow) {
    EXPECT_TRUE(observer_ != NULL);
    username_ = ASCIIToUTF16(username_after_login_);
    observer_->OnStateChanged();
  }
  virtual bool SetupInProgress() const {
    return false;
  }
  virtual void AddObserver(ProfileSyncServiceObserver* observer) {
    EXPECT_TRUE(observer_ == NULL);
    observer_ = observer;
  }
  virtual void RemoveObserver(ProfileSyncServiceObserver* observer) {
    EXPECT_TRUE(observer == observer_);
    observer_ = NULL;
  }

 private:
  string16 username_;
  std::string username_after_login_;
  ProfileSyncServiceObserver* observer_;
};

class ExtensionWebstorePrivateBrowserTest : public ExtensionBrowserTest {
 public:
  ExtensionWebstorePrivateBrowserTest() {
    test_url_base_ = std::string() + kHttpScheme + kStandardSchemeSeparator +
                     kTestUrlHostname;
  }

  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL, test_url_base_);
  }

  // This generates a regular test server url pointing to a test file at
  // |relative_path|, but replaces the hostname with kTestUrlHostname so that
  // we get the webstore private APIs injected (this happens because of the
  // command line switch we added in SetupCommandLine).
  GURL GetUrl(const std::string& relative_path) {
    GURL base_url = test_server()->GetURL(
        "files/extensions/webstore_private/" + relative_path);
    GURL::Replacements replacements;
    std::string replacement_host = std::string(kTestUrlHostname);
    replacements.SetHostStr(replacement_host);
    return base_url.ReplaceComponents(replacements);
  }

  void RunLoginTest(const std::string& relative_path,
                    const std::string& initial_login,
                    const std::string& login_result) {
    FakeProfileSyncService sync_service(initial_login, login_result);
    WebstorePrivateApi::SetTestingProfileSyncService(&sync_service);
    ExtensionTestMessageListener listener("success", false);
    GURL url = GetUrl(relative_path);
    ui_test_utils::NavigateToURL(browser(), url);
    EXPECT_TRUE(listener.WaitUntilSatisfied());
    WebstorePrivateApi::SetTestingProfileSyncService(NULL);
  }

 protected:
  std::string test_url_base_;
};

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBrowserTest,
                       FAILS_BrowserLogin) {
  host_resolver()->AddRule(kTestUrlHostname, "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  RunLoginTest("browser_login/expect_nonempty.html", "foo@bar.com", "");
  RunLoginTest("browser_login/prompt_no_preferred.html", "", "");
  RunLoginTest("browser_login/prompt_preferred.html", "", "foo@bar.com");
  RunLoginTest("browser_login/prompt_already_logged_in_error.html",
               "foo@bar.com",
               "foo@bar.com");
}
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- *
 *                        OpenSim:  toyLeg_example.cpp                        *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2012 Stanford University and the Authors                *
 * Author(s): Matt S. DeMers                                                  *
 *                                                                            *
 * 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.                                             *
 * -------------------------------------------------------------------------- */

/*
 *  Below is an example of an OpenSim application that provides its own
 *  main() routine.  This application acts as an example for utilizing the
 *  ControllabeSpring actuator.
 */

// Author:  Matt DeMers

//==============================================================================
//==============================================================================
#include "PistonActuator.h"
#include "ControllableSpring.h"
#include <OpenSim/OpenSim.h>

using namespace OpenSim;
using namespace SimTK;

//______________________________________________________________________________
/**
 * Run a simulation of block sliding with contact on by two muscles sliding with contact
 */
int main()
{

    try {
        // Create a new OpenSim model
        Model osimModel;
        osimModel.setName("osimModel");
        osimModel.setAuthors("Matt DeMers");

        double Pi = SimTK::Pi;

        // Get the ground body
        Ground& ground = osimModel.updGround();
        ground.addMeshGeometry("checkered_floor.vtp");

        // create linkage body
        double linkageMass = 0.001, linkageLength = 0.5, linkageDiameter = 0.06;

        Vec3 linkageDimensions(linkageDiameter, linkageLength, linkageDiameter);
        Vec3 linkageMassCenter(0,linkageLength/2,0);
        Inertia linkageInertia = Inertia::cylinderAlongY(linkageDiameter/2.0, linkageLength/2.0);

        OpenSim::Body* linkage1 = new OpenSim::Body("linkage1", linkageMass, linkageMassCenter, linkageMass*linkageInertia);

        // Graphical representation
        Cylinder cyl;
        //This cylinder.vtp geometry is 1 meter tall, 1 meter diameter.  Scale and shift it to look pretty
        cyl.set_scale_factors(linkageDimensions);
        Frame* cyl1Frame = new PhysicalOffsetFrame(*linkage1, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
        cyl1Frame->setName("Cyl1_frame");
        osimModel.addFrame(cyl1Frame);
        cyl.setFrameName("Cyl1_frame");
        linkage1->addGeometry(cyl);

        Sphere sphere(0.1);
        linkage1->addGeometry(sphere);
        //This sphere.vtp is 1 meter in diameter.  Scale it.

        // Creat a second linkage body
        OpenSim::Body* linkage2 = new OpenSim::Body(*linkage1);
        linkage2->setName("linkage2");
        Frame* cyl2Frame = new PhysicalOffsetFrame(*linkage2, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
        cyl2Frame->setName("Cyl2_frame");
        osimModel.addFrame(cyl2Frame);
        (linkage2->upd_GeometrySet(0)).setFrameName("Cyl2_frame");
        // Creat a block to be the pelvis
        double blockMass = 20.0, blockSideLength = 0.2;
        Vec3 blockMassCenter(0);
        Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
        OpenSim::Body *block = new OpenSim::Body("block", blockMass, blockMassCenter, blockInertia);
        Brick brick(SimTK::Vec3(0.05, 0.05, 0.05));
        block->addGeometry(brick);
        //This block.vtp is 0.1x0.1x0.1 meters.  scale its appearance
        //block->updDisplayer()->updGeometrySet()[0].setScaleFactors(Vec3(2.0));

        // Create 1 degree-of-freedom pin joints between the bodies to creat a kinematic chain from ground through the block

        Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, linkageLength, 0.0), orientationInChild(0), locationInChild(0);

        PinJoint *ankle = new PinJoint("ankle", ground, locationInGround, orientationInGround, *linkage1,
            locationInChild, orientationInChild);

        PinJoint *knee = new PinJoint("knee", *linkage1, locationInParent, orientationInChild, *linkage2,
            locationInChild, orientationInChild);

        PinJoint *hip = new PinJoint("hip", *linkage2, locationInParent, orientationInChild, *block,
            locationInChild, orientationInChild);

        double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};
        CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();
        ankleCoordinateSet[0].setName("q1");
        ankleCoordinateSet[0].setRange(range);

        CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();
        kneeCoordinateSet[0].setName("q2");
        kneeCoordinateSet[0].setRange(range);

        CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();
        hipCoordinateSet[0].setName("q3");
        hipCoordinateSet[0].setRange(range);

        // Add the bodies to the model
        osimModel.addBody(linkage1);
        osimModel.addBody(linkage2);
        osimModel.addBody(block);

        // Add the joints to the model
        osimModel.addJoint(ankle);
        osimModel.addJoint(knee);
        osimModel.addJoint(hip);
        // Define contraints on the model
        //  Add a point on line constraint to limit the block to vertical motion

        Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);
        PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);
        osimModel.addConstraint(lineConstraint);

        // Add PistonActuator between the first linkage and the block
        Vec3 pointOnBodies(0);
        PistonActuator *piston = new PistonActuator();
        piston->setName("piston");
        piston->setBodyA(linkage1);
        piston->setBodyB(block);
        piston->setPointA(pointOnBodies);
        piston->setPointB(pointOnBodies);
        piston->setOptimalForce(200.0);
        piston->setPointsAreGlobal(false);

        osimModel.addForce(piston);
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        // Added ControllableSpring between the first linkage and the second block
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        ControllableSpring *spring = new ControllableSpring;
        spring->setName("spring");
        spring->setBodyA(block);
        spring->setBodyB(linkage1);
        spring->setPointA(pointOnBodies);
        spring->setPointB(pointOnBodies);
        spring->setOptimalForce(2000.0);
        spring->setPointsAreGlobal(false);
        spring->setRestLength(0.8);

        osimModel.addForce(spring);

        // define the simulation times
        double t0(0.0), tf(15);

        // create a controller to control the piston and spring actuators
        // the prescribed controller sets the controls as functions of time
        PrescribedController *legController = new PrescribedController();
        // give the legController control over all (two) model actuators
        legController->setActuators(osimModel.updActuators());

        // specify some control nodes for spring stiffness control
        double t[] = {0.0, 4.0, 7.0,  10.0, 15.0};
        double x[] = {1.0, 1.0, 0.25,  0.25, 5.0};

        // specify the control function for each actuator
        legController->prescribeControlForActuator("piston", new Constant(0.1));
        legController->prescribeControlForActuator("spring", new PiecewiseLinearFunction(5, t, x));

        // add the controller to the model
        osimModel.addController(legController);

        // define the acceration due to gravity
        osimModel.setGravity(Vec3(0, -9.80665, 0));

        // enable the model visualizer see the model in action, which can be
        // useful for debugging
        osimModel.setUseVisualizer(false);

        // Initialize system
        SimTK::State& si = osimModel.initSystem();

        // Pin joint initial states
        double q1_i = -Pi/4;
        double q2_i = - 2*q1_i;
        CoordinateSet &coordinates = osimModel.updCoordinateSet();
        coordinates[0].setValue(si, q1_i, true);
        coordinates[1].setValue(si,q2_i, true);

        // Setup integrator and manager
        SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
        integrator.setAccuracy(1.0e-3);

        ForceReporter *forces = new ForceReporter(&osimModel);
        osimModel.updAnalysisSet().adoptAndAppend(forces);
        Manager manager(osimModel, integrator);

        //Examine the model
        osimModel.printDetailedInfo(si, std::cout);
        // Save the model
        osimModel.print("toyLeg.osim");
        // Print out the initial position and velocity states
        si.getQ().dump("Initial q's");
        si.getU().dump("Initial u's");
        std::cout << "Initial time: " << si.getTime() << std::endl;

        osimModel.dumpPathName();
        // Integrate
        manager.setInitialTime(t0);
        manager.setFinalTime(tf);
        std::cout<<"\n\nIntegrating from " << t0 << " to " << tf << std::endl;
        manager.integrate(si);

        // Save results
        osimModel.printControlStorage("SpringActuatedLeg_controls.sto");
        Storage statesDegrees(manager.getStateStorage());
        osimModel.updSimbodyEngine().convertRadiansToDegrees(statesDegrees);
        //statesDegrees.print("PistonActuatedLeg_states_degrees.mot");
        statesDegrees.print("SpringActuatedLeg_states_degrees.mot");

        forces->getForceStorage().print("actuator_forces.mot");

    }
    catch (const std::exception& ex)
    {
        std::cout << "Exception in toyLeg_example: " << ex.what() << std::endl;
        return 1;
    }

    std::cout << "Done." << std::endl;
    return 0;
}
<commit_msg>Remove references in comments to sphere.vtp, block.vtp and cylinder.vtp as they're replaced with Geometry primitives Sphere, Brick and Cylinder.<commit_after>/* -------------------------------------------------------------------------- *
 *                        OpenSim:  toyLeg_example.cpp                        *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2012 Stanford University and the Authors                *
 * Author(s): Matt S. DeMers                                                  *
 *                                                                            *
 * 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.                                             *
 * -------------------------------------------------------------------------- */

/*
 *  Below is an example of an OpenSim application that provides its own
 *  main() routine.  This application acts as an example for utilizing the
 *  ControllabeSpring actuator.
 */

// Author:  Matt DeMers

//==============================================================================
//==============================================================================
#include "PistonActuator.h"
#include "ControllableSpring.h"
#include <OpenSim/OpenSim.h>

using namespace OpenSim;
using namespace SimTK;

//______________________________________________________________________________
/**
 * Run a simulation of block sliding with contact on by two muscles sliding with contact
 */
int main()
{

    try {
        // Create a new OpenSim model
        Model osimModel;
        osimModel.setName("osimModel");
        osimModel.setAuthors("Matt DeMers");

        double Pi = SimTK::Pi;

        // Get the ground body
        Ground& ground = osimModel.updGround();
        ground.addMeshGeometry("checkered_floor.vtp");

        // create linkage body
        double linkageMass = 0.001, linkageLength = 0.5, linkageDiameter = 0.06;

        Vec3 linkageDimensions(linkageDiameter, linkageLength, linkageDiameter);
        Vec3 linkageMassCenter(0,linkageLength/2,0);
        Inertia linkageInertia = Inertia::cylinderAlongY(linkageDiameter/2.0, linkageLength/2.0);

        OpenSim::Body* linkage1 = new OpenSim::Body("linkage1", linkageMass, linkageMassCenter, linkageMass*linkageInertia);

        // Graphical representation
        Cylinder cyl;
        cyl.set_scale_factors(linkageDimensions);
        Frame* cyl1Frame = new PhysicalOffsetFrame(*linkage1, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
        cyl1Frame->setName("Cyl1_frame");
        osimModel.addFrame(cyl1Frame);
        cyl.setFrameName("Cyl1_frame");
        linkage1->addGeometry(cyl);

        Sphere sphere(0.1);
        linkage1->addGeometry(sphere);

        // Creat a second linkage body
        OpenSim::Body* linkage2 = new OpenSim::Body(*linkage1);
        linkage2->setName("linkage2");
        Frame* cyl2Frame = new PhysicalOffsetFrame(*linkage2, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
        cyl2Frame->setName("Cyl2_frame");
        osimModel.addFrame(cyl2Frame);
        (linkage2->upd_GeometrySet(0)).setFrameName("Cyl2_frame");
        // Creat a block to be the pelvis
        double blockMass = 20.0, blockSideLength = 0.2;
        Vec3 blockMassCenter(0);
        Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
        OpenSim::Body *block = new OpenSim::Body("block", blockMass, blockMassCenter, blockInertia);
        Brick brick(SimTK::Vec3(0.05, 0.05, 0.05));
        block->addGeometry(brick);

        // Create 1 degree-of-freedom pin joints between the bodies to creat a kinematic chain from ground through the block
        Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, linkageLength, 0.0), orientationInChild(0), locationInChild(0);

        PinJoint *ankle = new PinJoint("ankle", ground, locationInGround, orientationInGround, *linkage1,
            locationInChild, orientationInChild);

        PinJoint *knee = new PinJoint("knee", *linkage1, locationInParent, orientationInChild, *linkage2,
            locationInChild, orientationInChild);

        PinJoint *hip = new PinJoint("hip", *linkage2, locationInParent, orientationInChild, *block,
            locationInChild, orientationInChild);

        double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};
        CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();
        ankleCoordinateSet[0].setName("q1");
        ankleCoordinateSet[0].setRange(range);

        CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();
        kneeCoordinateSet[0].setName("q2");
        kneeCoordinateSet[0].setRange(range);

        CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();
        hipCoordinateSet[0].setName("q3");
        hipCoordinateSet[0].setRange(range);

        // Add the bodies to the model
        osimModel.addBody(linkage1);
        osimModel.addBody(linkage2);
        osimModel.addBody(block);

        // Add the joints to the model
        osimModel.addJoint(ankle);
        osimModel.addJoint(knee);
        osimModel.addJoint(hip);
        // Define contraints on the model
        //  Add a point on line constraint to limit the block to vertical motion

        Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);
        PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);
        osimModel.addConstraint(lineConstraint);

        // Add PistonActuator between the first linkage and the block
        Vec3 pointOnBodies(0);
        PistonActuator *piston = new PistonActuator();
        piston->setName("piston");
        piston->setBodyA(linkage1);
        piston->setBodyB(block);
        piston->setPointA(pointOnBodies);
        piston->setPointB(pointOnBodies);
        piston->setOptimalForce(200.0);
        piston->setPointsAreGlobal(false);

        osimModel.addForce(piston);
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        // Added ControllableSpring between the first linkage and the second block
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        ControllableSpring *spring = new ControllableSpring;
        spring->setName("spring");
        spring->setBodyA(block);
        spring->setBodyB(linkage1);
        spring->setPointA(pointOnBodies);
        spring->setPointB(pointOnBodies);
        spring->setOptimalForce(2000.0);
        spring->setPointsAreGlobal(false);
        spring->setRestLength(0.8);

        osimModel.addForce(spring);

        // define the simulation times
        double t0(0.0), tf(15);

        // create a controller to control the piston and spring actuators
        // the prescribed controller sets the controls as functions of time
        PrescribedController *legController = new PrescribedController();
        // give the legController control over all (two) model actuators
        legController->setActuators(osimModel.updActuators());

        // specify some control nodes for spring stiffness control
        double t[] = {0.0, 4.0, 7.0,  10.0, 15.0};
        double x[] = {1.0, 1.0, 0.25,  0.25, 5.0};

        // specify the control function for each actuator
        legController->prescribeControlForActuator("piston", new Constant(0.1));
        legController->prescribeControlForActuator("spring", new PiecewiseLinearFunction(5, t, x));

        // add the controller to the model
        osimModel.addController(legController);

        // define the acceration due to gravity
        osimModel.setGravity(Vec3(0, -9.80665, 0));

        // enable the model visualizer see the model in action, which can be
        // useful for debugging
        osimModel.setUseVisualizer(false);

        // Initialize system
        SimTK::State& si = osimModel.initSystem();

        // Pin joint initial states
        double q1_i = -Pi/4;
        double q2_i = - 2*q1_i;
        CoordinateSet &coordinates = osimModel.updCoordinateSet();
        coordinates[0].setValue(si, q1_i, true);
        coordinates[1].setValue(si,q2_i, true);

        // Setup integrator and manager
        SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
        integrator.setAccuracy(1.0e-3);

        ForceReporter *forces = new ForceReporter(&osimModel);
        osimModel.updAnalysisSet().adoptAndAppend(forces);
        Manager manager(osimModel, integrator);

        //Examine the model
        osimModel.printDetailedInfo(si, std::cout);
        // Save the model
        osimModel.print("toyLeg.osim");
        // Print out the initial position and velocity states
        si.getQ().dump("Initial q's");
        si.getU().dump("Initial u's");
        std::cout << "Initial time: " << si.getTime() << std::endl;

        osimModel.dumpPathName();
        // Integrate
        manager.setInitialTime(t0);
        manager.setFinalTime(tf);
        std::cout<<"\n\nIntegrating from " << t0 << " to " << tf << std::endl;
        manager.integrate(si);

        // Save results
        osimModel.printControlStorage("SpringActuatedLeg_controls.sto");
        Storage statesDegrees(manager.getStateStorage());
        osimModel.updSimbodyEngine().convertRadiansToDegrees(statesDegrees);
        //statesDegrees.print("PistonActuatedLeg_states_degrees.mot");
        statesDegrees.print("SpringActuatedLeg_states_degrees.mot");

        forces->getForceStorage().print("actuator_forces.mot");

    }
    catch (const std::exception& ex)
    {
        std::cout << "Exception in toyLeg_example: " << ex.what() << std::endl;
        return 1;
    }

    std::cout << "Done." << std::endl;
    return 0;
}
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIXMLAttributes.cpp
    created:    Sat Mar 12 2005
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/XMLAttributes.h"
#include "CEGUI/Exceptions.h"
#include <sstream>
#include <iterator>

// Start of CEGUI namespace section
namespace CEGUI
{
    XMLAttributes::XMLAttributes(void)
    {}

    XMLAttributes::~XMLAttributes(void)
    {}

    void XMLAttributes::add(const String& attrName, const String& attrValue)
    {
        d_attrs[attrName] = attrValue;
    }

    void XMLAttributes::remove(const String& attrName)
    {
        AttributeMap::iterator pos = d_attrs.find(attrName);

        if (pos != d_attrs.end())
            d_attrs.erase(pos);
    }

    bool XMLAttributes::exists(const String& attrName) const
    {
        return d_attrs.find(attrName) != d_attrs.end();
    }

    size_t XMLAttributes::getCount(void) const
    {
        return d_attrs.size();
    }

    const String& XMLAttributes::getName(size_t index) const
    {
        if (index >= d_attrs.size())
        {
            CEGUI_THROW(InvalidRequestException("XMLAttributes::getName - The specified index is out of range for this XMLAttributes block."));
        }

        AttributeMap::const_iterator iter = d_attrs.begin();
        std::advance(iter, index);

        return (*iter).first;
    }

    const String& XMLAttributes::getValue(size_t index) const
    {
        if (index >= d_attrs.size())
        {
            CEGUI_THROW(InvalidRequestException("XMLAttributes::getValue - The specified index is out of range for this XMLAttributes block."));
        }

        AttributeMap::const_iterator iter = d_attrs.begin();
        std::advance(iter, index);

        return (*iter).second;
    }

    const String& XMLAttributes::getValue(const String& attrName) const
    {
        AttributeMap::const_iterator pos = d_attrs.find(attrName);

        if (pos != d_attrs.end())
        {
            return (*pos).second;
        }
        else
        {
            CEGUI_THROW(UnknownObjectException("XMLAttributes::getValue - no value exists for an attribute named '" + attrName + "'."));
        }
    }

    const String& XMLAttributes::getValueAsString(const String& attrName, const String& def) const
    {
        return (exists(attrName)) ? getValue(attrName) : def;
    }

    bool XMLAttributes::getValueAsBool(const String& attrName, bool def) const
    {
        if (!exists(attrName))
        {
            return def;
        }

        const String& val = getValue(attrName);

        if (val == "false" || val == "0")
        {
            return false;
        }
        else if (val == "true" || val == "1")
        {
            return true;
        }
        else
        {
            CEGUI_THROW(InvalidRequestException("XMLAttributes::getValueAsInteger - failed to convert attribute '" + attrName + "' with value '" + getValue(attrName) + "' to bool."));
        }
    }

    int XMLAttributes::getValueAsInteger(const String& attrName, int def) const
    {
        if (!exists(attrName))
        {
            return def;
        }

        int val;
        std::istringstream strm(getValue(attrName).c_str());

        strm >> val;

        // success?
        if (strm.fail())
        {
            CEGUI_THROW(InvalidRequestException("XMLAttributes::getValueAsInteger - failed to convert attribute '" + attrName + "' with value '" + getValue(attrName) + "' to integer."));
        }

        return val;
    }

    float XMLAttributes::getValueAsFloat(const String& attrName, float def) const
    {
        if (!exists(attrName))
        {
            return def;
        }

        float val;
        std::istringstream strm(getValue(attrName).c_str());

        strm >> val;

        // success?
        if (strm.fail())
        {
            CEGUI_THROW(InvalidRequestException("XMLAttributes::getValueAsInteger - failed to convert attribute '" + attrName + "' with value '" + getValue(attrName) + "' to float."));
        }

        return val;
    }

} // End of  CEGUI namespace section
<commit_msg>Interpret False and True as boolean values when loading XML<commit_after>/***********************************************************************
    filename:   CEGUIXMLAttributes.cpp
    created:    Sat Mar 12 2005
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/XMLAttributes.h"
#include "CEGUI/Exceptions.h"
#include <sstream>
#include <iterator>

// Start of CEGUI namespace section
namespace CEGUI
{
    XMLAttributes::XMLAttributes(void)
    {}

    XMLAttributes::~XMLAttributes(void)
    {}

    void XMLAttributes::add(const String& attrName, const String& attrValue)
    {
        d_attrs[attrName] = attrValue;
    }

    void XMLAttributes::remove(const String& attrName)
    {
        AttributeMap::iterator pos = d_attrs.find(attrName);

        if (pos != d_attrs.end())
            d_attrs.erase(pos);
    }

    bool XMLAttributes::exists(const String& attrName) const
    {
        return d_attrs.find(attrName) != d_attrs.end();
    }

    size_t XMLAttributes::getCount(void) const
    {
        return d_attrs.size();
    }

    const String& XMLAttributes::getName(size_t index) const
    {
        if (index >= d_attrs.size())
        {
            CEGUI_THROW(InvalidRequestException("XMLAttributes::getName - The specified index is out of range for this XMLAttributes block."));
        }

        AttributeMap::const_iterator iter = d_attrs.begin();
        std::advance(iter, index);

        return (*iter).first;
    }

    const String& XMLAttributes::getValue(size_t index) const
    {
        if (index >= d_attrs.size())
        {
            CEGUI_THROW(InvalidRequestException("XMLAttributes::getValue - The specified index is out of range for this XMLAttributes block."));
        }

        AttributeMap::const_iterator iter = d_attrs.begin();
        std::advance(iter, index);

        return (*iter).second;
    }

    const String& XMLAttributes::getValue(const String& attrName) const
    {
        AttributeMap::const_iterator pos = d_attrs.find(attrName);

        if (pos != d_attrs.end())
        {
            return (*pos).second;
        }
        else
        {
            CEGUI_THROW(UnknownObjectException("XMLAttributes::getValue - no value exists for an attribute named '" + attrName + "'."));
        }
    }

    const String& XMLAttributes::getValueAsString(const String& attrName, const String& def) const
    {
        return (exists(attrName)) ? getValue(attrName) : def;
    }

    bool XMLAttributes::getValueAsBool(const String& attrName, bool def) const
    {
        if (!exists(attrName))
        {
            return def;
        }

        const String& val = getValue(attrName);

        if (val == "false" || val == "False" || val == "0")
        {
            return false;
        }
        else if (val == "true" || val == "True" || val == "1")
        {
            return true;
        }
        else
        {
            CEGUI_THROW(InvalidRequestException("XMLAttributes::getValueAsBool - failed to convert attribute '" + attrName + "' with value '" + getValue(attrName) + "' to bool."));
        }
    }

    int XMLAttributes::getValueAsInteger(const String& attrName, int def) const
    {
        if (!exists(attrName))
        {
            return def;
        }

        int val;
        std::istringstream strm(getValue(attrName).c_str());

        strm >> val;

        // success?
        if (strm.fail())
        {
            CEGUI_THROW(InvalidRequestException("XMLAttributes::getValueAsInteger - failed to convert attribute '" + attrName + "' with value '" + getValue(attrName) + "' to integer."));
        }

        return val;
    }

    float XMLAttributes::getValueAsFloat(const String& attrName, float def) const
    {
        if (!exists(attrName))
        {
            return def;
        }

        float val;
        std::istringstream strm(getValue(attrName).c_str());

        strm >> val;

        // success?
        if (strm.fail())
        {
            CEGUI_THROW(InvalidRequestException("XMLAttributes::getValueAsInteger - failed to convert attribute '" + attrName + "' with value '" + getValue(attrName) + "' to float."));
        }

        return val;
    }

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>// alien:///alice/cern.ch/user/t/tschuste/correction_hybrid_nulled.root
AliDhcTask *AddTaskDhc(
  Int_t iAna = 2,
  TString chUName = "",
  TString chHEffFile = "",
  TString chMuEffFile = "",
  TString chTaskFile = "",
  TString chTaskName = "",
  TString chNTracks = "PicoTracks")
{

  Char_t chExtraName[256];

  // Get the analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskDhc", "No analysis manager found.");
    return;
  }

  // ESD or AOD? write into the task name etc.
  sprintf(chExtraName,"_%s",mgr->GetInputEventHandler()->GetDataType());

  AliDhcTask *dhcTask = 0x0;

  // If string chTaskFile is given, load a pre-configured task from file
  if (!chTaskFile.EqualTo("")) {
    iAna=999;
    TFile *fiDhcTask = 0x0;
    fiDhcTask = TFile::Open(chTaskFile,"OLD");
    if (!fiDhcTask){
      Error("AddTaskDhc",Form("Requested file: %s was not opened. ABORT.",chTaskFile));
      return;
    }
    dhcTask = (AliDhcTask*) fiDhcTask->Get(chTaskName);
  }
  else { // create a new task
    // Binning
    Double_t arPt[5] = {0.5, 1.0, 2.0, 4.0};
    TAxis *axPt = new TAxis(3,arPt);
    Double_t arCent[5] = {0.0, 20.0, 40.0, 60.0, 100.0};
    TAxis *axCent = new TAxis(4,arCent);
    TAxis *axZvtx = new TAxis(1,-10.0,10.0);
    Double_t arCentMix[9] = {0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 80.0, 100.0};
    TAxis *axCentMix = new TAxis(8,arCentMix);
    TAxis *axZvtxMix = new TAxis(8,-10.0,10.0);

    // Efficiency correction files
    TFile *fiHEff  = 0x0;
    TFile *fiMuEff = 0x0;
    THnF* hHEff    = 0x0;
    THnF* hMuEff   = 0x0;
    if (!chHEffFile.EqualTo("")) {
      fiHEff = TFile::Open(chHEffFile,"OLD");
      if (!fiHEff){
        Error("AddTaskDhc",Form("Requested file: %s was not opened. ABORT.",chHEffFile));
        return;
      }
      hHEff = (THnF*) fiHEff->Get("correction");
    }
    if (!chMuEffFile.EqualTo("")) {
      fiMuEff = TFile::Open(chMuEffFile,"OLD");
      if (!fiMuEff){
        Error("AddTaskDhc",Form("Requested file: %s was not opened. ABORT.",chMuEffFile));
        return;
      }
      hMuEff = (THnF*) fiMuEff->Get("correction");
    }

    dhcTask = new AliDhcTask("Task_tschuste_Dhc_fornow");
    if (iAna==1) { // h-h
      Int_t nDetaBins = 40;
      Int_t nDPhiBins = 72;
      dhcTask->SetAnaMode(AliDhcTask::kHH);
      dhcTask->SetHEffT(hHEff);
      dhcTask->SetHEffA(hHEff);
      dhcTask->SetEtaMax(1.2);
      dhcTask->SetPtTACrit(kTRUE);
      sprintf(chExtraName,"%s_HH",chExtraName);
      if (hHEff) {
        sprintf(chExtraName,"%s_corrH",chExtraName);
      }
    } else if (iAna==2) { // mu-h
      Int_t nDetaBins = 100;
      Int_t nDPhiBins = 36;
      dhcTask->SetAnaMode(AliDhcTask::kMuH);
      dhcTask->SetHEffT(hMuEff);
      dhcTask->SetHEffA(hHEff);
      dhcTask->SetEtaMax(5.0);
      dhcTask->SetPtTACrit(kFALSE);
      sprintf(chExtraName,"%s_MuH",chExtraName);
      if (hMuEff) {
        sprintf(chExtraName,"%s_corrMu",chExtraName);
      }
      if (hHEff) {
        sprintf(chExtraName,"%s_corrH",chExtraName);
      }
    }
    dhcTask->SetTracksName(chNTracks);
    dhcTask->SetDoWeights(kFALSE);
    dhcTask->SetCentMethod("V0M");
    dhcTask->SetDEtaDPhiBins(nDetaBins,nDPhiBins);
    dhcTask->SetPtTBins(axPt);
    dhcTask->SetPtABins(axPt);
    dhcTask->SetCentBins(axCent);
    dhcTask->SetZVtxBins(axZvtx);
    dhcTask->SetCentMixBins(axCentMix);
    dhcTask->SetZVtxMixBins(axZvtxMix);
    dhcTask->SelectCollisionCandidates(AliVEvent::kINT7);
    dhcTask->SetVerbosity(0);
  }
  if (!dhcTask) {
    Error("AddTaskDhc","no dhcTask");
    return 0x0;
  }

  // make a unique task name
  Char_t chNewTaskName[256];
  if (chTaskName.EqualTo("")) {
    sprintf(chNewTaskName,"Task_Dhc%s%s",chExtraName,chUName.Data());
  } else {
    sprintf(chNewTaskName,"%s",chTaskName);
  }

  AliDhcTask *mgrTask = mgr->GetTask(chNewTaskName);
  if (mgrTask)
    sprintf(chNewTaskName,"%s_bis%04.0f",chNewTaskName,10000*gRandom->Rndm());

  dhcTask->SetName(chNewTaskName);
  Info("AddTaskDhc",Form("DHC Analysis, adding task %s",dhcTask->GetName()));
  mgr->AddTask(dhcTask);
  AliAnalysisDataContainer *co_Dhc = mgr->CreateContainer(Form("Cont_%s",chNewTaskName),
                                                          TList::Class(),
                                                          AliAnalysisManager::kOutputContainer,
                                                          Form("%s:PWGCF_out_%s", AliAnalysisManager::GetCommonFileName(), chNewTaskName));
  mgr->ConnectInput(dhcTask,0,mgr->GetCommonInputContainer());
  mgr->ConnectOutput(dhcTask,1,co_Dhc);

  return dhcTask;
}
<commit_msg>add iana4<commit_after>// $Id$

// File config location
// alien:///alice/cern.ch/user/t/tschuste/correction_hybrid_nulled.root

AliDhcTask *AddTaskDhc(
  Int_t iAna = 2,
  TString chUName = "",
  TString chHEffFile = "",
  TString chMuEffFile = "",
  TString chTaskFile = "",
  TString chTaskName = "",
  TString chNTracks = "PicoTracks"
)
{
  Char_t chExtraName[256];

  // Get the analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskDhc", "No analysis manager found.");
    return;
  }

  // ESD or AOD? write into the task name etc.
  sprintf(chExtraName,"_%s",mgr->GetInputEventHandler()->GetDataType());

  AliDhcTask *dhcTask = 0x0;

  // if string chTaskFile is given, load a pre-configured task from file
  if (!chTaskFile.EqualTo("")) {
    iAna=999;
    TFile *fiDhcTask = 0x0;
    fiDhcTask = TFile::Open(chTaskFile,"OLD");
    if (!fiDhcTask){
      Error("AddTaskDhc",Form("Requested file: %s was not opened. ABORT.",chTaskFile));
      return;
    }
    dhcTask = (AliDhcTask*) fiDhcTask->Get(chTaskName);
  }
  else { // create a new task
    // Binning
    Double_t arPt[5] = {0.5, 1.0, 2.0, 4.0};
    TAxis *axPt = new TAxis(3,arPt);
    Double_t arCent[5] = {0.0, 20.0, 40.0, 60.0, 100.0};
    TAxis *axCent = new TAxis(4,arCent);
    TAxis *axZvtx = new TAxis(1,-10.0,10.0);
    Double_t arCentMix[9] = {0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 80.0, 100.0};
    TAxis *axCentMix = new TAxis(8,arCentMix);
    TAxis *axZvtxMix = new TAxis(8,-10.0,10.0);

    // Efficiency correction files
    TFile *fiHEff  = 0x0;
    TFile *fiMuEff = 0x0;
    THnF* hHEff    = 0x0;
    THnF* hMuEff   = 0x0;
    if (!chHEffFile.EqualTo("")) {
      fiHEff = TFile::Open(chHEffFile,"OLD");
      if (!fiHEff){
        Error("AddTaskDhc",Form("Requested file: %s was not opened. ABORT.",chHEffFile));
        return;
      }
      hHEff = (THnF*) fiHEff->Get("correction");
    }
    if (!chMuEffFile.EqualTo("")) {
      fiMuEff = TFile::Open(chMuEffFile,"OLD");
      if (!fiMuEff){
        Error("AddTaskDhc",Form("Requested file: %s was not opened. ABORT.",chMuEffFile));
        return;
      }
      hMuEff = (THnF*) fiMuEff->Get("correction");
    }

    dhcTask = new AliDhcTask("Task_Dhc_Temp_Name");
    if (iAna==1) { // h-h
      Int_t nDetaBins = 40;
      Int_t nDPhiBins = 72;
      dhcTask->SetAnaMode(AliDhcTask::kHH);
      dhcTask->SetHEffT(hHEff);
      dhcTask->SetHEffA(hHEff);
      dhcTask->SetEtaMax(1.2);
      dhcTask->SetPtTACrit(kTRUE);
      sprintf(chExtraName,"%s_HH",chExtraName);
      if (hHEff) {
        sprintf(chExtraName,"%s_corrH",chExtraName);
      }
    } else if (iAna==2) { // mu-h
      Int_t nDetaBins = 100;
      Int_t nDPhiBins = 36;
      dhcTask->SetAnaMode(AliDhcTask::kMuH);
      dhcTask->SetHEffT(hMuEff);
      dhcTask->SetHEffA(hHEff);
      dhcTask->SetEtaMax(5.0);
      dhcTask->SetPtTACrit(kFALSE);
      sprintf(chExtraName,"%s_MuH",chExtraName);
      if (hMuEff) {
        sprintf(chExtraName,"%s_corrMu",chExtraName);
      }
      if (hHEff) {
        sprintf(chExtraName,"%s_corrH",chExtraName);
      }
    } else if (iAna==4) { // mu-mu
      Int_t nDetaBins = 60;
      Int_t nDPhiBins = 36;
      dhcTask->SetAnaMode(AliDhcTask::kMuMu);
      dhcTask->SetHEffT(hMuEff);
      dhcTask->SetHEffA(hHEff);
      dhcTask->SetEtaMax(5.0);
      dhcTask->SetPtTACrit(kFALSE);
      sprintf(chExtraName,"%s_MuMu",chExtraName);
      if (hMuEff) {
        sprintf(chExtraName,"%s_corrMu",chExtraName);
      }
      if (hHEff) {
        sprintf(chExtraName,"%s_corrH",chExtraName);
      }
    } else {
      Error("AddTaskDhc", Form("iAna %d not known", iAna));
    }
    dhcTask->SetTracksName(chNTracks);
    dhcTask->SetDoWeights(kFALSE);
    dhcTask->SetCentMethod("V0M");
    dhcTask->SetDEtaDPhiBins(nDetaBins,nDPhiBins);
    dhcTask->SetPtTBins(axPt);
    dhcTask->SetPtABins(axPt);
    dhcTask->SetCentBins(axCent);
    dhcTask->SetZVtxBins(axZvtx);
    dhcTask->SetCentMixBins(axCentMix);
    dhcTask->SetZVtxMixBins(axZvtxMix);
    dhcTask->SelectCollisionCandidates(AliVEvent::kINT7);
    dhcTask->SetVerbosity(0);
  }
  if (!dhcTask) {
    Error("AddTaskDhc","no dhcTask");
    return 0x0;
  }

  // make a unique task name
  Char_t chNewTaskName[256];
  if (chTaskName.EqualTo("")) {
    sprintf(chNewTaskName,"Task_Dhc%s%s",chExtraName,chUName.Data());
  } else {
    sprintf(chNewTaskName,"%s",chTaskName);
  }

  AliDhcTask *mgrTask = mgr->GetTask(chNewTaskName);
  if (mgrTask)
    sprintf(chNewTaskName,"%s_bis%04.0f",chNewTaskName,10000*gRandom->Rndm());

  dhcTask->SetName(chNewTaskName);
  Info("AddTaskDhc",Form("DHC Analysis, adding task %s",dhcTask->GetName()));
  mgr->AddTask(dhcTask);
  AliAnalysisDataContainer *co_Dhc = mgr->CreateContainer(Form("Cont_%s",chNewTaskName),
                                                          TList::Class(),
                                                          AliAnalysisManager::kOutputContainer,
                                                          Form("%s:PWGCF_out_%s", AliAnalysisManager::GetCommonFileName(), chNewTaskName));
  mgr->ConnectInput(dhcTask,0,mgr->GetCommonInputContainer());
  mgr->ConnectOutput(dhcTask,1,co_Dhc);

  return dhcTask;
}
<|endoftext|>