<commit_before>/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-  */
/*
 * player.cc
 * Copyright (C) 2016 Unknown <jnarical@gmail.com>
 *
 */

#include "player.h"

Player::Player (Battlefield *btl) :
m_name( "Nameless hero" ),
m_level( START_LEVEL ),
m_exp( START_EXP ), m_expMax( START_MAX_EXP ),
m_damage( START_DAMAGE ),
m_HP( START_MAX_HP ), m_maxHP( START_MAX_HP ),
m_mana( START_MAX_MANA ), m_maxMana( START_MAX_MANA ),
m_sightRadius( SIGHT_RADIUS ),
m_battlefield( btl ),
m_target( NULL ),
m_display( NULL )
{
	m_battlefield->SetPlayer(this);
	Field *tempField = NULL;
	while (true)
	{
		uint8_t row = rand() % m_battlefield->GetSize();
		uint8_t col = rand() % m_battlefield->GetSize();
		tempField = m_battlefield->GetField(row, col);
		if (!tempField->HaveEnemy() && !tempField->HaveItem()) break;
	}
	m_position = tempField;
}

/*
Player::Player (const Player &p)
{
	m_name = p.m_name;
	m_level = p.m_level;
	m_exp = p.m_exp;
	m_expMax = p.m_expMax;
	m_damage = p.m_damage;
	m_HP = p.m_HP;
	m_maxHP = p.m_maxHP;
	m_mana = p.m_mana;
	m_maxMana = p.m_maxMana;
	m_sightRadius = p.m_sightRadius;

	m_battlefield = p.m_battlefield;
	m_display = p.m_display;
	m_position = p.m_position;
	m_target = NULL;
}
*/

void Player::Act(int input_key)
{
	Field *currentField = m_position;
	Field *nextField = currentField;
	Field *targetField = GetTarget();

	switch(input_key)
	{
		case KEY_LEFT:  nextField = m_battlefield->GetNextField(currentField, LEFT); break;
		case KEY_RIGHT:	nextField = m_battlefield->GetNextField(currentField, RIGHT); break;
		case KEY_UP:	nextField = m_battlefield->GetNextField(currentField, UP); break;
		case KEY_DOWN:  nextField = m_battlefield->GetNextField(currentField, DOWN);
	}

	if (nextField != currentField) //if we're moving somewhere
	{
		if (nextField == targetField) //where our target is
		{
			m_battlefield->Fight(this, targetField->GetEnemy()); //Kill'em!
		}
		else //if target was somewhere else
		{
			SetTarget(NULL); //forget about it

			if (nextField->HaveEnemy()) // select new target if any
			{
				SetTarget(nextField);
				m_battlefield->CalculateFutureFight(); // calculate future fight
			}
			else
			{
				m_position = nextField; //if there's no enemy - move there and look around
				LookAround();
			}
		}
	}
}

void Player::LookAround()
{
	uint8_t radius	= m_sightRadius;
	uint8_t column	= m_position->GetCol();
	uint8_t row		= m_position->GetRow();

	uint8_t leftBorder		= column;
	uint8_t rightBorder		= column;
	uint8_t topBorder		= row;
	uint8_t bottomBorder	= row;
	uint8_t maxCoord		= m_battlefield->GetSize() - 1;

	for (uint8_t delta = 1; delta <= radius; ++delta)   // Crop sight rectangle to battlefield
	{
		if (leftBorder - delta <= 0) leftBorder = 0; else --leftBorder;
		if (rightBorder + delta >= maxCoord) rightBorder = maxCoord; else ++rightBorder;
		if (topBorder - delta <= 0) topBorder = 0; else --topBorder;
		if (bottomBorder + delta >= maxCoord) bottomBorder = maxCoord; else ++bottomBorder;
	}

	for (uint8_t tempRow = topBorder; tempRow <= bottomBorder; ++tempRow)
		for (uint8_t tempColumn = leftBorder; tempColumn <= rightBorder; ++tempColumn)
			if ( InSightRadius(tempRow, tempColumn) )
			{
				Field *field = m_battlefield->GetField(tempRow, tempColumn);
				field->MakeVisible();
				AddMana(field->GetMana());
				AddHP(field->GetHP());
			}
}

void Player::GainExp(Monster *enemy)
{
	int delta = enemy->GetLevel() - m_level;
	int mult = (delta <= 0 ? 1 : delta + 1);
	m_exp += enemy->GetLevel() * mult * 2;
	if (m_exp >= m_expMax) LevelUp();
}

void Player::LevelUp()
{
 	while (m_exp >= m_expMax)
 	{
 	 	m_level++;
 	 	m_exp -= m_expMax;
 	 	m_expMax *= EXP_TO_NEXT_LVL_MULTIPLIER;
 	 	m_maxHP += ADD_MAXHP_PER_LVL;
 	 	m_damage += ADD_DAMAGE_PER_LVL;
 	 	SetHpFull();
 	 	SetManaFull();
 	}
	m_display->SendEvent(LVLUP);
}

bool Player::InSightRadius(uint8_t testRow, uint8_t testColumn)
{
	uint8_t column  = m_position->GetCol();
	uint8_t row		= m_position->GetRow();
	uint8_t radius  = m_sightRadius;
	int deltaRow	= testRow - row;
	int deltaColumn = testColumn - column;

	return (deltaRow * deltaRow + deltaColumn * deltaColumn <= radius * radius);
}

void Player::SetMana(uint8_t newQuantity)
{
	m_mana = newQuantity;
	//TODO: добавить проверку
}

void Player::SetManaFull()
{
	m_mana = m_maxMana;
}

void Player::AddMana(uint8_t delta)
{
	m_mana = (m_mana + delta > m_maxMana ? m_maxMana : m_mana + delta);
}

void Player::LoseMana(uint8_t delta)
{
	m_mana = (m_mana - delta < 0 ? 0 : m_mana - delta);
}

void Player::SetHP(uint8_t newQuantity)
{
	m_HP = newQuantity;
	//TODO: добавить проверку
}

void Player::SetHpFull()
{
	m_HP = m_maxHP;
}

void Player::AddHP(uint8_t delta)
{
	m_HP = (m_HP + delta > m_maxHP ? m_maxHP : m_HP + delta);
}

void Player::LoseHP(uint8_t delta)
{
	m_HP = (m_HP - delta < 0 ? 0 : m_HP - delta);
}

void Player::SetTarget(Field * fld)
{
	m_target = fld;
}

void Player::SetDisplay(Display * dspl)
{
	m_display = dspl;
}

Field * Player::GetTarget() const
{
	return 	m_target;
}

Field * Player::GetPosition() const
{
	return m_position;
}

bool Player::IsAlive() const
{
	return m_HP;
}

bool Player::HaveTarget() const
{
	return (m_target != NULL);
}

std::string Player::GetName() const
{
	return m_name;
}

uint8_t Player::GetLevel() const
{
	return m_level;
}

uint8_t Player::GetExp() const
{
	return m_exp;
}

uint8_t Player::GetExpMax() const
{
	return m_expMax;
}

uint8_t Player::GetDamage() const
{
	return m_damage;
}

uint8_t Player::GetHP() const
{
	return m_HP;
}

uint8_t Player::GetMaxHP() const
{
	return m_maxHP;
}

uint8_t Player::GetMana() const
{
	return m_mana;
}

uint8_t Player::GetMaxMana() const
{
	return m_maxMana;
}

<commit_msg>fix: recalculate next fight after each successful fight<commit_after>/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-  */
/*
 * player.cc
 * Copyright (C) 2016 Unknown <jnarical@gmail.com>
 *
 */

#include "player.h"

Player::Player (Battlefield *btl) :
m_name( "Nameless hero" ),
m_level( START_LEVEL ),
m_exp( START_EXP ), m_expMax( START_MAX_EXP ),
m_damage( START_DAMAGE ),
m_HP( START_MAX_HP ), m_maxHP( START_MAX_HP ),
m_mana( START_MAX_MANA ), m_maxMana( START_MAX_MANA ),
m_sightRadius( SIGHT_RADIUS ),
m_battlefield( btl ),
m_target( NULL ),
m_display( NULL )
{
	m_battlefield->SetPlayer(this);
	Field *tempField = NULL;
	while (true)
	{
		uint8_t row = rand() % m_battlefield->GetSize();
		uint8_t col = rand() % m_battlefield->GetSize();
		tempField = m_battlefield->GetField(row, col);
		if (!tempField->HaveEnemy() && !tempField->HaveItem()) break;
	}
	m_position = tempField;
}

/*
Player::Player (const Player &p)
{
	m_name = p.m_name;
	m_level = p.m_level;
	m_exp = p.m_exp;
	m_expMax = p.m_expMax;
	m_damage = p.m_damage;
	m_HP = p.m_HP;
	m_maxHP = p.m_maxHP;
	m_mana = p.m_mana;
	m_maxMana = p.m_maxMana;
	m_sightRadius = p.m_sightRadius;

	m_battlefield = p.m_battlefield;
	m_display = p.m_display;
	m_position = p.m_position;
	m_target = NULL;
}
*/

void Player::Act(int input_key)
{
	Field *currentField = m_position;
	Field *nextField = currentField;
	Field *targetField = GetTarget();

	switch(input_key)
	{
		case KEY_LEFT:  nextField = m_battlefield->GetNextField(currentField, LEFT); break;
		case KEY_RIGHT:	nextField = m_battlefield->GetNextField(currentField, RIGHT); break;
		case KEY_UP:	nextField = m_battlefield->GetNextField(currentField, UP); break;
		case KEY_DOWN:  nextField = m_battlefield->GetNextField(currentField, DOWN);
	}

	if (nextField != currentField) //if we're moving somewhere
	{
		if (nextField == targetField) //where our target is
		{
			m_battlefield->Fight(this, targetField->GetEnemy()); //Kill'em!
			if ( HaveTarget() ) m_battlefield->CalculateFutureFight(); //if enemy still alive calculate next fight
		}
		else //if target was somewhere else
		{
			SetTarget(NULL); //forget about it

			if (nextField->HaveEnemy()) // select new target if any
			{
				SetTarget(nextField);
				m_battlefield->CalculateFutureFight(); // calculate future fight
			}
			else
			{
				m_position = nextField; //if there's no enemy - move there and look around
				LookAround();
			}
		}
	}
}

void Player::LookAround()
{
	uint8_t radius	= m_sightRadius;
	uint8_t column	= m_position->GetCol();
	uint8_t row		= m_position->GetRow();

	uint8_t leftBorder		= column;
	uint8_t rightBorder		= column;
	uint8_t topBorder		= row;
	uint8_t bottomBorder	= row;
	uint8_t maxCoord		= m_battlefield->GetSize() - 1;

	for (uint8_t delta = 1; delta <= radius; ++delta)   // Crop sight rectangle to battlefield
	{
		if (leftBorder - delta <= 0) leftBorder = 0; else --leftBorder;
		if (rightBorder + delta >= maxCoord) rightBorder = maxCoord; else ++rightBorder;
		if (topBorder - delta <= 0) topBorder = 0; else --topBorder;
		if (bottomBorder + delta >= maxCoord) bottomBorder = maxCoord; else ++bottomBorder;
	}

	for (uint8_t tempRow = topBorder; tempRow <= bottomBorder; ++tempRow)
		for (uint8_t tempColumn = leftBorder; tempColumn <= rightBorder; ++tempColumn)
			if ( InSightRadius(tempRow, tempColumn) )
			{
				Field *field = m_battlefield->GetField(tempRow, tempColumn);
				field->MakeVisible();
				AddMana(field->GetMana());
				AddHP(field->GetHP());
			}
}

void Player::GainExp(Monster *enemy)
{
	int delta = enemy->GetLevel() - m_level;
	int mult = (delta <= 0 ? 1 : delta + 1);
	m_exp += enemy->GetLevel() * mult * 2;
	if (m_exp >= m_expMax) LevelUp();
}

void Player::LevelUp()
{
 	while (m_exp >= m_expMax)
 	{
 	 	m_level++;
 	 	m_exp -= m_expMax;
 	 	m_expMax *= EXP_TO_NEXT_LVL_MULTIPLIER;
 	 	m_maxHP += ADD_MAXHP_PER_LVL;
 	 	m_damage += ADD_DAMAGE_PER_LVL;
 	 	SetHpFull();
 	 	SetManaFull();
 	}
	m_display->SendEvent(LVLUP);
}

bool Player::InSightRadius(uint8_t testRow, uint8_t testColumn)
{
	uint8_t column  = m_position->GetCol();
	uint8_t row		= m_position->GetRow();
	uint8_t radius  = m_sightRadius;
	int deltaRow	= testRow - row;
	int deltaColumn = testColumn - column;

	return (deltaRow * deltaRow + deltaColumn * deltaColumn <= radius * radius);
}

void Player::SetMana(uint8_t newQuantity)
{
	m_mana = newQuantity;
	//TODO: добавить проверку
}

void Player::SetManaFull()
{
	m_mana = m_maxMana;
}

void Player::AddMana(uint8_t delta)
{
	m_mana = (m_mana + delta > m_maxMana ? m_maxMana : m_mana + delta);
}

void Player::LoseMana(uint8_t delta)
{
	m_mana = (m_mana - delta < 0 ? 0 : m_mana - delta);
}

void Player::SetHP(uint8_t newQuantity)
{
	m_HP = newQuantity;
	//TODO: добавить проверку
}

void Player::SetHpFull()
{
	m_HP = m_maxHP;
}

void Player::AddHP(uint8_t delta)
{
	m_HP = (m_HP + delta > m_maxHP ? m_maxHP : m_HP + delta);
}

void Player::LoseHP(uint8_t delta)
{
	m_HP = (m_HP - delta < 0 ? 0 : m_HP - delta);
}

void Player::SetTarget(Field * fld)
{
	m_target = fld;
}

void Player::SetDisplay(Display * dspl)
{
	m_display = dspl;
}

Field * Player::GetTarget() const
{
	return 	m_target;
}

Field * Player::GetPosition() const
{
	return m_position;
}

bool Player::IsAlive() const
{
	return m_HP;
}

bool Player::HaveTarget() const
{
	return (m_target != NULL);
}

std::string Player::GetName() const
{
	return m_name;
}

uint8_t Player::GetLevel() const
{
	return m_level;
}

uint8_t Player::GetExp() const
{
	return m_exp;
}

uint8_t Player::GetExpMax() const
{
	return m_expMax;
}

uint8_t Player::GetDamage() const
{
	return m_damage;
}

uint8_t Player::GetHP() const
{
	return m_HP;
}

uint8_t Player::GetMaxHP() const
{
	return m_maxHP;
}

uint8_t Player::GetMana() const
{
	return m_mana;
}

uint8_t Player::GetMaxMana() const
{
	return m_maxMana;
}

<|endoftext|>


<commit_before>// null-conduit.cc
//
// Copyright (C) 2000 by Dan Pilone, Adriaan de Groot
//
// This file is distributed under the Gnu General Public Licence (GPL).
// The GPL should have been included with this file in a file called
// COPYING.
//
// This is the version of null-conduit.cc for KDE 2 / KPilot 4

// The NULL conduit is a conduit that does nothing.
// It's just a programming example, and maybe sometime
// we can attach it to databases as a means of *not*
// doing anything with those databases.
//
//

#include "options.h"

// Only include what we really need:
// First UNIX system stuff, then std C++,
// then Qt, then KDE, then local includes.
//
//
#include <stream.h>
#include <kmessagebox.h>
#include <kconfig.h>
#include <kdebug.h>

#include "conduitApp.h"
#include "kpilotlink.h"
#include "null-conduit.h"
#include "setupDialog.h"

// Something to allow us to check what revision
// the modules are that make up a binary distribution.
//
//
static const char *id=
	"$Id$";

// This is a generic main() function, all
// conduits look basically the same,
// except for the name of the conduit.
//
//
int main(int argc, char* argv[])
{
#ifdef KDE2
	ConduitApp a(argc,argv,"null-conduit",
		I18N_NOOP("NULL Conduit"),
		"4.0b");

	a.addAuthor("Adriaan de Groot",
		"NULL Conduit author",
		"adridg@sci.kun.nl");
#else
	ConduitApp a(argc, argv, "null-conduit",
		"\t\tNull-Conduit -- A conduit for KPilot\n"
		"Copyright (C) 2000 Adriaan de Groot");
#endif

	NullConduit conduit(a.getMode());
	a.setConduit(&conduit);
	return a.exec();
}

// A conduit that does nothing has a very
// simple constructor and destructor.
//
//
NullConduit::NullConduit(eConduitMode mode)
	: BaseConduit(mode)
{
	FUNCTIONSETUP;

}

NullConduit::~NullConduit()
{
	FUNCTIONSETUP;

}

// doSync should add a line to the logfile
// with the indicated text, but the
// addSyncLogEntry() doesn't work (not
// in any other conduit, either).
//
// Just print the message to error.
//
//
void
NullConduit::doSync()
{
	FUNCTIONSETUP;

	KConfig& config = KPilotLink::getConfig();
	config.setGroup(NullOptions::NullGroup);

	QString m=config.readEntry("Text");
	addSyncLogMessage(m.latin1());

	kdDebug() << fname << ": Message from null-conduit:\n"
		<< fname << ": " << m
		<< endl;
}

// aboutAndSetup is pretty much the same
// on all conduits as well.
//
//
QWidget*
NullConduit::aboutAndSetup()
{
	FUNCTIONSETUP;

	return new NullOptions(0L);
}

const char *
NullConduit::dbInfo()
{
	KConfig& config = KPilotLink::getConfig(NullOptions::NullGroup);

	QString m = config.readEntry("DB");
	if (m.isNull())
	{
		return "";
	}
	else
	{
		return m.ascii();
	}
}

// $Log$
// Revision 1.9  2000/11/02 23:10:32  adridg
// Added attach-to-database feature
//
// Revision 1.8  2000/09/27 18:41:21  adridg
// Added author info and new QT layout code.
//
// Revision 1.7  2000/09/05 07:13:57  adridg
// Updated to KCmdLineArgs
//
// Revision 1.6  2000/08/28 12:22:03  pilone
// 	KDE 2.0 Cleanup patches.  Start of adding conduits as kpilot
// services.
//
// Revision 1.5  2000/07/27 23:07:16  pilone
// 	Ported the conduits.  They build.  Don't know if they work, but they
// build.
//
// Revision 1.8  2000/07/20 21:29:42  adridg
// Minor KDE1 & KDE2 interoperability issues
//
// Revision 1.7  2000/07/19 20:12:06  adridg
// Added KDE2 code
//
// Revision 1.6  2000/07/13 18:08:42  adridg
// Restructuring and sanitation of config files
//
// Revision 1.5  2000/07/10 21:23:33  adridg
// Adjusted to changes in setupDialog class
//
// Revision 1.4  2000/05/21 00:42:53  adridg
// Changed to reflect new debug guidelines and usage()
//
// Revision 1.3  2000/01/23 23:13:59  adridg
// Unified dialog layout
//
// Revision 1.2  2000/01/22 23:01:27  adridg
// Minor ID stuff
//
// Revision 1.1  2000/01/21 16:31:38  adridg
// Added null conduit to 3.1b11 (KDE 1.1.2)
//
// Revision 1.2  2000/01/17 13:50:21  adridg
// Fixed resize bugs; log null-conduit message; lots of comments added as example
//
<commit_msg>Handle setup properly<commit_after>// null-conduit.cc
//
// Copyright (C) 2000 by Dan Pilone, Adriaan de Groot
//
// This file is distributed under the Gnu General Public Licence (GPL).
// The GPL should have been included with this file in a file called
// COPYING.
//
// This is the version of null-conduit.cc for KDE 2 / KPilot 4

// The NULL conduit is a conduit that does nothing.
// It's just a programming example, and maybe sometime
// we can attach it to databases as a means of *not*
// doing anything with those databases.
//
//

#include "options.h"

// Only include what we really need:
// First UNIX system stuff, then std C++,
// then Qt, then KDE, then local includes.
//
//
#include <stream.h>
#include <kmessagebox.h>
#include <kconfig.h>
#include <kdebug.h>

#include "conduitApp.h"
#include "kpilotlink.h"
#include "null-conduit.h"
#include "setupDialog.h"

// Something to allow us to check what revision
// the modules are that make up a binary distribution.
//
//
static const char *id=
	"$Id$";

// This is a generic main() function, all
// conduits look basically the same,
// except for the name of the conduit.
//
//
int main(int argc, char* argv[])
{
#ifdef KDE2
	ConduitApp a(argc,argv,"null-conduit",
		I18N_NOOP("NULL Conduit"),
		"4.0b");

	a.addAuthor("Adriaan de Groot",
		"NULL Conduit author",
		"adridg@sci.kun.nl");
#else
	ConduitApp a(argc, argv, "null-conduit",
		"\t\tNull-Conduit -- A conduit for KPilot\n"
		"Copyright (C) 2000 Adriaan de Groot");
#endif

	NullConduit conduit(a.getMode());
	a.setConduit(&conduit);
	return a.exec();
}

// A conduit that does nothing has a very
// simple constructor and destructor.
//
//
NullConduit::NullConduit(eConduitMode mode)
	: BaseConduit(mode)
{
	FUNCTIONSETUP;

}

NullConduit::~NullConduit()
{
	FUNCTIONSETUP;

}

// doSync should add a line to the logfile
// with the indicated text, but the
// addSyncLogEntry() doesn't work (not
// in any other conduit, either).
//
// Just print the message to error.
//
//
void
NullConduit::doSync()
{
	FUNCTIONSETUP;

	KConfig& config = KPilotLink::getConfig();
	config.setGroup(NullOptions::NullGroup);

	QString m=config.readEntry("Text");
	addSyncLogMessage(m.latin1());

	kdDebug() << fname << ": Message from null-conduit:\n"
		<< fname << ": " << m
		<< endl;
}

// aboutAndSetup is pretty much the same
// on all conduits as well.
//
//
QWidget*
NullConduit::aboutAndSetup()
{
	FUNCTIONSETUP;

	return new NullOptions(0L);
}

const char *
NullConduit::dbInfo()
{
	KConfig& config = KPilotLink::getConfig(NullOptions::NullGroup);

	QString m = config.readEntry("DB");
	if (m.isNull())
	{
		return "<none>";
	}
	else
	{
		return m.ascii();
	}
}

// $Log$
// Revision 1.10  2000/11/13 08:52:31  adridg
// Much getConfig() grief averted
//
// Revision 1.9  2000/11/02 23:10:32  adridg
// Added attach-to-database feature
//
// Revision 1.8  2000/09/27 18:41:21  adridg
// Added author info and new QT layout code.
//
// Revision 1.7  2000/09/05 07:13:57  adridg
// Updated to KCmdLineArgs
//
// Revision 1.6  2000/08/28 12:22:03  pilone
// 	KDE 2.0 Cleanup patches.  Start of adding conduits as kpilot
// services.
//
// Revision 1.5  2000/07/27 23:07:16  pilone
// 	Ported the conduits.  They build.  Don't know if they work, but they
// build.
//
// Revision 1.8  2000/07/20 21:29:42  adridg
// Minor KDE1 & KDE2 interoperability issues
//
// Revision 1.7  2000/07/19 20:12:06  adridg
// Added KDE2 code
//
// Revision 1.6  2000/07/13 18:08:42  adridg
// Restructuring and sanitation of config files
//
// Revision 1.5  2000/07/10 21:23:33  adridg
// Adjusted to changes in setupDialog class
//
// Revision 1.4  2000/05/21 00:42:53  adridg
// Changed to reflect new debug guidelines and usage()
//
// Revision 1.3  2000/01/23 23:13:59  adridg
// Unified dialog layout
//
// Revision 1.2  2000/01/22 23:01:27  adridg
// Minor ID stuff
//
// Revision 1.1  2000/01/21 16:31:38  adridg
// Added null conduit to 3.1b11 (KDE 1.1.2)
//
// Revision 1.2  2000/01/17 13:50:21  adridg
// Fixed resize bugs; log null-conduit message; lots of comments added as example
//
<|endoftext|>


<commit_before>#include "server.hpp"

// #define DEBUG

using namespace server;

Server::Server() {
  initialize();
}

Server::Server(IP_Stack stack) : inet_(stack) {}

net::Inet4<VirtioNet>& Server::ip_stack() const {
  return *inet_;
}

Router& Server::router() noexcept {
  return router_;
}

void Server::listen(Port port) {
  printf("Listening to port %i \n", port);

  inet_->tcp().bind(port).onConnect(OnConnect::from<Server, &Server::connect>(this));
}

void Server::connect(net::TCP::Connection_ptr conn) {
  printf("<Server> Connection from %s\n", conn->remote().to_string().c_str());
  // if there is a free spot in connections
  if(free_idx_.size() > 0) {
    auto idx = free_idx_.back();
    connections_[idx] = std::make_shared<Connection>(*this, conn, idx);
    free_idx_.pop_back();
  }
  // if not, add a new shared ptr
  else {
    connections_.emplace_back(new Connection{*this, conn, connections_.size()});
  }
}

void Server::initialize() {
  auto& eth0 = hw::Dev::eth<0,VirtioNet>();
  //-------------------------------
  inet_ = std::make_shared<net::Inet4<VirtioNet>>(eth0);
  //-------------------------------
  inet_->network_config({ 10,0,0,42 },     // IP
      { 255,255,255,0 }, // Netmask
      { 10,0,0,1 },      // Gateway
      { 8,8,8,8 });      // DNS
}

void Server::close(size_t idx) {
  connections_[idx] = nullptr;
  free_idx_.push_back(idx);
}

void Server::process(Request_ptr req, Response_ptr res) {
  router_[{req->method(), req->uri()}](*req, res);
}
<commit_msg>added ensure<commit_after>#include "server.hpp"

// #define DEBUG

using namespace server;

Server::Server() {
  initialize();
}

Server::Server(IP_Stack stack) : inet_(stack) {}

net::Inet4<VirtioNet>& Server::ip_stack() const {
  return *inet_;
}

Router& Server::router() noexcept {
  return router_;
}

void Server::listen(Port port) {
  printf("Listening to port %i \n", port);

  inet_->tcp().bind(port).onConnect(OnConnect::from<Server, &Server::connect>(this));
}

void Server::connect(net::TCP::Connection_ptr conn) {
  printf("<Server> Connection from %s\n", conn->remote().to_string().c_str());
  // if there is a free spot in connections
  if(free_idx_.size() > 0) {
    auto idx = free_idx_.back();
    Ensures(connections_[idx] == nullptr);
    connections_[idx] = std::make_shared<Connection>(*this, conn, idx);
    free_idx_.pop_back();
  }
  // if not, add a new shared ptr
  else {
    connections_.emplace_back(new Connection{*this, conn, connections_.size()});
  }
}

void Server::initialize() {
  auto& eth0 = hw::Dev::eth<0,VirtioNet>();
  //-------------------------------
  inet_ = std::make_shared<net::Inet4<VirtioNet>>(eth0);
  //-------------------------------
  inet_->network_config({ 10,0,0,42 },     // IP
      { 255,255,255,0 }, // Netmask
      { 10,0,0,1 },      // Gateway
      { 8,8,8,8 });      // DNS
}

void Server::close(size_t idx) {
  connections_[idx] = nullptr;
  free_idx_.push_back(idx);
}

void Server::process(Request_ptr req, Response_ptr res) {
  router_[{req->method(), req->uri()}](*req, res);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: macro.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2008-02-27 10:04:59 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _RTL_MACRO_HXX
#define _RTL_MACRO_HXX

#include <rtl/bootstrap.h>
#include <rtl/ustring.hxx>

#if defined WIN32
#define THIS_OS "Windows"
#elif defined OS2
#define THIS_OS "OS/2"
#elif defined SOLARIS
#define THIS_OS "Solaris"
#elif defined LINUX
#define THIS_OS "Linux"
#elif defined MACOSX
#define THIS_OS "MacOSX"
#elif defined NETBSD
#define THIS_OS "NetBSD"
#elif defined FREEBSD
#define THIS_OS "FreeBSD"
#elif defined IRIX
#define THIS_OS "Irix"
#endif

#if ! defined THIS_OS
#error "unknown OS -- insert your OS identifier above"
this is inserted for the case that the preprocessor ignores error
#endif

#if defined INTEL
#define THIS_ARCH "x86"
#elif defined POWERPC
#define THIS_ARCH "PowerPC"
#elif defined S390
#define THIS_ARCH "S390"
#elif defined SPARC
#define THIS_ARCH "SPARC"
#elif defined IRIX
#define THIS_ARCH "MIPS"
#elif defined X86_64
#define THIS_ARCH "X86_64"
#elif defined MIPS
#define THIS_ARCH "MIPS"
#elif defined ARM
#define THIS_ARCH "ARM"
#elif defined IA64
#define THIS_ARCH "IA64"
#endif

#if ! defined THIS_ARCH
#error "unknown ARCH -- insert your ARCH identifier above"
this is inserted for the case that the preprocessor ignores error
#endif

/*
  Expand macros via rtl_bootstrap_get.
  see
    http://udk.openoffice.org/common/man/spec/uno_default_bootstrapping.html
  for details.
*/
::rtl::OUString SAL_CALL expandMacros(rtlBootstrapHandle handle, const ::rtl::OUString & argstr);

#endif

<commit_msg>INTEGRATION: CWS sb83 (1.8.10); FILE MERGED 2008/03/17 09:01:16 sb 1.8.10.2: RESYNC: (1.8-1.9); FILE MERGED 2007/12/18 15:36:49 sb 1.8.10.1: #i84200# Refactored expandMacros so that I could add support for a ${.link:...} hack to simulate symbolic links under Windows.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: macro.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: vg $ $Date: 2008-03-18 13:18:19 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _RTL_MACRO_HXX
#define _RTL_MACRO_HXX

#include <rtl/bootstrap.h>
#include <rtl/ustring.hxx>

#if defined WIN32
#define THIS_OS "Windows"
#elif defined OS2
#define THIS_OS "OS/2"
#elif defined SOLARIS
#define THIS_OS "Solaris"
#elif defined LINUX
#define THIS_OS "Linux"
#elif defined MACOSX
#define THIS_OS "MacOSX"
#elif defined NETBSD
#define THIS_OS "NetBSD"
#elif defined FREEBSD
#define THIS_OS "FreeBSD"
#elif defined IRIX
#define THIS_OS "Irix"
#endif

#if ! defined THIS_OS
#error "unknown OS -- insert your OS identifier above"
this is inserted for the case that the preprocessor ignores error
#endif

#if defined INTEL
#define THIS_ARCH "x86"
#elif defined POWERPC
#define THIS_ARCH "PowerPC"
#elif defined S390
#define THIS_ARCH "S390"
#elif defined SPARC
#define THIS_ARCH "SPARC"
#elif defined IRIX
#define THIS_ARCH "MIPS"
#elif defined X86_64
#define THIS_ARCH "X86_64"
#elif defined MIPS
#define THIS_ARCH "MIPS"
#elif defined ARM
#define THIS_ARCH "ARM"
#elif defined IA64
#define THIS_ARCH "IA64"
#endif

#if ! defined THIS_ARCH
#error "unknown ARCH -- insert your ARCH identifier above"
this is inserted for the case that the preprocessor ignores error
#endif

#endif

<|endoftext|>


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

 Program:   openCherry Platform
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) German Cancer Research Center, Division of Medical and
 Biological Informatics. All rights reserved.
 See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "cherryQtDisplay.h"

#include <cherryPlatform.h>

#include <QApplication>

namespace cherry {

QtDisplay::QtDisplay()
{
  this->CreateDisplay();
}

bool QtDisplay::InDisplayThread()
{
  return displayThread == QThread::currentThread();
}

  void QtDisplay::AsyncExec(Poco::Runnable* runnable)
  {
    emit NewAsyncRunnable(runnable);
  }

  void QtDisplay::SyncExec(Poco::Runnable* runnable)
  {
    emit NewSyncRunnable(runnable);
  }

  int QtDisplay::RunEventLoop()
  {
    return QApplication::exec();
  }

  void QtDisplay::ExitEventLoop(int code)
  {
    QApplication::exit(code);
  }

  void QtDisplay::CreateDisplay()
  {
    Display::instance = this;
    displayThread = QThread::currentThread();

    char** argv;
    int& argc = Platform::GetRawApplicationArgs(argv);

    QApplication* app = new QApplication(argc, argv);

    this->connect(this, SIGNAL(NewAsyncRunnable(Poco::Runnable*)), this, SLOT(ExecuteRunnable(Poco::Runnable*)));
    this->connect(this, SIGNAL(NewSyncRunnable(Poco::Runnable*)), this, SLOT(ExecuteRunnable(Poco::Runnable*)), Qt::BlockingQueuedConnection);
  }

  void QtDisplay::ExecuteRunnable(Poco::Runnable* runnable)
  {
    runnable->run();
  }

}
<commit_msg>FIX (#2058): query if there is a QApplication before creating a new one; if there already is one, use this one<commit_after>/*=========================================================================

 Program:   openCherry Platform
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) German Cancer Research Center, Division of Medical and
 Biological Informatics. All rights reserved.
 See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "cherryQtDisplay.h"

#include <cherryPlatform.h>

#include <QApplication>

namespace cherry {

QtDisplay::QtDisplay()
{
  this->CreateDisplay();
}

bool QtDisplay::InDisplayThread()
{
  return displayThread == QThread::currentThread();
}

  void QtDisplay::AsyncExec(Poco::Runnable* runnable)
  {
    emit NewAsyncRunnable(runnable);
  }

  void QtDisplay::SyncExec(Poco::Runnable* runnable)
  {
    emit NewSyncRunnable(runnable);
  }

  int QtDisplay::RunEventLoop()
  {
    return QApplication::exec();
  }

  void QtDisplay::ExitEventLoop(int code)
  {
    QApplication::exit(code);
  }

  void QtDisplay::CreateDisplay()
  {
    Display::instance = this;
    displayThread = QThread::currentThread();

    char** argv;
    int& argc = Platform::GetRawApplicationArgs(argv);

    QApplication* app = QApplication::instance() ? qApp : new QApplication(argc, argv);

    this->connect(this, SIGNAL(NewAsyncRunnable(Poco::Runnable*)), this, SLOT(ExecuteRunnable(Poco::Runnable*)));
    this->connect(this, SIGNAL(NewSyncRunnable(Poco::Runnable*)), this, SLOT(ExecuteRunnable(Poco::Runnable*)), Qt::BlockingQueuedConnection);
  }

  void QtDisplay::ExecuteRunnable(Poco::Runnable* runnable)
  {
    runnable->run();
  }

}
<|endoftext|>


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

#include <cstdint>
#include <cstdio>
#include <signal.h>
#include <util/CommandOptionParser.h>
#include <thread>
#include "Configuration.h"
#include <Aeron.h>
#include <array>

using namespace aeron::util;
using namespace aeron;

std::atomic<bool> running (true);

void sigIntHandler (int param)
{
    running = false;
}

static const char optHelp     = 'h';
static const char optPrefix   = 'p';
static const char optChannel  = 'c';
static const char optStreamId = 's';
static const char optMessages = 'm';
static const char optLinger   = 'l';

struct Settings
{
    std::string dirPrefix = "";
    std::string channel = samples::configuration::DEFAULT_CHANNEL;
    std::int32_t streamId = samples::configuration::DEFAULT_STREAM_ID;
    int numberOfMessages = samples::configuration::DEFAULT_NUMBER_OF_MESSAGES;
    int lingerTimeoutMs = samples::configuration::DEFAULT_LINGER_TIMEOUT_MS;
};

typedef std::array<std::uint8_t, 256> buffer_t;

Settings parseCmdLine(CommandOptionParser& cp, int argc, char** argv)
{
    cp.parse(argc, argv);
    if (cp.getOption(optHelp).isPresent())
    {
        cp.displayOptionsHelp(std::cout);
        exit(0);
    }

    Settings s;

    s.dirPrefix = cp.getOption(optPrefix).getParam(0, s.dirPrefix);
    s.channel = cp.getOption(optChannel).getParam(0, s.channel);
    s.streamId = cp.getOption(optStreamId).getParamAsInt(0, 1, INT32_MAX, s.streamId);
    s.numberOfMessages = cp.getOption(optMessages).getParamAsInt(0, 0, INT32_MAX, s.numberOfMessages);
    s.lingerTimeoutMs = cp.getOption(optLinger).getParamAsInt(0, 0, 60 * 60 * 1000, s.lingerTimeoutMs);

    return s;
}

int main(int argc, char** argv)
{
    CommandOptionParser cp;
    cp.addOption(CommandOption (optHelp,     0, 0, "                Displays help information."));
    cp.addOption(CommandOption (optPrefix,   1, 1, "dir             Prefix directory for aeron driver."));
    cp.addOption(CommandOption (optChannel,  1, 1, "channel         Channel."));
    cp.addOption(CommandOption (optStreamId, 1, 1, "streamId        Stream ID."));
    cp.addOption(CommandOption (optMessages, 1, 1, "number          Number of Messages."));
    cp.addOption(CommandOption (optLinger,   1, 1, "milliseconds    Linger timeout in milliseconds."));

    signal (SIGINT, sigIntHandler);

    try
    {
        Settings settings = parseCmdLine(cp, argc, argv);

        std::cout << "Publishing to channel " << settings.channel << " on Stream ID " << settings.streamId << std::endl;

        aeron::Context context;

        if (settings.dirPrefix != "")
        {
            context.aeronDir(settings.dirPrefix);
        }

        context.newPublicationHandler(
            [](const std::string& channel, std::int32_t streamId, std::int32_t sessionId, std::int64_t correlationId)
            {
                std::cout << "Publication: " << channel << " " << correlationId << ":" << streamId << ":" << sessionId << std::endl;
            });

        std::shared_ptr<Aeron> aeron = Aeron::connect(context);

        // add the publication to start the process
        std::int64_t id = aeron->addPublication(settings.channel, settings.streamId);

        std::shared_ptr<Publication> publication = aeron->findPublication(id);
        // wait for the publication to be valid
        while (!publication)
        {
            std::this_thread::yield();
            publication = aeron->findPublication(id);
        }

        AERON_DECL_ALIGNED(buffer_t buffer, 16);
        concurrent::AtomicBuffer srcBuffer(&buffer[0], buffer.size());
        char message[256];

        for (int i = 0; i < settings.numberOfMessages && running; i++)
        {
#if _MSC_VER
            const int messageLen = ::sprintf_s(message, sizeof(message), "Hello World! %d", i);
#else
            const int messageLen = ::snprintf(message, sizeof(message), "Hello World! %d", i);
#endif

            srcBuffer.putBytes(0, reinterpret_cast<std::uint8_t *>(message), messageLen);

            std::cout << "offering " << i << "/" << settings.numberOfMessages;
            std::cout.flush();

            const std::int64_t result = publication->offer(srcBuffer, 0, messageLen);

            if (result < 0)
            {
                std::cout << " ah?!" << std::endl;
            }
            else
            {
                std::cout << " yay!" << std::endl;
            }

            std::this_thread::sleep_for(std::chrono::seconds(1));
        }

        std::cout << "Done sending." << std::endl;

        if (settings.lingerTimeoutMs > 0)
        {
            std::cout << "Lingering for " << settings.lingerTimeoutMs << " milliseconds." << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(settings.lingerTimeoutMs));
        }
    }
    catch (CommandOptionException& e)
    {
        std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
        cp.displayOptionsHelp(std::cerr);
        return -1;
    }
    catch (SourcedException& e)
    {
        std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl;
        return -1;
    }
    catch (std::exception& e)
    {
        std::cerr << "FAILED: " << e.what() << " : " << std::endl;
        return -1;
    }

    return 0;
}
<commit_msg>[C++]: add more feedback information for when offer fails for BasicPublisher.<commit_after>/*
 * Copyright 2014 - 2015 Real Logic Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cstdint>
#include <cstdio>
#include <signal.h>
#include <util/CommandOptionParser.h>
#include <thread>
#include "Configuration.h"
#include <Aeron.h>
#include <array>

using namespace aeron::util;
using namespace aeron;

std::atomic<bool> running (true);

void sigIntHandler (int param)
{
    running = false;
}

static const char optHelp     = 'h';
static const char optPrefix   = 'p';
static const char optChannel  = 'c';
static const char optStreamId = 's';
static const char optMessages = 'm';
static const char optLinger   = 'l';

struct Settings
{
    std::string dirPrefix = "";
    std::string channel = samples::configuration::DEFAULT_CHANNEL;
    std::int32_t streamId = samples::configuration::DEFAULT_STREAM_ID;
    int numberOfMessages = samples::configuration::DEFAULT_NUMBER_OF_MESSAGES;
    int lingerTimeoutMs = samples::configuration::DEFAULT_LINGER_TIMEOUT_MS;
};

typedef std::array<std::uint8_t, 256> buffer_t;

Settings parseCmdLine(CommandOptionParser& cp, int argc, char** argv)
{
    cp.parse(argc, argv);
    if (cp.getOption(optHelp).isPresent())
    {
        cp.displayOptionsHelp(std::cout);
        exit(0);
    }

    Settings s;

    s.dirPrefix = cp.getOption(optPrefix).getParam(0, s.dirPrefix);
    s.channel = cp.getOption(optChannel).getParam(0, s.channel);
    s.streamId = cp.getOption(optStreamId).getParamAsInt(0, 1, INT32_MAX, s.streamId);
    s.numberOfMessages = cp.getOption(optMessages).getParamAsInt(0, 0, INT32_MAX, s.numberOfMessages);
    s.lingerTimeoutMs = cp.getOption(optLinger).getParamAsInt(0, 0, 60 * 60 * 1000, s.lingerTimeoutMs);

    return s;
}

int main(int argc, char** argv)
{
    CommandOptionParser cp;
    cp.addOption(CommandOption (optHelp,     0, 0, "                Displays help information."));
    cp.addOption(CommandOption (optPrefix,   1, 1, "dir             Prefix directory for aeron driver."));
    cp.addOption(CommandOption (optChannel,  1, 1, "channel         Channel."));
    cp.addOption(CommandOption (optStreamId, 1, 1, "streamId        Stream ID."));
    cp.addOption(CommandOption (optMessages, 1, 1, "number          Number of Messages."));
    cp.addOption(CommandOption (optLinger,   1, 1, "milliseconds    Linger timeout in milliseconds."));

    signal (SIGINT, sigIntHandler);

    try
    {
        Settings settings = parseCmdLine(cp, argc, argv);

        std::cout << "Publishing to channel " << settings.channel << " on Stream ID " << settings.streamId << std::endl;

        aeron::Context context;

        if (settings.dirPrefix != "")
        {
            context.aeronDir(settings.dirPrefix);
        }

        context.newPublicationHandler(
            [](const std::string& channel, std::int32_t streamId, std::int32_t sessionId, std::int64_t correlationId)
            {
                std::cout << "Publication: " << channel << " " << correlationId << ":" << streamId << ":" << sessionId << std::endl;
            });

        std::shared_ptr<Aeron> aeron = Aeron::connect(context);

        // add the publication to start the process
        std::int64_t id = aeron->addPublication(settings.channel, settings.streamId);

        std::shared_ptr<Publication> publication = aeron->findPublication(id);
        // wait for the publication to be valid
        while (!publication)
        {
            std::this_thread::yield();
            publication = aeron->findPublication(id);
        }

        AERON_DECL_ALIGNED(buffer_t buffer, 16);
        concurrent::AtomicBuffer srcBuffer(&buffer[0], buffer.size());
        char message[256];

        for (int i = 0; i < settings.numberOfMessages && running; i++)
        {
#if _MSC_VER
            const int messageLen = ::sprintf_s(message, sizeof(message), "Hello World! %d", i);
#else
            const int messageLen = ::snprintf(message, sizeof(message), "Hello World! %d", i);
#endif

            srcBuffer.putBytes(0, reinterpret_cast<std::uint8_t *>(message), messageLen);

            std::cout << "offering " << i << "/" << settings.numberOfMessages;
            std::cout.flush();

            const std::int64_t result = publication->offer(srcBuffer, 0, messageLen);

            if (result < 0)
            {
                if (PUBLICATION_NOT_CONNECTED == result)
                {
                    std::cout << " not connected yet." << std::endl;
                }
                else if (PUBLICATION_BACK_PRESSURE == result)
                {
                    std::cout << " back pressured." << std::endl;
                }
                else
                {
                    std::cout << " ah?! unknown " << result << std::endl;
                }
            }
            else
            {
                std::cout << " yay!" << std::endl;
            }

            std::this_thread::sleep_for(std::chrono::seconds(1));
        }

        std::cout << "Done sending." << std::endl;

        if (settings.lingerTimeoutMs > 0)
        {
            std::cout << "Lingering for " << settings.lingerTimeoutMs << " milliseconds." << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(settings.lingerTimeoutMs));
        }
    }
    catch (CommandOptionException& e)
    {
        std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
        cp.displayOptionsHelp(std::cerr);
        return -1;
    }
    catch (SourcedException& e)
    {
        std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl;
        return -1;
    }
    catch (std::exception& e)
    {
        std::cerr << "FAILED: " << e.what() << " : " << std::endl;
        return -1;
    }

    return 0;
}
<|endoftext|>


<commit_before>// MediaInfo - All info about media files
// Copyright (C) 2002-2008 Jerome Martinez, Zen@MediaArea.net
//
// This library is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// For user: you can disable or enable it
//#define MEDIAINFO_DEBUG
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Compilation conditions
#include <MediaInfo/Setup.h>
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/MediaInfo.h"
#include "MediaInfo/MediaInfo_Internal.h"
using namespace ZenLib;
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//---------------------------------------------------------------------------
//To clarify the code
#ifdef MEDIAINFO_DEBUG
    #include <stdio.h>
    FILE* F;
    std::string Debug;

    #undef MEDIAINFO_DEBUG
    #define MEDIAINFO_DEBUG(_TOAPPEND) \
        F=fopen("MediaInfo_Debug.txt", "a+t"); \
        Debug.clear(); \
        _TOAPPEND; \
        Debug+="\r\n"; \
        fwrite(Debug.c_str(), Debug.size(), 1, F); \
        fclose(F);
#else // MEDIAINFO_DEBUG
    #define MEDIAINFO_DEBUG(_TOAPPEND)
#endif // MEDIAINFO_DEBUG

#ifdef MEDIAINFO_DEBUG
#define EXECUTE_VOID(_METHOD,_DEBUGB) \
        ((MediaInfo_Internal*)Internal)->_METHOD;
#else //MEDIAINFO_DEBUG
#define EXECUTE_VOID(_METHOD,_DEBUGB) \
        ((MediaInfo_Internal*)Internal)->_METHOD; \
        MEDIAINFO_DEBUG(_DEBUGB)
#endif //MEDIAINFO_DEBUG

#ifdef MEDIAINFO_DEBUG
#define EXECUTE_INT(_METHOD,_DEBUGB) \
        return ((MediaInfo_Internal*)Internal)->_METHOD;
#else //MEDIAINFO_DEBUG
#define EXECUTE_INT(_METHOD, _DEBUGB) \
        int64u ToReturn=((MediaInfo_Internal*)Internal)->_METHOD; \
        MEDIAINFO_DEBUG(_DEBUGB) \
        return ToReturn;
#endif //MEDIAINFO_DEBUG

#ifdef MEDIAINFO_DEBUG
#define EXECUTE_STRING(_METHOD,_DEBUGB) \
        return ((MediaInfo_Internal*)Internal)->_METHOD;
#else //MEDIAINFO_DEBUG
#define EXECUTE_STRING(_METHOD,_DEBUGB) \
        Ztring ToReturn=((MediaInfo_Internal*)Internal)->_METHOD; \
        MEDIAINFO_DEBUG(_DEBUGB) \
        return ToReturn;
#endif //MEDIAINFO_DEBUG

inline std::string ToString(int64u Integer)
{
    return Ztring::ToZtring(Integer).To_Local();
}

inline std::string ToString(size_t Integer)
{
    return Ztring::ToZtring(Integer).To_Local();
}

//***************************************************************************
// Constructor/destructor
//***************************************************************************

//---------------------------------------------------------------------------
MediaInfo::MediaInfo()
{
    Internal=new MediaInfo_Internal();
}

//---------------------------------------------------------------------------
MediaInfo::~MediaInfo()
{
    delete (MediaInfo_Internal*)Internal; //Internal=NULL;
}

//***************************************************************************
// Files
//***************************************************************************

//---------------------------------------------------------------------------
size_t MediaInfo::Open(const String &File_Name_)
{
    return ((MediaInfo_Internal*)Internal)->Open(File_Name_);
}

//---------------------------------------------------------------------------
size_t MediaInfo::Open (const int8u* Begin_, size_t Begin_Size_, const int8u*, size_t, int64u FileSize_)
{
    return ((MediaInfo_Internal*)Internal)->Open(Begin_, Begin_Size_);
}

//---------------------------------------------------------------------------
size_t MediaInfo::Open_Buffer_Init (int64u File_Size, int64u File_Offset)
{
    MEDIAINFO_DEBUG(Debug+="Open_Buffer_Init, File_Size=";Debug+=ToString(File_Size);Debug+=", File_Offset=";Debug+=ToString(File_Offset);)
    EXECUTE_INT(Open_Buffer_Init(File_Size, File_Offset), Debug+="Open_Buffer, will return ";Debug+=ToString(ToReturn);)
}

//---------------------------------------------------------------------------
size_t MediaInfo::Open_Buffer_Continue (const int8u* ToAdd, size_t ToAdd_Size)
{
    size_t ToReturn=((MediaInfo_Internal*)Internal)->Open_Buffer_Continue(ToAdd, ToAdd_Size);
    if (ToReturn==0)
    {
        MEDIAINFO_DEBUG(Debug+="Open_Buffer_Continue, will return ";Debug+=ToString(ToReturn);Debug+=", forcing a Get() :";)
        Get(Stream_General, 0, _T("Format"));
    }
    return ToReturn;
}

//---------------------------------------------------------------------------
int64u MediaInfo::Open_Buffer_Continue_GoTo_Get ()
{
    return ((MediaInfo_Internal*)Internal)->Open_Buffer_Continue_GoTo_Get();
}

//---------------------------------------------------------------------------
size_t MediaInfo::Open_Buffer_Finalize ()
{
    MEDIAINFO_DEBUG(Debug+="Open_Buffer_Finalize";)
    EXECUTE_INT(Open_Buffer_Finalize(), Debug+="Open_Buffer_Finalize, will return ";Debug+=ToString(ToReturn);)
}

//---------------------------------------------------------------------------
size_t MediaInfo::Save()
{
    return 0; //Not yet implemented
}

//---------------------------------------------------------------------------
void MediaInfo::Close()
{
    MEDIAINFO_DEBUG(Debug+="Close";)
    return ((MediaInfo_Internal*)Internal)->Close();
}

//***************************************************************************
// Get File info
//***************************************************************************

//---------------------------------------------------------------------------
String MediaInfo::Inform(size_t)
{
    MEDIAINFO_DEBUG(Debug+="Inform";)
    EXECUTE_STRING(Inform(), Debug+="Inform, will return ";Debug+=ToReturn.To_Local();)
}

//---------------------------------------------------------------------------
String MediaInfo::Get(stream_t StreamKind, size_t StreamPos, size_t Parameter, info_t KindOfInfo)
{
    MEDIAINFO_DEBUG(Debug+="Get, StreamKind=";Debug+=ToString((size_t)StreamKind);Debug+=", StreamKind=";Debug+=ToString(StreamPos);Debug+=", Parameter=";Debug+=ToString(Parameter);)
    EXECUTE_STRING(Get(StreamKind, StreamPos, Parameter, KindOfInfo), Debug+="Get, will return ";Debug+=ToReturn.To_Local();)
}

//---------------------------------------------------------------------------
String MediaInfo::Get(stream_t StreamKind, size_t StreamPos, const String &Parameter, info_t KindOfInfo, info_t KindOfSearch)
{
    MEDIAINFO_DEBUG(Debug+="Get, StreamKind=";Debug+=ToString((size_t)StreamKind);Debug+=", StreamKind=";Debug+=ToString(StreamPos);Debug+=", Parameter=";Debug+=Ztring(Parameter).To_Local();)

    EXECUTE_STRING(Get(StreamKind, StreamPos, Parameter, KindOfInfo), Debug+="Get, will return ";Debug+=ToReturn.To_Local();)
}

//***************************************************************************
// Set File info
//***************************************************************************

//---------------------------------------------------------------------------
size_t MediaInfo::Set(const String &ToSet, stream_t StreamKind, size_t StreamNumber, size_t Parameter, const String &OldValue)
{
    return 0; //Not yet implemented
}

//---------------------------------------------------------------------------
size_t MediaInfo::Set(const String &ToSet, stream_t StreamKind, size_t StreamNumber, const String &Parameter, const String &OldValue)
{
    return 0; //Not yet implemented
}

//***************************************************************************
// Output buffer
//***************************************************************************

//---------------------------------------------------------------------------
size_t MediaInfo::Output_Buffer_Get (const String &Value)
{
    return ((MediaInfo_Internal*)Internal)->Output_Buffer_Get(Value);
}

//---------------------------------------------------------------------------
size_t MediaInfo::Output_Buffer_Get (size_t Pos)
{
    return ((MediaInfo_Internal*)Internal)->Output_Buffer_Get(Pos);
}

//***************************************************************************
// Information
//***************************************************************************

//---------------------------------------------------------------------------
String MediaInfo::Option (const String &Option, const String &Value)
{
    MEDIAINFO_DEBUG(Debug+="Option, Option=";Debug+=Ztring(Option).To_Local();Debug+=", Value=";Debug+=Ztring(Value).To_Local();)
    EXECUTE_STRING(Option(Option, Value), Debug+="Option, will return ";Debug+=ToReturn.To_Local();)
}

//---------------------------------------------------------------------------
String MediaInfo::Option_Static (const String &Option, const String &Value)
{
    MEDIAINFO_DEBUG(Debug+="Option_Static, Option=";Debug+=Ztring(Option).To_Local();Debug+=", Value=";Debug+=Ztring(Value).To_Local();)
    MediaInfoLib::Config.Init(); //Initialize Configuration

         if (Option==_T("Info_Capacities"))
    {
        return _T("Option desactivated for this version, will come back soon!");
        MediaInfo_Internal MI;
        return MI.Option(Option);
    }
    else if (Option==_T("Info_Version"))
    {
        Ztring ToReturn=MediaInfoLib::Config.Info_Version_Get();
        #if defined(MediaInfo_Internal_VIDEO_NO) || defined(MediaInfo_Internal_AUDIO_NO) || defined(MediaInfo_Internal_RIFF_NO) || defined(MediaInfo_Internal_OGG_NO) || defined(MediaInfo_Internal_MPEGPS_NO) || defined(MediaInfo_Internal_MPEGA_NO) || defined(MediaInfo_Internal_WM_NO) || defined(MediaInfo_Internal_QT_NO) || defined(MediaInfo_Internal_RM_NO) || defined(MediaInfo_Internal_DVDIF_NO) || defined(MediaInfo_Internal_DVDV_NO) || defined(MediaInfo_Internal_AAC_NO) || defined(MediaInfo_Internal_MK_NO) || defined(MediaInfo_Internal_APE_NO) || defined(MediaInfo_Internal_FLAC_NO) || defined(MediaInfo_Internal_SNDFILE_NO) || defined(MediaInfo_Internal_FLV_NO) || defined(MediaInfo_Internal_SWF_NO)
            ToReturn+=_T(" modified");
        #endif
        return ToReturn;
    }
    else
        return MediaInfoLib::Config.Option(Option, Value);
}

//---------------------------------------------------------------------------
size_t MediaInfo::Count_Get (stream_t StreamKind, size_t StreamPos)
{
    return ((MediaInfo_Internal*)Internal)->Count_Get(StreamKind, StreamPos);

}

//---------------------------------------------------------------------------
size_t MediaInfo::State_Get ()
{
    return 0; //Not yet implemented
}

} //NameSpace

<commit_msg><commit_after>// MediaInfo - All info about media files
// Copyright (C) 2002-2008 Jerome Martinez, Zen@MediaArea.net
//
// This library is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// For user: you can disable or enable it
//#define MEDIAINFO_DEBUG
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Compilation conditions
#include <MediaInfo/Setup.h>
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/MediaInfo.h"
#include "MediaInfo/MediaInfo_Internal.h"
using namespace ZenLib;
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//---------------------------------------------------------------------------
//To clarify the code
#ifdef MEDIAINFO_DEBUG
    #include <stdio.h>
    FILE* F;
    std::string Debug;

    #undef MEDIAINFO_DEBUG
    #define MEDIAINFO_DEBUG(_TOAPPEND) \
        F=fopen("MediaInfo_Debug.txt", "a+t"); \
        Debug.clear(); \
        _TOAPPEND; \
        Debug+="\r\n"; \
        fwrite(Debug.c_str(), Debug.size(), 1, F); \
        fclose(F);
#else // MEDIAINFO_DEBUG
    #define MEDIAINFO_DEBUG(_TOAPPEND)
#endif // MEDIAINFO_DEBUG

#ifdef MEDIAINFO_DEBUG
#define EXECUTE_VOID(_METHOD,_DEBUGB) \
        ((MediaInfo_Internal*)Internal)->_METHOD;
#else //MEDIAINFO_DEBUG
#define EXECUTE_VOID(_METHOD,_DEBUGB) \
        ((MediaInfo_Internal*)Internal)->_METHOD; \
        MEDIAINFO_DEBUG(_DEBUGB)
#endif //MEDIAINFO_DEBUG

#ifdef MEDIAINFO_DEBUG
#define EXECUTE_INT(_METHOD,_DEBUGB) \
        return ((MediaInfo_Internal*)Internal)->_METHOD;
#else //MEDIAINFO_DEBUG
#define EXECUTE_INT(_METHOD, _DEBUGB) \
        int64u ToReturn=((MediaInfo_Internal*)Internal)->_METHOD; \
        MEDIAINFO_DEBUG(_DEBUGB) \
        return ToReturn;
#endif //MEDIAINFO_DEBUG

#ifdef MEDIAINFO_DEBUG
#define EXECUTE_STRING(_METHOD,_DEBUGB) \
        return ((MediaInfo_Internal*)Internal)->_METHOD;
#else //MEDIAINFO_DEBUG
#define EXECUTE_STRING(_METHOD,_DEBUGB) \
        Ztring ToReturn=((MediaInfo_Internal*)Internal)->_METHOD; \
        MEDIAINFO_DEBUG(_DEBUGB) \
        return ToReturn;
#endif //MEDIAINFO_DEBUG

inline std::string ToString(int64u Integer)
{
    return Ztring::ToZtring(Integer).To_Local();
}

//***************************************************************************
// Constructor/destructor
//***************************************************************************

//---------------------------------------------------------------------------
MediaInfo::MediaInfo()
{
    Internal=new MediaInfo_Internal();
}

//---------------------------------------------------------------------------
MediaInfo::~MediaInfo()
{
    delete (MediaInfo_Internal*)Internal; //Internal=NULL;
}

//***************************************************************************
// Files
//***************************************************************************

//---------------------------------------------------------------------------
size_t MediaInfo::Open(const String &File_Name_)
{
    return ((MediaInfo_Internal*)Internal)->Open(File_Name_);
}

//---------------------------------------------------------------------------
size_t MediaInfo::Open (const int8u* Begin_, size_t Begin_Size_, const int8u*, size_t, int64u FileSize_)
{
    return ((MediaInfo_Internal*)Internal)->Open(Begin_, Begin_Size_);
}

//---------------------------------------------------------------------------
size_t MediaInfo::Open_Buffer_Init (int64u File_Size, int64u File_Offset)
{
    MEDIAINFO_DEBUG(Debug+="Open_Buffer_Init, File_Size=";Debug+=ToString(File_Size);Debug+=", File_Offset=";Debug+=ToString(File_Offset);)
    EXECUTE_INT(Open_Buffer_Init(File_Size, File_Offset), Debug+="Open_Buffer, will return ";Debug+=ToString(ToReturn);)
}

//---------------------------------------------------------------------------
size_t MediaInfo::Open_Buffer_Continue (const int8u* ToAdd, size_t ToAdd_Size)
{
    size_t ToReturn=((MediaInfo_Internal*)Internal)->Open_Buffer_Continue(ToAdd, ToAdd_Size);
    if (ToReturn==0)
    {
        MEDIAINFO_DEBUG(Debug+="Open_Buffer_Continue, will return ";Debug+=ToString(ToReturn);Debug+=", forcing a Get() :";)
        Get(Stream_General, 0, _T("Format"));
    }
    return ToReturn;
}

//---------------------------------------------------------------------------
int64u MediaInfo::Open_Buffer_Continue_GoTo_Get ()
{
    return ((MediaInfo_Internal*)Internal)->Open_Buffer_Continue_GoTo_Get();
}

//---------------------------------------------------------------------------
size_t MediaInfo::Open_Buffer_Finalize ()
{
    MEDIAINFO_DEBUG(Debug+="Open_Buffer_Finalize";)
    EXECUTE_INT(Open_Buffer_Finalize(), Debug+="Open_Buffer_Finalize, will return ";Debug+=ToString(ToReturn);)
}

//---------------------------------------------------------------------------
size_t MediaInfo::Save()
{
    return 0; //Not yet implemented
}

//---------------------------------------------------------------------------
void MediaInfo::Close()
{
    MEDIAINFO_DEBUG(Debug+="Close";)
    return ((MediaInfo_Internal*)Internal)->Close();
}

//***************************************************************************
// Get File info
//***************************************************************************

//---------------------------------------------------------------------------
String MediaInfo::Inform(size_t)
{
    MEDIAINFO_DEBUG(Debug+="Inform";)
    EXECUTE_STRING(Inform(), Debug+="Inform, will return ";Debug+=ToReturn.To_Local();)
}

//---------------------------------------------------------------------------
String MediaInfo::Get(stream_t StreamKind, size_t StreamPos, size_t Parameter, info_t KindOfInfo)
{
    MEDIAINFO_DEBUG(Debug+="Get, StreamKind=";Debug+=ToString((size_t)StreamKind);Debug+=", StreamKind=";Debug+=ToString(StreamPos);Debug+=", Parameter=";Debug+=ToString(Parameter);)
    EXECUTE_STRING(Get(StreamKind, StreamPos, Parameter, KindOfInfo), Debug+="Get, will return ";Debug+=ToReturn.To_Local();)
}

//---------------------------------------------------------------------------
String MediaInfo::Get(stream_t StreamKind, size_t StreamPos, const String &Parameter, info_t KindOfInfo, info_t KindOfSearch)
{
    MEDIAINFO_DEBUG(Debug+="Get, StreamKind=";Debug+=ToString((size_t)StreamKind);Debug+=", StreamKind=";Debug+=ToString(StreamPos);Debug+=", Parameter=";Debug+=Ztring(Parameter).To_Local();)

    EXECUTE_STRING(Get(StreamKind, StreamPos, Parameter, KindOfInfo), Debug+="Get, will return ";Debug+=ToReturn.To_Local();)
}

//***************************************************************************
// Set File info
//***************************************************************************

//---------------------------------------------------------------------------
size_t MediaInfo::Set(const String &ToSet, stream_t StreamKind, size_t StreamNumber, size_t Parameter, const String &OldValue)
{
    return 0; //Not yet implemented
}

//---------------------------------------------------------------------------
size_t MediaInfo::Set(const String &ToSet, stream_t StreamKind, size_t StreamNumber, const String &Parameter, const String &OldValue)
{
    return 0; //Not yet implemented
}

//***************************************************************************
// Output buffer
//***************************************************************************

//---------------------------------------------------------------------------
size_t MediaInfo::Output_Buffer_Get (const String &Value)
{
    return ((MediaInfo_Internal*)Internal)->Output_Buffer_Get(Value);
}

//---------------------------------------------------------------------------
size_t MediaInfo::Output_Buffer_Get (size_t Pos)
{
    return ((MediaInfo_Internal*)Internal)->Output_Buffer_Get(Pos);
}

//***************************************************************************
// Information
//***************************************************************************

//---------------------------------------------------------------------------
String MediaInfo::Option (const String &Option, const String &Value)
{
    MEDIAINFO_DEBUG(Debug+="Option, Option=";Debug+=Ztring(Option).To_Local();Debug+=", Value=";Debug+=Ztring(Value).To_Local();)
    EXECUTE_STRING(Option(Option, Value), Debug+="Option, will return ";Debug+=ToReturn.To_Local();)
}

//---------------------------------------------------------------------------
String MediaInfo::Option_Static (const String &Option, const String &Value)
{
    MEDIAINFO_DEBUG(Debug+="Option_Static, Option=";Debug+=Ztring(Option).To_Local();Debug+=", Value=";Debug+=Ztring(Value).To_Local();)
    MediaInfoLib::Config.Init(); //Initialize Configuration

         if (Option==_T("Info_Capacities"))
    {
        return _T("Option desactivated for this version, will come back soon!");
        MediaInfo_Internal MI;
        return MI.Option(Option);
    }
    else if (Option==_T("Info_Version"))
    {
        Ztring ToReturn=MediaInfoLib::Config.Info_Version_Get();
        #if defined(MediaInfo_Internal_VIDEO_NO) || defined(MediaInfo_Internal_AUDIO_NO) || defined(MediaInfo_Internal_RIFF_NO) || defined(MediaInfo_Internal_OGG_NO) || defined(MediaInfo_Internal_MPEGPS_NO) || defined(MediaInfo_Internal_MPEGA_NO) || defined(MediaInfo_Internal_WM_NO) || defined(MediaInfo_Internal_QT_NO) || defined(MediaInfo_Internal_RM_NO) || defined(MediaInfo_Internal_DVDIF_NO) || defined(MediaInfo_Internal_DVDV_NO) || defined(MediaInfo_Internal_AAC_NO) || defined(MediaInfo_Internal_MK_NO) || defined(MediaInfo_Internal_APE_NO) || defined(MediaInfo_Internal_FLAC_NO) || defined(MediaInfo_Internal_SNDFILE_NO) || defined(MediaInfo_Internal_FLV_NO) || defined(MediaInfo_Internal_SWF_NO)
            ToReturn+=_T(" modified");
        #endif
        return ToReturn;
    }
    else
        return MediaInfoLib::Config.Option(Option, Value);
}

//---------------------------------------------------------------------------
size_t MediaInfo::Count_Get (stream_t StreamKind, size_t StreamPos)
{
    return ((MediaInfo_Internal*)Internal)->Count_Get(StreamKind, StreamPos);

}

//---------------------------------------------------------------------------
size_t MediaInfo::State_Get ()
{
    return 0; //Not yet implemented
}

} //NameSpace

<|endoftext|>


<commit_before>#ifndef __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POSITIVE_ORDERED_HPP__
#define __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POSITIVE_ORDERED_HPP__

#include <sstream>
#include <stan/math/matrix/Eigen.hpp>
#include <stan/math/error_handling/default_policy.hpp>
#include <stan/math/error_handling/raise_domain_error.hpp>

namespace stan {
  namespace math {

    /**
     * Return true if the specified vector contains
     * only non-negative values and is sorted into increasing order.
     * There may be duplicate values.  Otherwise, raise a domain
     * error according to the specified policy.
     *
     * @param function
     * @param y Vector to test.
     * @param name
     * @param result
     * @tparam Policy Only the policy's type matters.
     * @return true if the vector has positive, ordered
     * values.
     */
    template <typename T_y, typename T_result, class Policy>
    bool check_positive_ordered(const char* function,
                                const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y,
                                const char* name,
                                T_result* result,
                                const Policy&) {
      using stan::math::policies::raise_domain_error;
      typedef typename Eigen::Matrix<T_y,Eigen::Dynamic,1>::size_type size_t;
      if (y.size() == 0) {
        return true;
      }
      if (y[0] < 0) {
        std::ostringstream stream;
        stream << name << " is not a valid positive_ordered vector."
               << " The element at 0 is %1%, but should be postive.";
        T_result tmp = raise_domain_error<T_result,T_y>(function,
                                                        stream.str().c_str(),
                                                        y[0],
                                                        Policy());
        if (result != 0)
          *result = tmp;
        return false;
      }
      for (size_t n = 1; n < y.size(); n++) {
        if (!(y[n] > y[n-1])) {
          std::ostringstream stream;
          stream << name << " is not a valid ordered vector."
                 << " The element at " << n
                 << " is %1%, but should be greater than the previous element, "
                 << y[n-1];
          T_result tmp = raise_domain_error<T_result,T_y>(function,
                                                          stream.str().c_str(),
                                                          y[n],
                                                          Policy());
          if (result != 0)
            *result = tmp;
          return false;
        }
      }
      return true;
    }
    template <typename T_y, typename T_result>
    bool check_positive_ordered(const char* function,
                                const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y,
                                const char* name,
                                T_result* result) {
      return check_positive_ordered(function,y,name,result,default_policy());
    }
    template <typename T>
    bool check_positive_ordered(const char* function,
                                const Eigen::Matrix<T,Eigen::Dynamic,1>& y,
                                const char* name,
                                T* result = 0) {
      return check_positive_ordered(function,y,name,result,default_policy());
    }

  }
}
#endif
<commit_msg>policies_refactor: updating matrix/check_positive_ordered<commit_after>#ifndef __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POSITIVE_ORDERED_HPP__
#define __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POSITIVE_ORDERED_HPP__

#include <sstream>
#include <stan/math/matrix/Eigen.hpp>
#include <stan/math/error_handling/raise_domain_error.hpp>

namespace stan {
  namespace math {

    /**
     * Return true if the specified vector contains
     * only non-negative values and is sorted into increasing order.
     * There may be duplicate values.  Otherwise, raise a domain
     * error according to the specified policy.
     *
     * @param function
     * @param y Vector to test.
     * @param name
     * @param result
     * @return true if the vector has positive, ordered
     * values.
     */
    template <typename T_y, typename T_result>
    bool check_positive_ordered(const char* function,
                                const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y,
                                const char* name,
                                T_result* result) {
      using stan::math::policies::raise_domain_error;
      typedef typename Eigen::Matrix<T_y,Eigen::Dynamic,1>::size_type size_t;
      if (y.size() == 0) {
        return true;
      }
      if (y[0] < 0) {
        std::ostringstream stream;
        stream << name << " is not a valid positive_ordered vector."
               << " The element at 0 is %1%, but should be postive.";
        T_result tmp = raise_domain_error<T_result,T_y>(function,
                                                        stream.str().c_str(),
                                                        y[0]);
        if (result != 0)
          *result = tmp;
        return false;
      }
      for (size_t n = 1; n < y.size(); n++) {
        if (!(y[n] > y[n-1])) {
          std::ostringstream stream;
          stream << name << " is not a valid ordered vector."
                 << " The element at " << n
                 << " is %1%, but should be greater than the previous element, "
                 << y[n-1];
          T_result tmp = raise_domain_error<T_result,T_y>(function,
                                                          stream.str().c_str(),
                                                          y[n]);
          if (result != 0)
            *result = tmp;
          return false;
        }
      }
      return true;
    }
    template <typename T>
    bool check_positive_ordered(const char* function,
                                const Eigen::Matrix<T,Eigen::Dynamic,1>& y,
                                const char* name,
                                T* result = 0) {
      return check_positive_ordered<T,T>(function,y,name,result);
    }

  }
}
#endif
<|endoftext|>


<commit_before>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

#include "ProxyFactory.h"

#include <map>
#include <stdio.h>
#include <v8.h>

#include "AndroidUtil.h"
#include "JavaObject.h"
#include "JNIUtil.h"
#include "KrollBindings.h"
#include "Proxy.h"
#include "TypeConverter.h"
#include "V8Runtime.h"
#include "V8Util.h"

#define TAG "ProxyFactory"

using namespace v8;

namespace titanium {

typedef struct {
	FunctionTemplate* v8ProxyTemplate;
	jmethodID javaProxyCreator;
} ProxyInfo;

typedef std::map<jclass, ProxyInfo> ProxyFactoryMap;
static ProxyFactoryMap factories;

#define GET_PROXY_INFO(jclass, info) \
	ProxyFactoryMap::iterator i = factories.find(jclass); \
	info = i != factories.end() ? &i->second : NULL

#define LOG_JNIENV_ERROR(msgMore) \
	LOGE(TAG, "Unable to find class %s", msgMore)

Handle<Object> ProxyFactory::createV8Proxy(jclass javaClass, jobject javaProxy)
{
	LOGV(TAG, "create v8 proxy");
	JNIEnv* env = JNIScope::getEnv();
	if (!env) {
		LOG_JNIENV_ERROR("while creating Java proxy.");
		return Handle<Object>();
	}

	ENTER_V8(V8Runtime::globalContext);
	Local<Function> creator;

	LOGV(TAG, "get proxy info");

	ProxyInfo* info;
	GET_PROXY_INFO(javaClass, info);
	if (!info) {
		// No info has been registered for this class yet, fall back
		// to the binding lookup table
		jstring javaClassName = JNIUtil::getClassName(javaClass);
		Handle<Value> className = TypeConverter::javaStringToJsString(javaClassName);
		env->DeleteLocalRef(javaClassName);

		Handle<Object> exports = KrollBindings::getBinding(className->ToString());

		if (exports.IsEmpty()) {
			String::Utf8Value classStr(className);
			LOGE(TAG, "Failed to find class for %s", *classStr);
			LOG_JNIENV_ERROR("while creating V8 Proxy.");
			return Handle<Object>();
		}

		// TODO: The first value in exports should be the type that's exported
		// But there's probably a better way to do this
		Handle<Array> names = exports->GetPropertyNames();
		if (names->Length() >= 1) {
			creator = Local<Function>::Cast(exports->Get(names->Get(0)));
		}
	} else {
		creator = info->v8ProxyTemplate->GetFunction();
	}

	Local<Value> external = External::New(javaProxy);
	Local<Object> v8Proxy = creator->NewInstance(1, &external);

	// set the pointer back on the java proxy
	jlong ptr = (jlong) *Persistent<Object>::New(v8Proxy);

	jobject javaV8Object = env->NewObject(JNIUtil::v8ObjectClass,
		JNIUtil::v8ObjectInitMethod, ptr);

	env->SetObjectField(javaProxy,
		JNIUtil::krollProxyKrollObjectField, javaV8Object);
	env->DeleteLocalRef(javaV8Object);

	return scope.Close(v8Proxy);
}

jobject ProxyFactory::createJavaProxy(jclass javaClass, Local<Object> v8Proxy, const Arguments& args)
{
	ProxyInfo* info;
	GET_PROXY_INFO(javaClass, info);

	if (!info) {
		JNIUtil::logClassName("ProxyFactory: failed to find class for %s", javaClass, true);
		LOGE(TAG, "No proxy info found for class.");
		return NULL;
	}

	JNIEnv* env = JNIScope::getEnv();
	if (!env) {
		LOG_JNIENV_ERROR("while creating Java proxy.");
		return NULL;
	}

	// Create a persistent handle to the V8 proxy
	// and cast it to a pointer. The Java proxy needs
	// a reference to the V8 proxy for later use.
	jlong pv8Proxy = (jlong) *Persistent<Object>::New(v8Proxy);

	// We also pass the creation URL of the proxy so we can track relative URLs
	Handle<Value> sourceUrl = args.Callee()->GetScriptOrigin().ResourceName();
	String::Utf8Value sourceUrlValue(sourceUrl);

	const char *url = "app://app.js";
	jstring javaSourceUrl = NULL;
	if (sourceUrlValue.length() > 0) {
		url = *sourceUrlValue;
		javaSourceUrl = env->NewStringUTF(url);
	}

	// Determine if this constructor call was made within
	// the createXYZ() wrapper function. This can be tested by checking
	// if an Arguments object was passed as the sole argument.
	bool calledFromCreate = false;
	if (args.Length() == 1 && args[0]->IsObject()) {
		Local<String> constructorName = args[0]->ToObject()->GetConstructorName();
		if (strcmp(*String::Utf8Value(constructorName), "Arguments") == 0) {
			calledFromCreate = true;
		}
	}

	// Convert the V8 arguments into Java types so they can be
	// passed to the Java creator method. Which converter we use
	// depends how this constructor was called.
	jobjectArray javaArgs;
	if (calledFromCreate) {
		Local<Object> arguments = args[0]->ToObject();
		int length = arguments->Get(Proxy::lengthSymbol)->Int32Value();
		Handle<Object> scopeVars = arguments->Get(0)->ToObject();
		Handle<Value> sourceUrl = scopeVars->Get(Proxy::sourceUrlSymbol);

		javaSourceUrl = TypeConverter::jsValueToJavaString(sourceUrl);
		javaArgs = TypeConverter::jsObjectIndexPropsToJavaArray(arguments, 1, length);
	} else {
		javaArgs = TypeConverter::jsArgumentsToJavaArray(args);
	}

	jobject javaV8Object = env->NewObject(JNIUtil::v8ObjectClass,
		JNIUtil::v8ObjectInitMethod, pv8Proxy);

	// Create the java proxy using the creator static method provided.
	// Send along a pointer to the v8 proxy so the two are linked.
	jobject javaProxy = env->CallStaticObjectMethod(JNIUtil::krollProxyClass,
		info->javaProxyCreator, javaClass, javaV8Object, javaArgs, javaSourceUrl);

	if (javaSourceUrl) {
		LOGV(TAG, "delete source url!");
		env->DeleteLocalRef(javaSourceUrl);
	}

	env->DeleteLocalRef(javaV8Object);
	env->DeleteLocalRef(javaArgs);

	return javaProxy;
}

jobject ProxyFactory::unwrapJavaProxy(const Arguments& args)
{
	if (args.Length() != 1)
		return NULL;
	Local<Value> firstArgument = args[0];
	return firstArgument->IsExternal() ? (jobject)External::Unwrap(firstArgument) : NULL;
}

void ProxyFactory::registerProxyPair(jclass javaProxyClass, FunctionTemplate* v8ProxyTemplate)
{
	JNIEnv* env = JNIScope::getEnv();
	if (!env) {
		LOG_JNIENV_ERROR("while registering proxy pair.");
		return;
	}

	ProxyInfo info;
	info.v8ProxyTemplate = v8ProxyTemplate;
	info.javaProxyCreator = JNIUtil::krollProxyCreateProxyMethod;

	factories[javaProxyClass] = info;
}

}

<commit_msg>Better handle cases where we don't passs ScopeVars to create methods.<commit_after>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

#include "ProxyFactory.h"

#include <map>
#include <stdio.h>
#include <v8.h>

#include "AndroidUtil.h"
#include "JavaObject.h"
#include "JNIUtil.h"
#include "KrollBindings.h"
#include "Proxy.h"
#include "TypeConverter.h"
#include "V8Runtime.h"
#include "V8Util.h"

#define TAG "ProxyFactory"

using namespace v8;

namespace titanium {

typedef struct {
	FunctionTemplate* v8ProxyTemplate;
	jmethodID javaProxyCreator;
} ProxyInfo;

typedef std::map<jclass, ProxyInfo> ProxyFactoryMap;
static ProxyFactoryMap factories;

#define GET_PROXY_INFO(jclass, info) \
	ProxyFactoryMap::iterator i = factories.find(jclass); \
	info = i != factories.end() ? &i->second : NULL

#define LOG_JNIENV_ERROR(msgMore) \
	LOGE(TAG, "Unable to find class %s", msgMore)

Handle<Object> ProxyFactory::createV8Proxy(jclass javaClass, jobject javaProxy)
{
	LOGV(TAG, "create v8 proxy");
	JNIEnv* env = JNIScope::getEnv();
	if (!env) {
		LOG_JNIENV_ERROR("while creating Java proxy.");
		return Handle<Object>();
	}

	ENTER_V8(V8Runtime::globalContext);
	Local<Function> creator;

	LOGV(TAG, "get proxy info");

	ProxyInfo* info;
	GET_PROXY_INFO(javaClass, info);
	if (!info) {
		// No info has been registered for this class yet, fall back
		// to the binding lookup table
		jstring javaClassName = JNIUtil::getClassName(javaClass);
		Handle<Value> className = TypeConverter::javaStringToJsString(javaClassName);
		env->DeleteLocalRef(javaClassName);

		Handle<Object> exports = KrollBindings::getBinding(className->ToString());

		if (exports.IsEmpty()) {
			String::Utf8Value classStr(className);
			LOGE(TAG, "Failed to find class for %s", *classStr);
			LOG_JNIENV_ERROR("while creating V8 Proxy.");
			return Handle<Object>();
		}

		// TODO: The first value in exports should be the type that's exported
		// But there's probably a better way to do this
		Handle<Array> names = exports->GetPropertyNames();
		if (names->Length() >= 1) {
			creator = Local<Function>::Cast(exports->Get(names->Get(0)));
		}
	} else {
		creator = info->v8ProxyTemplate->GetFunction();
	}

	Local<Value> external = External::New(javaProxy);
	Local<Object> v8Proxy = creator->NewInstance(1, &external);

	// set the pointer back on the java proxy
	jlong ptr = (jlong) *Persistent<Object>::New(v8Proxy);

	jobject javaV8Object = env->NewObject(JNIUtil::v8ObjectClass,
		JNIUtil::v8ObjectInitMethod, ptr);

	env->SetObjectField(javaProxy,
		JNIUtil::krollProxyKrollObjectField, javaV8Object);
	env->DeleteLocalRef(javaV8Object);

	return scope.Close(v8Proxy);
}

jobject ProxyFactory::createJavaProxy(jclass javaClass, Local<Object> v8Proxy, const Arguments& args)
{
	ProxyInfo* info;
	GET_PROXY_INFO(javaClass, info);

	if (!info) {
		JNIUtil::logClassName("ProxyFactory: failed to find class for %s", javaClass, true);
		LOGE(TAG, "No proxy info found for class.");
		return NULL;
	}

	JNIEnv* env = JNIScope::getEnv();
	if (!env) {
		LOG_JNIENV_ERROR("while creating Java proxy.");
		return NULL;
	}

	// Create a persistent handle to the V8 proxy
	// and cast it to a pointer. The Java proxy needs
	// a reference to the V8 proxy for later use.
	jlong pv8Proxy = (jlong) *Persistent<Object>::New(v8Proxy);

	// We also pass the creation URL of the proxy so we can track relative URLs
	Handle<Value> sourceUrl = args.Callee()->GetScriptOrigin().ResourceName();
	String::Utf8Value sourceUrlValue(sourceUrl);

	const char *url = "app://app.js";
	jstring javaSourceUrl = NULL;
	if (sourceUrlValue.length() > 0) {
		url = *sourceUrlValue;
		javaSourceUrl = env->NewStringUTF(url);
	}

	// Determine if this constructor call was made within
	// the createXYZ() wrapper function. This can be tested by checking
	// if an Arguments object was passed as the sole argument.
	bool calledFromCreate = false;
	if (args.Length() == 1 && args[0]->IsObject()) {
		if (V8Util::constructorNameMatches(args[0]->ToObject(), "Arguments")) {
			calledFromCreate = true;
		}
	}

	// Convert the V8 arguments into Java types so they can be
	// passed to the Java creator method. Which converter we use
	// depends how this constructor was called.
	jobjectArray javaArgs;
	if (calledFromCreate) {
		Local<Object> arguments = args[0]->ToObject();
		int length = arguments->Get(Proxy::lengthSymbol)->Int32Value();
		int start = 0;

		// Get the scope variables if provided and extract the source URL.
		// We need to send that to the Java side when creating the proxy.
		if (length > 0) {
			Local<Object> scopeVars = arguments->Get(0)->ToObject();
			if (V8Util::constructorNameMatches(scopeVars, "ScopeVars")) {
				Local<Value> sourceUrl = scopeVars->Get(Proxy::sourceUrlSymbol);
				javaSourceUrl = TypeConverter::jsValueToJavaString(sourceUrl);
			}
		}

		javaArgs = TypeConverter::jsObjectIndexPropsToJavaArray(arguments, start, length);
	} else {
		javaArgs = TypeConverter::jsArgumentsToJavaArray(args);
	}

	jobject javaV8Object = env->NewObject(JNIUtil::v8ObjectClass,
		JNIUtil::v8ObjectInitMethod, pv8Proxy);

	// Create the java proxy using the creator static method provided.
	// Send along a pointer to the v8 proxy so the two are linked.
	jobject javaProxy = env->CallStaticObjectMethod(JNIUtil::krollProxyClass,
		info->javaProxyCreator, javaClass, javaV8Object, javaArgs, javaSourceUrl);

	if (javaSourceUrl) {
		LOGV(TAG, "delete source url!");
		env->DeleteLocalRef(javaSourceUrl);
	}

	env->DeleteLocalRef(javaV8Object);
	env->DeleteLocalRef(javaArgs);

	return javaProxy;
}

jobject ProxyFactory::unwrapJavaProxy(const Arguments& args)
{
	if (args.Length() != 1)
		return NULL;
	Local<Value> firstArgument = args[0];
	return firstArgument->IsExternal() ? (jobject)External::Unwrap(firstArgument) : NULL;
}

void ProxyFactory::registerProxyPair(jclass javaProxyClass, FunctionTemplate* v8ProxyTemplate)
{
	JNIEnv* env = JNIScope::getEnv();
	if (!env) {
		LOG_JNIENV_ERROR("while registering proxy pair.");
		return;
	}

	ProxyInfo info;
	info.v8ProxyTemplate = v8ProxyTemplate;
	info.javaProxyCreator = JNIUtil::krollProxyCreateProxyMethod;

	factories[javaProxyClass] = info;
}

}

<|endoftext|>


<commit_before>
#include "ksp_plugin/orbit_analyser.hpp"

#include <string>
#include <vector>

#include "astronomy/standard_product_3.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "ksp_plugin/integrators.hpp"
#include "physics/solar_system.hpp"
#include "testing_utilities/approximate_quantity.hpp"
#include "testing_utilities/is_near.hpp"

namespace principia {
namespace ksp_plugin {

using astronomy::ITRS;
using astronomy::OrbitRecurrence;
using astronomy::StandardProduct3;
using base::not_null;
using geometry::Position;
using integrators::SymmetricLinearMultistepIntegrator;
using integrators::methods::QuinlanTremaine1990Order12;
using physics::BodySurfaceDynamicFrame;
using physics::Ephemeris;
using physics::RotatingBody;
using physics::SolarSystem;
using quantities::astronomy::JulianYear;
using quantities::astronomy::TerrestrialEquatorialRadius;
using quantities::si::Hour;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Milli;
using quantities::si::Radian;
using testing_utilities::IsNear;
using testing_utilities::operator""_⑴;
using ::testing::AllOf;
using ::testing::Eq;
using ::testing::IsNull;
using ::testing::Optional;
using ::testing::Property;

class OrbitAnalyserTest : public testing::Test {
 protected:
  OrbitAnalyserTest()
      : earth_1957_(RemoveAllButEarth(SolarSystem<Barycentric>(
            SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
            SOLUTION_DIR / "astronomy" /
                "sol_initial_state_jd_2436116_311504629.proto.txt",
            /*ignore_frame=*/true))),
        // As there is only one body left in this ephemeris, integration is
        // exact up to roundoff error regardless of the step size.  Use a long
        // step so that we do not waste time computing the ephemeris.
        ephemeris_(earth_1957_.MakeEphemeris(
            /*accuracy_parameters=*/{/*fitting_tolerance=*/1 * Milli(Metre),
                                     /*geopotential_tolerance=*/0x1p-24},
            Ephemeris<Barycentric>::FixedStepParameters(
                SymmetricLinearMultistepIntegrator<QuinlanTremaine1990Order12,
                                                   Position<Barycentric>>(),
                /*step=*/1 * JulianYear))),
        earth_(*earth_1957_.rotating_body(*ephemeris_, "Earth")),
        itrs_(ephemeris_.get(), &earth_),
        topex_poséidon_(SOLUTION_DIR / "astronomy" / "standard_product_3" /
                            "grgtop03.b97344.e97348.D_S.sp3",
                        StandardProduct3::Dialect::GRGS) {}

  SolarSystem<Barycentric> earth_1957_;
  not_null<std::unique_ptr<Ephemeris<Barycentric>>> ephemeris_;
  RotatingBody<Barycentric> const& earth_;
  BodySurfaceDynamicFrame<Barycentric, ITRS> itrs_;
  StandardProduct3 topex_poséidon_;

 private:
  SolarSystem<Barycentric> RemoveAllButEarth(
      SolarSystem<Barycentric> solar_system) {
    std::vector<std::string> const names = solar_system.names();
    for (auto const& name : names) {
      if (name != "Earth") {
        solar_system.RemoveMassiveBody(name);
      }
    }
    return solar_system;
  }
};

TEST_F(OrbitAnalyserTest, TOPEXPoséidon) {
  OrbitAnalyser analyser(ephemeris_.get(), DefaultHistoryParameters());
  EXPECT_THAT(analyser.analysis(), IsNull());
  EXPECT_THAT(analyser.progress_of_next_analysis(), Eq(0));
  auto const& arc =
      *topex_poséidon_.orbit(
          {StandardProduct3::SatelliteGroup::General, 1}).front();
  ephemeris_->Prolong(arc.begin()->time);
  analyser.RequestAnalysis(arc.begin()->time,
                           itrs_.FromThisFrameAtTime(arc.begin()->time)(
                               arc.begin()->degrees_of_freedom),
                           3 * Hour,
                           &earth_);
  while (analyser.progress_of_next_analysis() != 1) {
    absl::SleepFor(absl::Milliseconds(10));
  }
  // Since |progress_of_next_analysis| only tracks the integration, not the
  // analysis, we have no guarantee that an analysis is available immediately.
  do {
    absl::SleepFor(absl::Milliseconds(10));
    analyser.RefreshAnalysis();
  } while (analyser.analysis() == nullptr);
  EXPECT_THAT(analyser.analysis()
                  ->elements()
                  ->mean_semimajor_axis_interval()
                  .midpoint(),
              IsNear(7714_⑴ * Kilo(Metre)));
  EXPECT_THAT(analyser.analysis()->recurrence(),
              Optional(AllOf(Property(&OrbitRecurrence::νₒ, 13),
                             Property(&OrbitRecurrence::Dᴛₒ, -3),
                             Property(&OrbitRecurrence::Cᴛₒ, 10))));
  EXPECT_THAT(analyser.analysis()
                      ->equatorial_crossings()
                      ->longitudes_reduced_to_pass(1)
                      .measure() *
                  TerrestrialEquatorialRadius / Radian,
              IsNear(93_⑴ * Metre));
  // [13; -1; 3] is the subcycle of [13; -3; 10].
  analyser.analysis()->SetRecurrence({13, -1, 3});
  EXPECT_THAT(analyser.analysis()
                      ->equatorial_crossings()
                      ->longitudes_reduced_to_pass(1)
                      .measure() *
                  TerrestrialEquatorialRadius / Radian,
              IsNear(8211_⑴ * Metre));
  // Back to the auto-detected recurrence.
  analyser.analysis()->ResetRecurrence();
  EXPECT_THAT(analyser.analysis()->recurrence(),
              Optional(AllOf(Property(&OrbitRecurrence::νₒ, 13),
                             Property(&OrbitRecurrence::Dᴛₒ, -3),
                             Property(&OrbitRecurrence::Cᴛₒ, 10))));
}

}  // namespace ksp_plugin
}  // namespace principia
<commit_msg>fix the test<commit_after>
#include "ksp_plugin/orbit_analyser.hpp"

#include <string>
#include <vector>

#include "astronomy/standard_product_3.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "ksp_plugin/integrators.hpp"
#include "physics/solar_system.hpp"
#include "testing_utilities/approximate_quantity.hpp"
#include "testing_utilities/is_near.hpp"

namespace principia {
namespace ksp_plugin {

using astronomy::ITRS;
using astronomy::OrbitRecurrence;
using astronomy::StandardProduct3;
using base::not_null;
using geometry::Position;
using integrators::SymmetricLinearMultistepIntegrator;
using integrators::methods::QuinlanTremaine1990Order12;
using physics::BodySurfaceDynamicFrame;
using physics::Ephemeris;
using physics::RotatingBody;
using physics::SolarSystem;
using quantities::astronomy::JulianYear;
using quantities::astronomy::TerrestrialEquatorialRadius;
using quantities::si::Hour;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Milli;
using quantities::si::Radian;
using testing_utilities::IsNear;
using testing_utilities::operator""_⑴;
using ::testing::AllOf;
using ::testing::Eq;
using ::testing::IsNull;
using ::testing::Optional;
using ::testing::Property;

class OrbitAnalyserTest : public testing::Test {
 protected:
  OrbitAnalyserTest()
      : earth_1957_(RemoveAllButEarth(SolarSystem<Barycentric>(
            SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
            SOLUTION_DIR / "astronomy" /
                "sol_initial_state_jd_2436116_311504629.proto.txt",
            /*ignore_frame=*/true))),
        // As there is only one body left in this ephemeris, integration is
        // exact up to roundoff error regardless of the step size.  Use a long
        // step so that we do not waste time computing the ephemeris.
        ephemeris_(earth_1957_.MakeEphemeris(
            /*accuracy_parameters=*/{/*fitting_tolerance=*/1 * Milli(Metre),
                                     /*geopotential_tolerance=*/0x1p-24},
            Ephemeris<Barycentric>::FixedStepParameters(
                SymmetricLinearMultistepIntegrator<QuinlanTremaine1990Order12,
                                                   Position<Barycentric>>(),
                /*step=*/1 * JulianYear))),
        earth_(*earth_1957_.rotating_body(*ephemeris_, "Earth")),
        itrs_(ephemeris_.get(), &earth_),
        topex_poséidon_(SOLUTION_DIR / "astronomy" / "standard_product_3" /
                            "grgtop03.b97344.e97348.D_S.sp3",
                        StandardProduct3::Dialect::GRGS) {}

  SolarSystem<Barycentric> earth_1957_;
  not_null<std::unique_ptr<Ephemeris<Barycentric>>> ephemeris_;
  RotatingBody<Barycentric> const& earth_;
  BodySurfaceDynamicFrame<Barycentric, ITRS> itrs_;
  StandardProduct3 topex_poséidon_;

 private:
  SolarSystem<Barycentric> RemoveAllButEarth(
      SolarSystem<Barycentric> solar_system) {
    std::vector<std::string> const names = solar_system.names();
    for (auto const& name : names) {
      if (name != "Earth") {
        solar_system.RemoveMassiveBody(name);
      }
    }
    return solar_system;
  }
};

TEST_F(OrbitAnalyserTest, TOPEXPoséidon) {
  OrbitAnalyser analyser(ephemeris_.get(), DefaultHistoryParameters());
  EXPECT_THAT(analyser.analysis(), IsNull());
  EXPECT_THAT(analyser.progress_of_next_analysis(), Eq(0));
  auto const& arc =
      *topex_poséidon_.orbit(
          {StandardProduct3::SatelliteGroup::General, 1}).front();
  ephemeris_->Prolong(arc.begin()->time);
  analyser.RequestAnalysis(arc.begin()->time,
                           itrs_.FromThisFrameAtTime(arc.begin()->time)(
                               arc.begin()->degrees_of_freedom),
                           3 * Hour);
  while (analyser.progress_of_next_analysis() != 1) {
    absl::SleepFor(absl::Milliseconds(10));
  }
  // Since |progress_of_next_analysis| only tracks the integration, not the
  // analysis, we have no guarantee that an analysis is available immediately.
  do {
    absl::SleepFor(absl::Milliseconds(10));
    analyser.RefreshAnalysis();
  } while (analyser.analysis() == nullptr);
  EXPECT_THAT(analyser.analysis()
                  ->elements()
                  ->mean_semimajor_axis_interval()
                  .midpoint(),
              IsNear(7714_⑴ * Kilo(Metre)));
  EXPECT_THAT(analyser.analysis()->recurrence(),
              Optional(AllOf(Property(&OrbitRecurrence::νₒ, 13),
                             Property(&OrbitRecurrence::Dᴛₒ, -3),
                             Property(&OrbitRecurrence::Cᴛₒ, 10))));
  EXPECT_THAT(analyser.analysis()
                      ->equatorial_crossings()
                      ->longitudes_reduced_to_pass(1)
                      .measure() *
                  TerrestrialEquatorialRadius / Radian,
              IsNear(93_⑴ * Metre));
  // [13; -1; 3] is the subcycle of [13; -3; 10].
  analyser.analysis()->SetRecurrence({13, -1, 3});
  EXPECT_THAT(analyser.analysis()
                      ->equatorial_crossings()
                      ->longitudes_reduced_to_pass(1)
                      .measure() *
                  TerrestrialEquatorialRadius / Radian,
              IsNear(8211_⑴ * Metre));
  // Back to the auto-detected recurrence.
  analyser.analysis()->ResetRecurrence();
  EXPECT_THAT(analyser.analysis()->recurrence(),
              Optional(AllOf(Property(&OrbitRecurrence::νₒ, 13),
                             Property(&OrbitRecurrence::Dᴛₒ, -3),
                             Property(&OrbitRecurrence::Cᴛₒ, 10))));
}

}  // namespace ksp_plugin
}  // namespace principia
<|endoftext|>