<commit_before>/*
 * File description: axon_client.cpp
 * Author information: Mike Raninger mikeranzinger@gmail.com
 * Copyright information: Copyright Mike Ranzinger
 */

#include "communication/messaging/axon_client.h"
#include "communication/timeout_exception.h"

#include <functional>

using namespace std;

namespace axon { namespace communication {

struct CMessageSocket
{
	CMessageSocket(CMessage::Ptr a_outboundMessage)
		: OutboundMessage(move(a_outboundMessage))
	{
	}

	CMessage::Ptr OutboundMessage;
	CMessage::Ptr IncomingMessage;
};

class CAxonClient::WaitHandle
    : public IMessageWaitHandle
{
public:
    typedef unique_ptr<WaitHandle> Ptr;

    WaitHandle(CAxonClient &a_client, CMessage::Ptr a_message, uint32_t a_timeout)
        : m_client(a_client), m_socket(move(a_message)), m_waited(false), m_timeout(a_timeout)
    {
        m_start = chrono::steady_clock::now();
    }
    ~WaitHandle()
    {
        p_RemoveFromSocketList(true);
    }

    virtual void Wait() override;
    virtual CMessage::Ptr GetMessage() override;

    CAxonClient &m_client;
    CMessageSocket m_socket;
    bool m_waited;
    CMessage::Ptr m_message;
    chrono::steady_clock::time_point m_start;
    uint32_t m_timeout;

private:
    void p_RemoveFromSocketList(bool a_getLock);
};

CAxonClient::CAxonClient()
{
	SetDefaultProtocol();
}

CAxonClient::CAxonClient(const std::string& a_connectionString)
{
	SetDefaultProtocol();

	Connect(a_connectionString);
}

CAxonClient::CAxonClient(IDataConnection::Ptr a_connection)
{
	SetDefaultProtocol();

	Connect(move(a_connection));
}

CAxonClient::CAxonClient(const std::string& a_connectionString, IProtocol::Ptr a_protocol)
{
	SetProtocol(move(a_protocol));

	Connect(a_connectionString);
}

CAxonClient::CAxonClient(IDataConnection::Ptr a_connection, IProtocol::Ptr a_protocol)
{
	SetProtocol(move(a_protocol));

	Connect(move(a_connection));
}

CAxonClient::Ptr CAxonClient::Create()
{
	return make_shared<CAxonClient>();
}

CAxonClient::Ptr CAxonClient::Create(const std::string& a_connectionString)
{
	return make_shared<CAxonClient>(a_connectionString);
}

CAxonClient::Ptr CAxonClient::Create(IDataConnection::Ptr a_connection)
{
	return make_shared<CAxonClient>(move(a_connection));
}

CAxonClient::Ptr CAxonClient::Create(const std::string& a_connectionString,
		IProtocol::Ptr a_protocol)
{
	return make_shared<CAxonClient>(a_connectionString, move(a_protocol));
}

CAxonClient::Ptr CAxonClient::Create(IDataConnection::Ptr a_connection,
		IProtocol::Ptr a_protocol)
{
	return make_shared<CAxonClient>(move(a_connection), move(a_protocol));
}

void CAxonClient::Connect(const std::string& a_connectionString)
{
	Connect(IDataConnection::Create(a_connectionString));
}

void CAxonClient::Connect(IDataConnection::Ptr a_connection)
{
	m_connection = move(a_connection);

	if (m_connection)
	{
#ifdef IS_WINDOWS
		int l_hack;
		m_connection->SetReceiveHandler(
			[this, l_hack](CDataBuffer a_buf)
			{
				p_OnDataReceived(move(a_buf));
			});
#else
		m_connection->SetReceiveHandler(bind(&CAxonClient::p_OnDataReceived, this, placeholders::_1));
#endif
	}
}

void CAxonClient::SetDefaultProtocol()
{
	SetProtocol(GetDefaultProtocol());
}

void CAxonClient::SetProtocol(IProtocol::Ptr a_protocol)
{
	if (!a_protocol)
		throw runtime_error("Invalid protocol. Cannot be null.");

	m_protocol = move(a_protocol);

	m_protocol->SetHandler(bind(&CAxonClient::p_OnMessageReceived, this, placeholders::_1));
}

string CAxonClient::ConnectionString() const
{
    if (!m_connection)
        return "";
    return m_connection->ConnectionString();
}

CMessage::Ptr CAxonClient::Send(const CMessage::Ptr &a_message)
{

	return Send(a_message, 0);
}

CMessage::Ptr CAxonClient::Send(const CMessage::Ptr &a_message, uint32_t a_timeout)
{
	IMessageWaitHandle::Ptr l_waitHandle = SendAsync(a_message, a_timeout);

	return l_waitHandle->GetMessage();
}

IMessageWaitHandle::Ptr CAxonClient::SendAsync(const CMessage::Ptr& a_message)
{
    return SendAsync(a_message, 0);
}

IMessageWaitHandle::Ptr CAxonClient::SendAsync(const CMessage::Ptr& a_message, uint32_t a_timeout)
{
    if (!m_connection || !m_connection->IsOpen())
        throw runtime_error("Cannot send data over a dead connection.");
    // Default timeout is 1 minute
    if (a_timeout == 0)
        a_timeout = 60000;

    WaitHandle::Ptr l_waitHandle(new WaitHandle(*this, a_message, a_timeout));

    // Add the socket to the map of messages waiting to be handled
    {
        lock_guard<mutex> l_lock(m_pendingLock);

        m_pendingList.push_back(&l_waitHandle->m_socket);
    }

    p_Send(*a_message);

    return move(l_waitHandle);
}

//--------------------------------------------------------------
// Wait Handle Implementation
//--------------------------------------------------------------
void CAxonClient::WaitHandle::Wait()
{
    if (m_waited)
        return;

    auto l_durLeft = chrono::milliseconds(m_timeout) -
            chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - m_start);

    unique_lock<mutex> l_waitLock(m_client.m_pendingLock);

    if (m_socket.IncomingMessage)
    {
        p_RemoveFromSocketList(false);
        m_waited = true;
        return;
    }

    if (l_durLeft < chrono::milliseconds(0))
        throw CTimeoutException(m_timeout);

    while (!m_socket.IncomingMessage)
    {
        cv_status l_status = m_client.m_newMessageEvent.wait_for(l_waitLock, l_durLeft);

        l_durLeft = chrono::milliseconds(m_timeout) -
            chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - m_start);

        if (m_socket.IncomingMessage
                || l_status == cv_status::timeout
                || l_durLeft < chrono::milliseconds(0))
        {
            // Don't need to acquire the lock because we already have it
            p_RemoveFromSocketList(false);

            if (!m_socket.IncomingMessage)
            {
                throw CTimeoutException(m_timeout);
            }
        }
    }

    m_waited = true;
}

CMessage::Ptr CAxonClient::WaitHandle::GetMessage()
{
    Wait();

    return m_message;
}

void CAxonClient::WaitHandle::p_RemoveFromSocketList(bool a_getLock)
{
    try
    {
        if (a_getLock)
            m_client.m_pendingLock.lock();

        auto iter = find(m_client.m_pendingList.begin(), m_client.m_pendingList.end(), &m_socket);

        if (iter != m_client.m_pendingList.end())
            m_client.m_pendingList.erase(iter);

        if (a_getLock)
            m_client.m_pendingLock.unlock();
    }
    catch (...)
    {
        if (a_getLock)
            m_client.m_pendingLock.unlock();
        throw;
    }
}
//--------------------------------------------------------------

void CAxonClient::SendNonBlocking(const CMessage::Ptr &a_message)
{
	a_message->SetOneWay(true);

	p_Send(*a_message);
}

void CAxonClient::p_Send(const CMessage& a_message)
{
	CDataBuffer l_buffer = m_protocol->SerializeMessage(a_message);

	m_connection->Send(l_buffer.ToShared());
}

void CAxonClient::p_OnMessageReceived(const CMessage::Ptr& a_message)
{
	// This function is invoked whenever the protocol has reconstructed
	// a message. There are 3 things that this object needs to try before
	// erroring out:
	// 1) Check to see if this message is a response from an outbound call
	//    Resolution: Add the message to the new messages map and signal
	//                that there is a new message
	// 2) Check to see if this instance has a handler for this message
	//    Resolution: Handle the message and send the return value back out
	// 3) If this client is a child of a server, then see if the server
	//      can handle the message.
	//
	// If none of the steps succeed, then throw a fault

    SetExecutingInstance(this);

	bool l_handled = false;

	{
		lock_guard<mutex> l_lock(m_pendingLock);

		const std::string &l_reqId = a_message->RequestId();

		// See if the RequestId of this message is the Id of a message
		// in the outbound list
		auto iter = find_if(m_pendingList.begin(), m_pendingList.end(),
				[&l_reqId] (CMessageSocket *l_sock)
				{
					return l_reqId == l_sock->OutboundMessage->Id();
				});

		// This message is a result of an outbound request, so let
		// the blocking outbound requests know
		if (iter != m_pendingList.end())
		{
			(*iter)->IncomingMessage = a_message;
			l_handled = true;
		}
	}

	if (l_handled)
	{
		// Wake up everyone that is currently waiting
		m_newMessageEvent.notify_all();
		return;
	}

	// Ok, so this message isn't a result of an outbound call, so see if this
	// client has a handler for it
	CMessage::Ptr l_response;
	if (TryHandle(*a_message, l_response))
	{
		// There was a handler for this message, so now
		// send it back out to the caller
		if (!a_message->IsOneWay())
			SendNonBlocking(l_response);
		l_handled = true;
	}

	if (l_handled)
		return;

	if (TryHandleWithServer(*a_message, l_response))
	{
		if (!a_message->IsOneWay())
			SendNonBlocking(l_response);
		l_handled = true;
	}

	if (l_handled)
		return;

	// If this message is not a request, then send a fault back to the caller
	if (a_message->RequestId().empty() && !a_message->IsOneWay())
	{
		l_response = make_shared<CMessage>(*a_message,
				CFaultException("The action '" + a_message->GetAction() + "' has no supported handlers."));
		SendNonBlocking(l_response);
	}
	else
	{
		// This is probably due to a timeout
		// TODO: Log this
	}
}

void CAxonClient::p_OnDataReceived(CDataBuffer a_buffer)
{
	// This function is invoked whenever the data connection
	// signals that data has been received from the remote peer.
	// In the case of the AxonClient, this should be immediately forwarded to
	// the protocol so that a message can be reconstructed from it.
	// The data connection owns the buffer, so a copy must be made

	m_protocol->Process(move(a_buffer));
}

bool CAxonClient::TryHandleWithServer(const CMessage& a_msg, CMessage::Ptr& a_out) const
{
	// Derived instances need to override this
	return false;
}

}
}

<commit_msg>Fixed a bug with the async call stuff<commit_after>/*
 * File description: axon_client.cpp
 * Author information: Mike Raninger mikeranzinger@gmail.com
 * Copyright information: Copyright Mike Ranzinger
 */

#include "communication/messaging/axon_client.h"
#include "communication/timeout_exception.h"

#include <functional>
#include <assert.h>

using namespace std;

namespace axon { namespace communication {

struct CMessageSocket
{
	CMessageSocket(CMessage::Ptr a_outboundMessage)
		: OutboundMessage(move(a_outboundMessage))
	{
	}

	CMessage::Ptr OutboundMessage;
	CMessage::Ptr IncomingMessage;
};

class CAxonClient::WaitHandle
    : public IMessageWaitHandle
{
public:
    typedef unique_ptr<WaitHandle> Ptr;

    WaitHandle(CAxonClient &a_client, CMessage::Ptr a_message, uint32_t a_timeout)
        : m_client(a_client), m_socket(move(a_message)), m_waited(false), m_timeout(a_timeout)
    {
        m_start = chrono::steady_clock::now();
    }
    ~WaitHandle()
    {
        p_RemoveFromSocketList(true);
    }

    virtual void Wait() override;
    virtual CMessage::Ptr GetMessage() override;

    CAxonClient &m_client;
    CMessageSocket m_socket;
    bool m_waited;
    chrono::steady_clock::time_point m_start;
    uint32_t m_timeout;

private:
    void p_RemoveFromSocketList(bool a_getLock);
};

CAxonClient::CAxonClient()
{
	SetDefaultProtocol();
}

CAxonClient::CAxonClient(const std::string& a_connectionString)
{
	SetDefaultProtocol();

	Connect(a_connectionString);
}

CAxonClient::CAxonClient(IDataConnection::Ptr a_connection)
{
	SetDefaultProtocol();

	Connect(move(a_connection));
}

CAxonClient::CAxonClient(const std::string& a_connectionString, IProtocol::Ptr a_protocol)
{
	SetProtocol(move(a_protocol));

	Connect(a_connectionString);
}

CAxonClient::CAxonClient(IDataConnection::Ptr a_connection, IProtocol::Ptr a_protocol)
{
	SetProtocol(move(a_protocol));

	Connect(move(a_connection));
}

CAxonClient::Ptr CAxonClient::Create()
{
	return make_shared<CAxonClient>();
}

CAxonClient::Ptr CAxonClient::Create(const std::string& a_connectionString)
{
	return make_shared<CAxonClient>(a_connectionString);
}

CAxonClient::Ptr CAxonClient::Create(IDataConnection::Ptr a_connection)
{
	return make_shared<CAxonClient>(move(a_connection));
}

CAxonClient::Ptr CAxonClient::Create(const std::string& a_connectionString,
		IProtocol::Ptr a_protocol)
{
	return make_shared<CAxonClient>(a_connectionString, move(a_protocol));
}

CAxonClient::Ptr CAxonClient::Create(IDataConnection::Ptr a_connection,
		IProtocol::Ptr a_protocol)
{
	return make_shared<CAxonClient>(move(a_connection), move(a_protocol));
}

void CAxonClient::Connect(const std::string& a_connectionString)
{
	Connect(IDataConnection::Create(a_connectionString));
}

void CAxonClient::Connect(IDataConnection::Ptr a_connection)
{
	m_connection = move(a_connection);

	if (m_connection)
	{
#ifdef IS_WINDOWS
		int l_hack;
		m_connection->SetReceiveHandler(
			[this, l_hack](CDataBuffer a_buf)
			{
				p_OnDataReceived(move(a_buf));
			});
#else
		m_connection->SetReceiveHandler(bind(&CAxonClient::p_OnDataReceived, this, placeholders::_1));
#endif
	}
}

void CAxonClient::SetDefaultProtocol()
{
	SetProtocol(GetDefaultProtocol());
}

void CAxonClient::SetProtocol(IProtocol::Ptr a_protocol)
{
	if (!a_protocol)
		throw runtime_error("Invalid protocol. Cannot be null.");

	m_protocol = move(a_protocol);

	m_protocol->SetHandler(bind(&CAxonClient::p_OnMessageReceived, this, placeholders::_1));
}

string CAxonClient::ConnectionString() const
{
    if (!m_connection)
        return "";
    return m_connection->ConnectionString();
}

CMessage::Ptr CAxonClient::Send(const CMessage::Ptr &a_message)
{

	return Send(a_message, 0);
}

CMessage::Ptr CAxonClient::Send(const CMessage::Ptr &a_message, uint32_t a_timeout)
{
	IMessageWaitHandle::Ptr l_waitHandle = SendAsync(a_message, a_timeout);

	return l_waitHandle->GetMessage();
}

IMessageWaitHandle::Ptr CAxonClient::SendAsync(const CMessage::Ptr& a_message)
{
    return SendAsync(a_message, 0);
}

IMessageWaitHandle::Ptr CAxonClient::SendAsync(const CMessage::Ptr& a_message, uint32_t a_timeout)
{
    if (!m_connection || !m_connection->IsOpen())
        throw runtime_error("Cannot send data over a dead connection.");
    // Default timeout is 1 minute
    if (a_timeout == 0)
        a_timeout = 60000;

    WaitHandle::Ptr l_waitHandle(new WaitHandle(*this, a_message, a_timeout));

    // Add the socket to the map of messages waiting to be handled
    {
        lock_guard<mutex> l_lock(m_pendingLock);

        m_pendingList.push_back(&l_waitHandle->m_socket);
    }

    p_Send(*a_message);

    return move(l_waitHandle);
}

//--------------------------------------------------------------
// Wait Handle Implementation
//--------------------------------------------------------------
void CAxonClient::WaitHandle::Wait()
{
    if (m_waited)
        return;

    auto l_durLeft = chrono::milliseconds(m_timeout) -
            chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - m_start);

    unique_lock<mutex> l_waitLock(m_client.m_pendingLock);

    if (m_socket.IncomingMessage)
    {
        p_RemoveFromSocketList(false);
        m_waited = true;
        return;
    }

    if (l_durLeft < chrono::milliseconds(0))
        throw CTimeoutException(m_timeout);

    while (!m_socket.IncomingMessage)
    {
        cv_status l_status = m_client.m_newMessageEvent.wait_for(l_waitLock, l_durLeft);

        l_durLeft = chrono::milliseconds(m_timeout) -
            chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - m_start);

        if (m_socket.IncomingMessage
                || l_status == cv_status::timeout
                || l_durLeft < chrono::milliseconds(0))
        {
            // Don't need to acquire the lock because we already have it
            p_RemoveFromSocketList(false);

            if (!m_socket.IncomingMessage)
            {
                throw CTimeoutException(m_timeout);
            }
        }
    }

    assert(m_socket.IncomingMessage);
    m_socket.IncomingMessage->FaultCheck();

    m_waited = true;
}

CMessage::Ptr CAxonClient::WaitHandle::GetMessage()
{
    Wait();

    return m_socket.IncomingMessage;
}

void CAxonClient::WaitHandle::p_RemoveFromSocketList(bool a_getLock)
{
    try
    {
        if (a_getLock)
            m_client.m_pendingLock.lock();

        auto iter = find(m_client.m_pendingList.begin(), m_client.m_pendingList.end(), &m_socket);

        if (iter != m_client.m_pendingList.end())
            m_client.m_pendingList.erase(iter);

        if (a_getLock)
            m_client.m_pendingLock.unlock();
    }
    catch (...)
    {
        if (a_getLock)
            m_client.m_pendingLock.unlock();
        throw;
    }
}
//--------------------------------------------------------------

void CAxonClient::SendNonBlocking(const CMessage::Ptr &a_message)
{
	a_message->SetOneWay(true);

	p_Send(*a_message);
}

void CAxonClient::p_Send(const CMessage& a_message)
{
	CDataBuffer l_buffer = m_protocol->SerializeMessage(a_message);

	m_connection->Send(l_buffer.ToShared());
}

void CAxonClient::p_OnMessageReceived(const CMessage::Ptr& a_message)
{
	// This function is invoked whenever the protocol has reconstructed
	// a message. There are 3 things that this object needs to try before
	// erroring out:
	// 1) Check to see if this message is a response from an outbound call
	//    Resolution: Add the message to the new messages map and signal
	//                that there is a new message
	// 2) Check to see if this instance has a handler for this message
	//    Resolution: Handle the message and send the return value back out
	// 3) If this client is a child of a server, then see if the server
	//      can handle the message.
	//
	// If none of the steps succeed, then throw a fault

    SetExecutingInstance(this);

	bool l_handled = false;

	{
		lock_guard<mutex> l_lock(m_pendingLock);

		const std::string &l_reqId = a_message->RequestId();

		// See if the RequestId of this message is the Id of a message
		// in the outbound list
		auto iter = find_if(m_pendingList.begin(), m_pendingList.end(),
				[&l_reqId] (CMessageSocket *l_sock)
				{
					return l_reqId == l_sock->OutboundMessage->Id();
				});

		// This message is a result of an outbound request, so let
		// the blocking outbound requests know
		if (iter != m_pendingList.end())
		{
			(*iter)->IncomingMessage = a_message;
			l_handled = true;
		}
	}

	if (l_handled)
	{
		// Wake up everyone that is currently waiting
		m_newMessageEvent.notify_all();
		return;
	}

	// Ok, so this message isn't a result of an outbound call, so see if this
	// client has a handler for it
	CMessage::Ptr l_response;
	if (TryHandle(*a_message, l_response))
	{
		// There was a handler for this message, so now
		// send it back out to the caller
		if (!a_message->IsOneWay())
			SendNonBlocking(l_response);
		l_handled = true;
	}

	if (l_handled)
		return;

	if (TryHandleWithServer(*a_message, l_response))
	{
		if (!a_message->IsOneWay())
			SendNonBlocking(l_response);
		l_handled = true;
	}

	if (l_handled)
		return;

	// If this message is not a request, then send a fault back to the caller
	if (a_message->RequestId().empty() && !a_message->IsOneWay())
	{
		l_response = make_shared<CMessage>(*a_message,
				CFaultException("The action '" + a_message->GetAction() + "' has no supported handlers."));
		SendNonBlocking(l_response);
	}
	else
	{
		// This is probably due to a timeout
		// TODO: Log this
	}
}

void CAxonClient::p_OnDataReceived(CDataBuffer a_buffer)
{
	// This function is invoked whenever the data connection
	// signals that data has been received from the remote peer.
	// In the case of the AxonClient, this should be immediately forwarded to
	// the protocol so that a message can be reconstructed from it.
	// The data connection owns the buffer, so a copy must be made

	m_protocol->Process(move(a_buffer));
}

bool CAxonClient::TryHandleWithServer(const CMessage& a_msg, CMessage::Ptr& a_out) const
{
	// Derived instances need to override this
	return false;
}

}
}

<|endoftext|>


<commit_before>#include <cstdlib>
#include "mseq.hpp"
#include "state.hpp"
#include "automata.hpp"

typedef Automata<mseq::empty>
    ::push_state<State<0>>::type
    ::push_state<State<1>>::type
    ::push_state<State<2, true>>::type
    ::start_state<2>::type
    automata;

template <typename T>
void print_type() {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

int main() {
    print_type<automata>();
    return 0;
}
<commit_msg>Update some tests<commit_after>#include <cstdlib>
#include "mseq.hpp"
#include "state.hpp"
#include "automata.hpp"

typedef
    Automata<>

    ::create_state<0>::type
    ::create_state<1, true>::type

    ::start_state<0>::type

    ::create_edge<0, 1, 'a'>::type
    ::create_edge<1, 1, 'a'>::type
    ::create_edge<1, 0, ','>::type

    automata;

typedef
    automata::get_state<1>::type
    state1;

template <typename T>
void print_type() {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

int main() {

    //if (automata::match("aa,a")::value) {
    //    std::cout << "matched" << std::endl;
    //}

    print_type<automata>();
    print_type<automata::get_edges_for<1>::type>();
    //print_type<state1>();

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>

using namespace std;

int main() {
        string userinput = "";
	string login;
	if(!getlogin())
		perror("getlogin");
	else
		login = getlogin();
	char hostname[64];
	if(gethostname(hostname, sizeof hostname))
		perror("gethostname");
	while(userinput != "exit") {
		cout << getlogin() << "@" << hostname <<  " $ ";
		getline(cin, userinput);
	}
	return 0;
}
<commit_msg>got rid of main while to start parse<commit_after>#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>

using namespace std;

int main() {
        string userinput = "";
	string login;
	if(!getlogin())
		perror("getlogin");
	else
		login = getlogin();
	char hostname[64];
	if(gethostname(hostname, sizeof hostname))
		perror("gethostname");
	return 0;
}
<|endoftext|>


<commit_before>#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <omp.h>
#include <sstream>
#include <binUtils.h>
#include <ompUtils.h>
#include <parUtils.h>
#include <octUtils.h>

#include <TreeNode.h>
#include <gensort.h>
#include <sortRecord.h>

#define MAX_DEPTH 30
#define SORT_FUNCTION par::HyperQuickSort

// #define SORT_FUNCTION par::sampleSort
// #define __VERIFY__

long getNumElements(char* code) {
  unsigned int slen = strlen(code);
  char dtype = code[0];
  char tmp[128];
  strncpy(tmp, code+1, slen-3); tmp[slen-3] = '\0';
  // std::cout << "tmp is " << tmp << std::endl;
  long numBytes = atoi(tmp);
  switch(code[slen-2]) {
    case 'g':
    case 'G':
      numBytes *= 1024*1024*1024;
      break;
    case 'k':
    case 'K':
      numBytes *= 1024;
      break;
    case 'm':
    case 'M':
      numBytes *= 1024*1024;
      break;
    default:
      // std::cout << "unknown code " << code[slen-2] << std::endl;
      return 0;
  };

  switch (dtype) {
    case 'd': // double array
      return numBytes/sizeof(double);
      break;
    case 'f': // float array
      return numBytes/sizeof(float);
      break;
    case 'i': // int array
      return numBytes/sizeof(int);
      break;
    case 'l': // long array
      return numBytes/sizeof(long);
      break;
    case 't': // treenode
      return numBytes/sizeof(ot::TreeNode);
      break;
    case 'x': // gensort record
      return numBytes/sizeof(sortRecord);
      break;
    default:
      return 0;
  };

}

template <class T>
bool verify(std::vector<T>& in_, std::vector<T> &out_, MPI_Comm comm){

  // Find out my identity in the default communicator
  int myrank, p;
  MPI_Comm_rank(comm, &myrank);
  MPI_Comm_size(comm,&p);

  std::vector<T> in;
  {
    int N_local=in_.size()*sizeof(T);
    std::vector<int> r_size(p, 0);
    std::vector<int> r_disp(p, 0);
    MPI_Gather(&N_local  , 1, MPI_INT,
        &r_size[0], 1, MPI_INT, 0, comm);
    omp_par::scan(&r_size[0], &r_disp[0], p);

    if(!myrank) in.resize((r_size[p-1]+r_disp[p-1])/sizeof(T));
    MPI_Gatherv((char*)&in_[0],    N_local,             MPI_BYTE,
        (char*)&in [0], &r_size[0], &r_disp[0], MPI_BYTE, 0, comm);
  }

  std::vector<T> out;
  {
    int N_local=out_.size()*sizeof(T);
    std::vector<int> r_size(p, 0);
    std::vector<int> r_disp(p, 0);
    MPI_Gather(&N_local  , 1, MPI_INT,
        &r_size[0], 1, MPI_INT, 0, comm);
    omp_par::scan(&r_size[0], &r_disp[0], p);

    if(!myrank) out.resize((r_size[p-1]+r_disp[p-1])/sizeof(T));
    MPI_Gatherv((char*)&out_[0],    N_local,             MPI_BYTE,
        (char*)&out [0], &r_size[0], &r_disp[0], MPI_BYTE, 0, comm);
  }

  if(in.size()!=out.size()){
    std::cout<<"Wrong size: in="<<in.size()<<" out="<<out.size()<<'\n';
    return false;
  }
  std::sort(&in[0], &in[in.size()]);

  for(long j=0;j<in.size();j++)
    if(in[j]!=out[j]){
      std::cout<<"Failed at:"<<j<<'\n';
//      std::cout<<"Failed at:"<<j<<"; in="<<in[j]<<" out="<<out[j]<<'\n';
      return false;
    }

  return true;
}

double time_sort_bench(size_t N, MPI_Comm comm) {
  int myrank, p;

  MPI_Comm_rank(comm, &myrank);
  MPI_Comm_size(comm,&p);

  typedef sortRecord Data_t;
  std::vector<Data_t> in(N);
  genRecords((char* )&(*(in.begin())), myrank, N);

  std::vector<Data_t> in_cpy=in;
  std::vector<Data_t> out;

  // Warmup run and verification.
  SORT_FUNCTION<Data_t>(in, out, comm);
  // SORT_FUNCTION<Data_t>(in_cpy, comm);
  in=in_cpy;
#ifdef __VERIFY__
  verify(in,out,comm);
#endif

  //Sort
  MPI_Barrier(comm);
  double wtime=-omp_get_wtime();
  SORT_FUNCTION<Data_t>(in, out, comm);
  // SORT_FUNCTION<Data_t>(in, comm);
  MPI_Barrier(comm);
  wtime+=omp_get_wtime();

  return wtime;
}

double time_sort_tn(size_t N, MPI_Comm comm) {
  int myrank, p;

  MPI_Comm_rank(comm, &myrank);
  MPI_Comm_size(comm,&p);
  int omp_p=omp_get_max_threads();

  typedef ot::TreeNode Data_t;
  std::vector<Data_t> in(N);
  unsigned int s = (1u << MAX_DEPTH);
#pragma omp parallel for
  for(int j=0;j<omp_p;j++){
    unsigned int seed=j*p+myrank;
    size_t start=(j*N)/omp_p;
    size_t end=((j+1)*N)/omp_p;
    for(unsigned int i=start;i<end;i++){
      ot::TreeNode node(rand_r(&seed)%s, rand_r(&seed)%s, rand_r(&seed)%s, MAX_DEPTH-1, 3, MAX_DEPTH);
      // ot::TreeNode node(binOp::reversibleHash(3*i*myrank)%s, binOp::reversibleHash(3*i*myrank+1)%s, binOp::reversibleHash(3*i*myrank+2)%s, MAX_DEPTH-1, 3, MAX_DEPTH);
      in[i]=node;
    }
  }

  // std::cout << "finished generating data " << std::endl;
  std::vector<Data_t> in_cpy=in;
  std::vector<Data_t> out;

  // Warmup run and verification.
  SORT_FUNCTION<Data_t>(in, out, comm);
  in=in_cpy;
  // SORT_FUNCTION<Data_t>(in_cpy, comm);
#ifdef __VERIFY__
  verify(in,out,comm);
#endif

  //Sort
  MPI_Barrier(comm);
  double wtime=-omp_get_wtime();
  SORT_FUNCTION<Data_t>(in, out, comm);
  // SORT_FUNCTION<Data_t>(in, comm);
  MPI_Barrier(comm);
  wtime+=omp_get_wtime();

  return wtime;
}

template <class T>
double time_sort(size_t N, MPI_Comm comm){
  int myrank, p;

  MPI_Comm_rank(comm, &myrank);
  MPI_Comm_size(comm,&p);
  int omp_p=omp_get_max_threads();

  // Geerate random data
  std::vector<T> in(N);
#pragma omp parallel for
  for(int j=0;j<omp_p;j++){
    unsigned int seed=j*p+myrank;
    size_t start=(j*N)/omp_p;
    size_t end=((j+1)*N)/omp_p;
    for(unsigned int i=start;i<end;i++){
      in[i]=rand_r(&seed);
    }
  }
  // for(unsigned int i=0;i<N;i++) in[i]=binOp::reversibleHash(myrank*i);
  // std::cout << "finished generating data " << std::endl;
  std::vector<T> in_cpy=in;
  std::vector<T> out;

  // Warmup run and verification.
  SORT_FUNCTION<T>(in, out, comm);
  in=in_cpy;
  // SORT_FUNCTION<T>(in_cpy, comm);
#ifdef __VERIFY__
  verify(in,out,comm);
#endif

  //Sort
  MPI_Barrier(comm);
  double wtime=-omp_get_wtime();
  SORT_FUNCTION<T>(in, out, comm);
  // SORT_FUNCTION<T>(in, comm);
  MPI_Barrier(comm);
  wtime+=omp_get_wtime();

  return wtime;
}

int main(int argc, char **argv){
  if (argc < 3) {
    std::cerr << "Usage: " << argv[0] << " numThreads typeSize" << std::endl;
    std::cerr << "\t\t typeSize is a character for type of data follwed by data size per node." << std::endl;
		std::cerr << "\t\t typeSize can be d-double, f-float, i-int, l-long, t-TreeNode or x-100byte record." << std::endl;
    std::cerr << "\t\t Examples:" << std::endl;
    std::cerr << "\t\t i1GB : integer  array of size 1GB" << std::endl;
    std::cerr << "\t\t l1GB : long     array of size 1GB" << std::endl;
    std::cerr << "\t\t t1GB : TreeNode array of size 1GB" << std::endl;
    std::cerr << "\t\t x4GB : 100byte  array of size 4GB" << std::endl;
    return 1;
  }

  std::cout<<setiosflags(std::ios::fixed)<<std::setprecision(4)<<std::setiosflags(std::ios::right);

  //Set number of OpenMP threads to use.
  omp_set_num_threads(atoi(argv[1]));

  // Initialize MPI
  MPI_Init(&argc, &argv);

  // Find out my identity in the default communicator
  int myrank;
  MPI_Comm_rank(MPI_COMM_WORLD, &myrank);

  // Find out number of processes
  int p;
  MPI_Comm_size(MPI_COMM_WORLD, &p);

  int proc_group=0;
  int min_np=1;
  MPI_Comm comm;
  for(int i=p;myrank<i && i>=min_np ;i=i>>1) proc_group++;
  MPI_Comm_split(MPI_COMM_WORLD, proc_group, myrank, &comm);

  std::vector<double> tt(10000,0);

  int k = 0; // in case size based runs are needed
  char dtype = argv[2][0];
  long N = getNumElements(argv[2]);
  if (!N) {
    std::cerr << "illegal typeSize code provided: " << argv[2] << std::endl;
    return 2;
  }

  if (!myrank)
    std::cout << "sorting array of size " << N*p << " of type " << dtype << std::endl;

  // check if arguments are ok ...

  { // -- full size run
    double ttt;

    switch(dtype) {
			case 'd':
				ttt = time_sort<double>(N, MPI_COMM_WORLD);
				break;
			case 'f':
				ttt = time_sort<float>(N, MPI_COMM_WORLD);
				break;
			case 'i':
				ttt = time_sort<int>(N, MPI_COMM_WORLD);
				break;
      case 'l':
        ttt = time_sort<long>(N, MPI_COMM_WORLD);
        break;
      case 't':
        ttt = time_sort_tn(N, MPI_COMM_WORLD);
        break;
      case 'x':
        ttt = time_sort_bench(N, MPI_COMM_WORLD);
        break;
    };
    if(!myrank){
      tt[100*k+0]=ttt;
    }
  }
  { // smaller /2^k runs
    int myrank_;
    MPI_Comm_rank(comm, &myrank_);
    double ttt;

    switch(dtype) {
			case 'd':
				ttt = time_sort<double>(N, comm);
				break;
			case 'f':
				ttt = time_sort<float>(N, comm);
				break;
			case 'i':
        ttt = time_sort<int>(N, comm);
        break;
      case 'l':
        ttt = time_sort<long>(N, comm);
        break;
      case 't':
        ttt = time_sort_tn(N, comm);
        break;
      case 'x':
        ttt = time_sort_bench(N, comm);
        break;
    };

    if(!myrank_){
      tt[100*k+proc_group]=ttt;
    }
  }

  std::vector<double> tt_glb(10000);
  MPI_Reduce(&tt[0], &tt_glb[0], 10000, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  if(!myrank){
    std::cout<<"\nNew Sort:\n";
    for(int i=0;i<proc_group;i++){
      int np=p;
      if(i>0) np=(p>>(i-1))-(p>>i);
      std::cout<<"\tP="<<np<<' ';
      // for(int k=0;k<=log_N;k++)
        std::cout<<tt_glb[100*k+i]<<' ';
      std::cout<<'\n';
    }
  }

  // Shut down MPI
  MPI_Finalize();
  return 0;

}

<commit_msg>changes to test selection and kway. Do not use this version for runs<commit_after>#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <omp.h>
#include <sstream>
#include <binUtils.h>
#include <ompUtils.h>
#include <parUtils.h>
#include <octUtils.h>

#include <TreeNode.h>
#include <gensort.h>
#include <sortRecord.h>

#define MAX_DEPTH 30
#define SORT_FUNCTION par::HyperQuickSort

// #define SORT_FUNCTION par::sampleSort
// #define __VERIFY__

long getNumElements(char* code) {
  unsigned int slen = strlen(code);
  char dtype = code[0];
  char tmp[128];
  strncpy(tmp, code+1, slen-3); tmp[slen-3] = '\0';
  // std::cout << "tmp is " << tmp << std::endl;
  long numBytes = atoi(tmp);
  switch(code[slen-2]) {
    case 'g':
    case 'G':
      numBytes *= 1024*1024*1024;
      break;
    case 'k':
    case 'K':
      numBytes *= 1024;
      break;
    case 'm':
    case 'M':
      numBytes *= 1024*1024;
      break;
    default:
      // std::cout << "unknown code " << code[slen-2] << std::endl;
      return 0;
  };

  switch (dtype) {
    case 'd': // double array
      return numBytes/sizeof(double);
      break;
    case 'f': // float array
      return numBytes/sizeof(float);
      break;
    case 'i': // int array
      return numBytes/sizeof(int);
      break;
    case 'l': // long array
      return numBytes/sizeof(long);
      break;
    case 't': // treenode
      return numBytes/sizeof(ot::TreeNode);
      break;
    case 'x': // gensort record
      return numBytes/sizeof(sortRecord);
      break;
    default:
      return 0;
  };

}

template <class T>
bool verify(std::vector<T>& in_, std::vector<T> &out_, MPI_Comm comm){

  // Find out my identity in the default communicator
  int myrank, p;
  MPI_Comm_rank(comm, &myrank);
  MPI_Comm_size(comm,&p);

  std::vector<T> in;
  {
    int N_local=in_.size()*sizeof(T);
    std::vector<int> r_size(p, 0);
    std::vector<int> r_disp(p, 0);
    MPI_Gather(&N_local  , 1, MPI_INT,
        &r_size[0], 1, MPI_INT, 0, comm);
    omp_par::scan(&r_size[0], &r_disp[0], p);

    if(!myrank) in.resize((r_size[p-1]+r_disp[p-1])/sizeof(T));
    MPI_Gatherv((char*)&in_[0],    N_local,             MPI_BYTE,
        (char*)&in [0], &r_size[0], &r_disp[0], MPI_BYTE, 0, comm);
  }

  std::vector<T> out;
  {
    int N_local=out_.size()*sizeof(T);
    std::vector<int> r_size(p, 0);
    std::vector<int> r_disp(p, 0);
    MPI_Gather(&N_local  , 1, MPI_INT,
        &r_size[0], 1, MPI_INT, 0, comm);
    omp_par::scan(&r_size[0], &r_disp[0], p);

    if(!myrank) out.resize((r_size[p-1]+r_disp[p-1])/sizeof(T));
    MPI_Gatherv((char*)&out_[0],    N_local,             MPI_BYTE,
        (char*)&out [0], &r_size[0], &r_disp[0], MPI_BYTE, 0, comm);
  }

  if(in.size()!=out.size()){
    std::cout<<"Wrong size: in="<<in.size()<<" out="<<out.size()<<'\n';
    return false;
  }
  std::sort(&in[0], &in[in.size()]);

  for(long j=0;j<in.size();j++)
    if(in[j]!=out[j]){
      std::cout<<"Failed at:"<<j<<'\n';
//      std::cout<<"Failed at:"<<j<<"; in="<<in[j]<<" out="<<out[j]<<'\n';
      return false;
    }

  return true;
}

double time_sort_bench(size_t N, MPI_Comm comm) {
  int myrank, p;

  MPI_Comm_rank(comm, &myrank);
  MPI_Comm_size(comm,&p);

  typedef sortRecord Data_t;
  std::vector<Data_t> in(N);
  genRecords((char* )&(*(in.begin())), myrank, N);

  std::vector<Data_t> in_cpy=in;
  std::vector<Data_t> out;

  // Warmup run and verification.
  SORT_FUNCTION<Data_t>(in, out, comm);
  // SORT_FUNCTION<Data_t>(in_cpy, comm);
  in=in_cpy;
#ifdef __VERIFY__
  verify(in,out,comm);
#endif

  //Sort
  MPI_Barrier(comm);
  double wtime=-omp_get_wtime();
  SORT_FUNCTION<Data_t>(in, out, comm);
  // SORT_FUNCTION<Data_t>(in, comm);
  MPI_Barrier(comm);
  wtime+=omp_get_wtime();

  return wtime;
}

double time_sort_tn(size_t N, MPI_Comm comm) {
  int myrank, p;

  MPI_Comm_rank(comm, &myrank);
  MPI_Comm_size(comm,&p);
  int omp_p=omp_get_max_threads();

  typedef ot::TreeNode Data_t;
  std::vector<Data_t> in(N);
  unsigned int s = (1u << MAX_DEPTH);
#pragma omp parallel for
  for(int j=0;j<omp_p;j++){
    unsigned int seed=j*p+myrank;
    size_t start=(j*N)/omp_p;
    size_t end=((j+1)*N)/omp_p;
    for(unsigned int i=start;i<end;i++){
      ot::TreeNode node(rand_r(&seed)%s, rand_r(&seed)%s, rand_r(&seed)%s, MAX_DEPTH-1, 3, MAX_DEPTH);
      // ot::TreeNode node(binOp::reversibleHash(3*i*myrank)%s, binOp::reversibleHash(3*i*myrank+1)%s, binOp::reversibleHash(3*i*myrank+2)%s, MAX_DEPTH-1, 3, MAX_DEPTH);
      in[i]=node;
    }
  }

  // std::cout << "finished generating data " << std::endl;
  std::vector<Data_t> in_cpy=in;
  std::vector<Data_t> out;

  // Warmup run and verification.
  SORT_FUNCTION<Data_t>(in, out, comm);
  in=in_cpy;
  // SORT_FUNCTION<Data_t>(in_cpy, comm);
#ifdef __VERIFY__
  verify(in,out,comm);
#endif

  //Sort
  MPI_Barrier(comm);
  double wtime=-omp_get_wtime();
  SORT_FUNCTION<Data_t>(in, out, comm);
  // SORT_FUNCTION<Data_t>(in, comm);
  MPI_Barrier(comm);
  wtime+=omp_get_wtime();

  return wtime;
}

template <class T>
double time_sort(size_t N, MPI_Comm comm){
  int myrank, p;

  MPI_Comm_rank(comm, &myrank);
  MPI_Comm_size(comm,&p);
  int omp_p=omp_get_max_threads();

  // Geerate random data
  std::vector<T> in(N);
#pragma omp parallel for
  for(int j=0;j<omp_p;j++){
    unsigned int seed=j*p+myrank;
    size_t start=(j*N)/omp_p;
    size_t end=((j+1)*N)/omp_p;
    for(unsigned int i=start;i<end;i++){
      in[i]=rand_r(&seed);
    }
  }
  // for(unsigned int i=0;i<N;i++) in[i]=binOp::reversibleHash(myrank*i);
  // std::cout << "finished generating data " << std::endl;
  std::vector<T> in_cpy=in;
  std::vector<T> out;

	unsigned int kway = 7;
	DendroIntL Nglobal=p*N;

	std::vector<unsigned int> min_idx(kway), max_idx(kway);
	std::vector<DendroIntL> K(kway);
	for(size_t i = 0; i < kway; ++i)
	{
		min_idx[i] = 0;
		max_idx[i] = N;
		K[i] = (Nglobal*(i+1))/(kway+1);
	}

	std::sort(in.begin(), in.end());

	double tselect =- omp_get_wtime();
	std::vector<T> guess = par::GuessRangeMedian<T>(in, min_idx, max_idx, comm);
	std::vector<T> slct = par::Sorted_k_Select<T>(in, min_idx, max_idx, K, guess, comm);
	tselect += omp_get_wtime();

	double pselect =- omp_get_wtime();
	std::vector<T> pslct = par::Sorted_approx_Select(in, kway, comm);
	pselect += omp_get_wtime();

	if (!myrank) {
		for(size_t i = 0; i < kway; ++i)
		{
			std::cout << slct[i] << " " << pslct[i] << std::endl;
		}
		std::cout << "times: " << tselect << " " << pselect << std::endl;
	}

	return 0.0;

  // Warmup run and verification.
  SORT_FUNCTION<T>(in, out, comm);
  in=in_cpy;
  // SORT_FUNCTION<T>(in_cpy, comm);
#ifdef __VERIFY__
  verify(in,out,comm);
#endif

  //Sort
  MPI_Barrier(comm);
  double wtime=-omp_get_wtime();
  SORT_FUNCTION<T>(in, out, comm);
  // SORT_FUNCTION<T>(in, comm);
  MPI_Barrier(comm);
  wtime+=omp_get_wtime();

  return wtime;
}

int main(int argc, char **argv){
  if (argc < 3) {
    std::cerr << "Usage: " << argv[0] << " numThreads typeSize" << std::endl;
    std::cerr << "\t\t typeSize is a character for type of data follwed by data size per node." << std::endl;
		std::cerr << "\t\t typeSize can be d-double, f-float, i-int, l-long, t-TreeNode or x-100byte record." << std::endl;
    std::cerr << "\t\t Examples:" << std::endl;
    std::cerr << "\t\t i1GB : integer  array of size 1GB" << std::endl;
    std::cerr << "\t\t l1GB : long     array of size 1GB" << std::endl;
    std::cerr << "\t\t t1GB : TreeNode array of size 1GB" << std::endl;
    std::cerr << "\t\t x4GB : 100byte  array of size 4GB" << std::endl;
    return 1;
  }

  std::cout<<setiosflags(std::ios::fixed)<<std::setprecision(4)<<std::setiosflags(std::ios::right);

  //Set number of OpenMP threads to use.
  omp_set_num_threads(atoi(argv[1]));

  // Initialize MPI
  MPI_Init(&argc, &argv);

  // Find out my identity in the default communicator
  int myrank;
  MPI_Comm_rank(MPI_COMM_WORLD, &myrank);

  // Find out number of processes
  int p;
  MPI_Comm_size(MPI_COMM_WORLD, &p);

  int proc_group=0;
  int min_np=1;
  MPI_Comm comm;
  for(int i=p;myrank<i && i>=min_np ;i=i>>1) proc_group++;
  MPI_Comm_split(MPI_COMM_WORLD, proc_group, myrank, &comm);

  std::vector<double> tt(10000,0);

  int k = 0; // in case size based runs are needed
  char dtype = argv[2][0];
  long N = getNumElements(argv[2]);
  if (!N) {
    std::cerr << "illegal typeSize code provided: " << argv[2] << std::endl;
    return 2;
  }

  if (!myrank)
    std::cout << "sorting array of size " << N*p << " of type " << dtype << std::endl;

  // check if arguments are ok ...

  { // -- full size run
    double ttt;

    switch(dtype) {
			case 'd':
				ttt = time_sort<double>(N, MPI_COMM_WORLD);
				break;
			case 'f':
				ttt = time_sort<float>(N, MPI_COMM_WORLD);
				break;
			case 'i':
				ttt = time_sort<int>(N, MPI_COMM_WORLD);
				break;
      case 'l':
        ttt = time_sort<long>(N, MPI_COMM_WORLD);
        break;
      case 't':
        ttt = time_sort_tn(N, MPI_COMM_WORLD);
        break;
      case 'x':
        ttt = time_sort_bench(N, MPI_COMM_WORLD);
        break;
    };
    if(!myrank){
      tt[100*k+0]=ttt;
    }
  }
	MPI_Finalize();
	return 0;
  { // smaller /2^k runs
    int myrank_;
    MPI_Comm_rank(comm, &myrank_);
    double ttt;

    switch(dtype) {
			case 'd':
				ttt = time_sort<double>(N, comm);
				break;
			case 'f':
				ttt = time_sort<float>(N, comm);
				break;
			case 'i':
        ttt = time_sort<int>(N, comm);
        break;
      case 'l':
        ttt = time_sort<long>(N, comm);
        break;
      case 't':
        ttt = time_sort_tn(N, comm);
        break;
      case 'x':
        ttt = time_sort_bench(N, comm);
        break;
    };

    if(!myrank_){
      tt[100*k+proc_group]=ttt;
    }
  }

  std::vector<double> tt_glb(10000);
  MPI_Reduce(&tt[0], &tt_glb[0], 10000, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  if(!myrank){
    std::cout<<"\nNew Sort:\n";
    for(int i=0;i<proc_group;i++){
      int np=p;
      if(i>0) np=(p>>(i-1))-(p>>i);
      std::cout<<"\tP="<<np<<' ';
      // for(int k=0;k<=log_N;k++)
        std::cout<<tt_glb[100*k+i]<<' ';
      std::cout<<'\n';
    }
  }

  // Shut down MPI
  MPI_Finalize();
  return 0;

}

<|endoftext|>


<commit_before>/*
 * StepParameters.hpp
 *
 *  Created on: Feb 18, 2016
 *      Author: Péter Fankhauser
 *   Institute: ETH Zurich, Autonomous Systems Lab
 */

#pragma once

#include "free_gait_core/TypeDefs.hpp"
#include "free_gait_core/step/StepCompleter.hpp"

namespace free_gait {

class StepParameters
{
 public:
  StepParameters() {}
  virtual ~StepParameters() {};

  friend class StepCompleter;

 protected:

  struct FootstepParameters
  {
    std::string profileType = "triangle";
    double profileHeight = 0.05;
    double averageVelocity = 0.3;
    double liftOffSpeed = 0.05;
    double touchdownSpeed = 0.07;
    double minimumDuration_ = 0.3;
  } footTargetParameters;

  struct EndEffectorTargetParameters
  {
    double averageVelocity = 0.15;
    double minimumDuration_ = 0.1;
  } endEffectorTargetParameters;

  struct LegModeParameters
  {
    double duration = 0.5;
    std::string frameId = "base";
  } legModeParameters;

  struct BaseAutoParameters
  {
    double averageLinearVelocity = 0.14;
    double averageAngularVelocity = 0.25;
    double supportMargin = 0.05;
    double minimumDuration = 0.4;
    PlanarStance nominalPlanarStanceInBaseFrame;

    BaseAutoParameters()
    {
      Position2 position;
      position << 0.385, 0.25;
      nominalPlanarStanceInBaseFrame.emplace(LimbEnum::LF_LEG, position);
      nominalPlanarStanceInBaseFrame.emplace(LimbEnum::RF_LEG, Position2(Eigen::Vector2d(position(0), -position(1))));
      nominalPlanarStanceInBaseFrame.emplace(LimbEnum::LH_LEG, Position2(Eigen::Vector2d(-position(0), position(1))));
      nominalPlanarStanceInBaseFrame.emplace(LimbEnum::RH_LEG, Position2(Eigen::Vector2d(-position(0), -position(1))));
    }

  } baseAutoParameters;

  struct BaseTargetParameters
  {
    double averageLinearVelocity = 0.05;
    double averageAngularVelocity = 0.1;
    double minimumDuration = 0.7;
  } baseTargetParameters;

  struct BaseTrajectoryParameters
  {
    BaseTrajectoryParameters()
    {
    }

  } baseTrajectoryParameters;
};

} /* namespace */
<commit_msg>Increased speed of footstep and base auto.<commit_after>/*
 * StepParameters.hpp
 *
 *  Created on: Feb 18, 2016
 *      Author: Péter Fankhauser
 *   Institute: ETH Zurich, Autonomous Systems Lab
 */

#pragma once

#include "free_gait_core/TypeDefs.hpp"
#include "free_gait_core/step/StepCompleter.hpp"

namespace free_gait {

class StepParameters
{
 public:
  StepParameters() {}
  virtual ~StepParameters() {};

  friend class StepCompleter;

 protected:

  struct FootstepParameters
  {
    std::string profileType = "triangle";
    double profileHeight = 0.065;
    double averageVelocity = 0.5;
    double liftOffSpeed = 0.06;
    double touchdownSpeed = 0.08;
    double minimumDuration_ = 0.2;
  } footTargetParameters;

  struct EndEffectorTargetParameters
  {
    double averageVelocity = 0.15;
    double minimumDuration_ = 0.1;
  } endEffectorTargetParameters;

  struct LegModeParameters
  {
    double duration = 0.5;
    std::string frameId = "base";
  } legModeParameters;

  struct BaseAutoParameters
  {
    double averageLinearVelocity = 0.18;
    double averageAngularVelocity = 0.32;
    double supportMargin = 0.05;
    double minimumDuration = 0.3;
    PlanarStance nominalPlanarStanceInBaseFrame;

    BaseAutoParameters()
    {
      Position2 position;
      position << 0.385, 0.25;
      nominalPlanarStanceInBaseFrame.emplace(LimbEnum::LF_LEG, position);
      nominalPlanarStanceInBaseFrame.emplace(LimbEnum::RF_LEG, Position2(Eigen::Vector2d(position(0), -position(1))));
      nominalPlanarStanceInBaseFrame.emplace(LimbEnum::LH_LEG, Position2(Eigen::Vector2d(-position(0), position(1))));
      nominalPlanarStanceInBaseFrame.emplace(LimbEnum::RH_LEG, Position2(Eigen::Vector2d(-position(0), -position(1))));
    }

  } baseAutoParameters;

  struct BaseTargetParameters
  {
    double averageLinearVelocity = 0.05;
    double averageAngularVelocity = 0.1;
    double minimumDuration = 0.7;
  } baseTargetParameters;

  struct BaseTrajectoryParameters
  {
    BaseTrajectoryParameters()
    {
    }

  } baseTrajectoryParameters;
};

} /* namespace */
<|endoftext|>


<commit_before>#include "UDLR.h"

UDLR::UDLR(std::shared_ptr<Ps3Controller>& _controller) : controller(_controller) {
    constexpr int width = 40;
    constexpr int height = 60;
    constexpr int padding = 15;

    UButton.addVertex(ofVec3f(0, padding));
    UButton.addVertex(ofVec3f(width/2, padding + height - width));
    UButton.addVertex(ofVec3f(width/2, padding + height));
    UButton.addVertex(ofVec3f(-1*width/2, padding + height));
    UButton.addVertex(ofVec3f(-1*width/2, padding + height - width));
}

UDLR::~UDLR() {

}

const ofColor& UDLR::getColor(const float& val) {
    static ofColor c;

    c.set(val, val, val);

    return c;
}

void UDLR::draw() {

    using v = Ps3Controller::CVal;

    ofPushStyle();
    ofPushMatrix();
    ofFill();

    ofSetColor(getColor(controller->getCVal(v::D)));
    UButton.draw();

    ofRotateDeg(90);
    ofSetColor(getColor(controller->getCVal(v::L)));
    UButton.draw();

    ofRotateDeg(90);
    ofSetColor(getColor(controller->getCVal(v::U)));
    UButton.draw();

    ofRotateDeg(90);
    ofSetColor(getColor(controller->getCVal(v::R)));
    UButton.draw();

    ofPopMatrix();
    ofPopStyle();
}
<commit_msg>less wrong<commit_after>#include "UDLR.h"

UDLR::UDLR(std::shared_ptr<Ps3Controller>& _controller) : controller(_controller) {
    constexpr int width = 40;
    constexpr int height = 60;
    constexpr int padding = 15;

    UButton.addVertex(ofVec3f(0, padding));
    UButton.addVertex(ofVec3f(width/2, padding + height - width));
    UButton.addVertex(ofVec3f(width/2, padding + height));
    UButton.addVertex(ofVec3f(-1*width/2, padding + height));
    UButton.addVertex(ofVec3f(-1*width/2, padding + height - width));

    UButton.addIndex(0);
    UButton.addIndex(1);
    UButton.addIndex(4);

    UButton.addIndex(1);
    UButton.addIndex(2);
    UButton.addIndex(3);

    UButton.addIndex(3);
    UButton.addIndex(4);
    UButton.addIndex(1);
}

UDLR::~UDLR() {

}

const ofColor& UDLR::getColor(const float& val) {
    static ofColor c;

    c.set(val, val, val);

    return c;
}

void UDLR::draw() {

    using v = Ps3Controller::CVal;

    ofPushStyle();
    ofPushMatrix();
    ofFill();

    ofSetColor(getColor(controller->getCVal(v::D)));
    UButton.draw();

    ofRotateDeg(90);
    ofSetColor(getColor(controller->getCVal(v::L)));
    UButton.draw();

    ofRotateDeg(90);
    ofSetColor(getColor(controller->getCVal(v::U)));
    UButton.draw();

    ofRotateDeg(90);
    ofSetColor(getColor(controller->getCVal(v::R)));
    UButton.draw();

    ofPopMatrix();
    ofPopStyle();
}
<|endoftext|>


<commit_before>#include "User.hpp"
#include "Network.hpp"
#include "PawnDispatcher.hpp"
#include "PawnCallback.hpp"
#include "CLog.hpp"
#include "utils.hpp"

User::User(UserId_t pawn_id, json &data) :
	m_PawnId(pawn_id)
{
	if (!utils::TryGetJsonValue(data, m_Id, "id"))
	{
		CLog::Get()->Log(LogLevel::ERROR,
			"invalid JSON: expected \"id\" in \"{}\"", data.dump());
		return;
	}

	Update(data);
}

void User::Update(json &data)
{
	_valid =
		utils::TryGetJsonValue(data, m_Username, "username") &&
		utils::TryGetJsonValue(data, m_Discriminator, "discriminator");

	if (!_valid)
	{
		CLog::Get()->Log(LogLevel::ERROR,
			"can't update user: invalid JSON: \"{}\"", data.dump());
		return;
	}

	utils::TryGetJsonValue(data, m_IsBot, "bot");
	utils::TryGetJsonValue(data, m_IsVerified, "verified");
	utils::TryGetJsonValue(data, m_Email, "email");
}

void UserManager::Initialize()
{
	assert(m_Initialized != m_InitValue);

	Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::READY, [this](json &data)
	{
		if (!utils::IsValidJson(data, "user", json::value_t::object))
		{
			// TODO: should be loglevel fatal
			CLog::Get()->Log(LogLevel::ERROR,
				"invalid JSON: expected \"user\" in \"{}\"", data.dump());
			return;
		}
		AddUser(data["user"]); // that's our bot
		m_Initialized++;
	});

	Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::USER_UPDATE, [](json &data)
	{
		Snowflake_t user_id;
		if (!utils::TryGetJsonValue(data, user_id, "id"))
		{
			CLog::Get()->Log(LogLevel::ERROR,
				"invalid JSON: expected \"id\" in \"{}\"", data.dump());
		}

		PawnDispatcher::Get()->Dispatch([data, user_id]() mutable
		{
			auto const &user = UserManager::Get()->FindUserById(user_id);
			if (!user)
			{
				CLog::Get()->Log(LogLevel::ERROR,
					"can't update user: user id \"{}\" not cached", user_id);
				return;
			}

			user->Update(data);

			// forward DCC_OnUserUpdate(DCC_User:user);
			PawnCallbackManager::Get()->Call("DCC_OnUserUpdate", user->GetPawnId());
		});
	});
}

bool UserManager::WaitForInitialization()
{
	unsigned int const
		SLEEP_TIME_MS = 20,
		TIMEOUT_TIME_MS = 20 * 1000;
	unsigned int waited_time = 0;
	while (m_Initialized != m_InitValue)
	{
		std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME_MS));
		waited_time += SLEEP_TIME_MS;
		if (waited_time > TIMEOUT_TIME_MS)
			return false;
	}
	return true;
}

UserId_t UserManager::AddUser(json &data)
{
	Snowflake_t sfid;
	if (!utils::TryGetJsonValue(data, sfid, "id"))
	{
		CLog::Get()->Log(LogLevel::ERROR,
			"invalid JSON: expected \"id\" in \"{}\"", data.dump());
		return INVALID_USER_ID;
	}

	User_t const &user = FindUserById(sfid);
	if (user)
	{
		CLog::Get()->Log(LogLevel::ERROR,
			"can't add user: user id \"{}\" already exists (PAWN id '{}')",
			sfid, user->GetPawnId());
		return INVALID_USER_ID;
	}

	UserId_t id = 1;
	while (m_Users.find(id) != m_Users.end())
		++id;

	if (!m_Users.emplace(id, User_t(new User(id, data))).first->second)
	{
		CLog::Get()->Log(LogLevel::ERROR,
			"can't create user: duplicate key '{}'", id);
		return INVALID_USER_ID;
	}

	return id;
}

User_t const &UserManager::FindUser(UserId_t id)
{
	static User_t invalid_user;
	auto it = m_Users.find(id);
	if (it == m_Users.end())
		return invalid_user;
	return it->second;
}

User_t const &UserManager::FindUserByName(
	std::string const &name, std::string const &discriminator)
{
	static User_t invalid_user;
	for (auto const &u : m_Users)
	{
		User_t const &user = u.second;
		if (user->GetUsername().compare(name) == 0
			&& user->GetDiscriminator().compare(discriminator) == 0)
		{
			return user;
		}
	}
	return invalid_user;
}

User_t const &UserManager::FindUserById(Snowflake_t const &sfid)
{
	static User_t invalid_user;
	for (auto const &u : m_Users)
	{
		User_t const &user = u.second;
		if (user->GetId().compare(sfid) == 0)
			return user;
	}
	return invalid_user;
}
<commit_msg>return user id if it already exists<commit_after>#include "User.hpp"
#include "Network.hpp"
#include "PawnDispatcher.hpp"
#include "PawnCallback.hpp"
#include "CLog.hpp"
#include "utils.hpp"

User::User(UserId_t pawn_id, json &data) :
	m_PawnId(pawn_id)
{
	if (!utils::TryGetJsonValue(data, m_Id, "id"))
	{
		CLog::Get()->Log(LogLevel::ERROR,
			"invalid JSON: expected \"id\" in \"{}\"", data.dump());
		return;
	}

	Update(data);
}

void User::Update(json &data)
{
	_valid =
		utils::TryGetJsonValue(data, m_Username, "username") &&
		utils::TryGetJsonValue(data, m_Discriminator, "discriminator");

	if (!_valid)
	{
		CLog::Get()->Log(LogLevel::ERROR,
			"can't update user: invalid JSON: \"{}\"", data.dump());
		return;
	}

	utils::TryGetJsonValue(data, m_IsBot, "bot");
	utils::TryGetJsonValue(data, m_IsVerified, "verified");
	utils::TryGetJsonValue(data, m_Email, "email");
}

void UserManager::Initialize()
{
	assert(m_Initialized != m_InitValue);

	Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::READY, [this](json &data)
	{
		if (!utils::IsValidJson(data, "user", json::value_t::object))
		{
			// TODO: should be loglevel fatal
			CLog::Get()->Log(LogLevel::ERROR,
				"invalid JSON: expected \"user\" in \"{}\"", data.dump());
			return;
		}
		AddUser(data["user"]); // that's our bot
		m_Initialized++;
	});

	Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::USER_UPDATE, [](json &data)
	{
		Snowflake_t user_id;
		if (!utils::TryGetJsonValue(data, user_id, "id"))
		{
			CLog::Get()->Log(LogLevel::ERROR,
				"invalid JSON: expected \"id\" in \"{}\"", data.dump());
		}

		PawnDispatcher::Get()->Dispatch([data, user_id]() mutable
		{
			auto const &user = UserManager::Get()->FindUserById(user_id);
			if (!user)
			{
				CLog::Get()->Log(LogLevel::ERROR,
					"can't update user: user id \"{}\" not cached", user_id);
				return;
			}

			user->Update(data);

			// forward DCC_OnUserUpdate(DCC_User:user);
			PawnCallbackManager::Get()->Call("DCC_OnUserUpdate", user->GetPawnId());
		});
	});
}

bool UserManager::WaitForInitialization()
{
	unsigned int const
		SLEEP_TIME_MS = 20,
		TIMEOUT_TIME_MS = 20 * 1000;
	unsigned int waited_time = 0;
	while (m_Initialized != m_InitValue)
	{
		std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME_MS));
		waited_time += SLEEP_TIME_MS;
		if (waited_time > TIMEOUT_TIME_MS)
			return false;
	}
	return true;
}

UserId_t UserManager::AddUser(json &data)
{
	Snowflake_t sfid;
	if (!utils::TryGetJsonValue(data, sfid, "id"))
	{
		CLog::Get()->Log(LogLevel::ERROR,
			"invalid JSON: expected \"id\" in \"{}\"", data.dump());
		return INVALID_USER_ID;
	}

	User_t const &user = FindUserById(sfid);
	if (user)
		return user->GetPawnId();

	UserId_t id = 1;
	while (m_Users.find(id) != m_Users.end())
		++id;

	if (!m_Users.emplace(id, User_t(new User(id, data))).first->second)
	{
		CLog::Get()->Log(LogLevel::ERROR,
			"can't create user: duplicate key '{}'", id);
		return INVALID_USER_ID;
	}

	return id;
}

User_t const &UserManager::FindUser(UserId_t id)
{
	static User_t invalid_user;
	auto it = m_Users.find(id);
	if (it == m_Users.end())
		return invalid_user;
	return it->second;
}

User_t const &UserManager::FindUserByName(
	std::string const &name, std::string const &discriminator)
{
	static User_t invalid_user;
	for (auto const &u : m_Users)
	{
		User_t const &user = u.second;
		if (user->GetUsername().compare(name) == 0
			&& user->GetDiscriminator().compare(discriminator) == 0)
		{
			return user;
		}
	}
	return invalid_user;
}

User_t const &UserManager::FindUserById(Snowflake_t const &sfid)
{
	static User_t invalid_user;
	for (auto const &u : m_Users)
	{
		User_t const &user = u.second;
		if (user->GetId().compare(sfid) == 0)
			return user;
	}
	return invalid_user;
}
<|endoftext|>


<commit_before>// Copyright 2014 RethinkDB, all rights reserved.
#ifndef CONCURRENCY_NEW_SEMAPHORE_HPP_
#define CONCURRENCY_NEW_SEMAPHORE_HPP_

#include "concurrency/cond_var.hpp"
#include "containers/intrusive_list.hpp"

// KSI: This is a horrible name, fix it.

// This semaphore obeys first-in-line/first-acquisition semantics.  The
// new_semaphore_acq_t's will receive access to the semaphore in the same order that
// such access was requested.  Also, there aren't problems with starvation.  Also, it
// doesn't have naked lock and unlock functions, you have to use new_semaphore_acq_t.

class new_semaphore_acq_t;

class new_semaphore_t {
public:
    explicit new_semaphore_t(int64_t capacity);
    ~new_semaphore_t();

    int64_t capacity() const { return capacity_; }
    int64_t current() const { return current_; }

    void set_capacity(int64_t new_capacity);

private:
    friend class new_semaphore_acq_t;
    void add_acquirer(new_semaphore_acq_t *acq);
    void remove_acquirer(new_semaphore_acq_t *acq);

    void pulse_waiters();

    // Normally, current_ <= capacity_, and capacity_ doesn't change.  current_ can
    // exceed capacity_ for three reasons.
    //   1. A call to change_acquired_count could force it to overflow.
    //   2. An acquirer will never be blocked while current_ is 0.
    //   3. An act of God could change capacity_ (currently unimplemented; hail Satan).
    int64_t capacity_;
    int64_t current_;

    intrusive_list_t<new_semaphore_acq_t> waiters_;

    DISABLE_COPYING(new_semaphore_t);
};

class new_semaphore_acq_t : public intrusive_list_node_t<new_semaphore_acq_t> {
public:
    // Construction is non-blocking, it gets you in line for the semaphore.  You need
    // to call acquisition_signal()->wait() in order to wait for your acquisition of the
    // semaphore.  Acquirers receive the semaphore in the same order that they've
    // acquired it.
    ~new_semaphore_acq_t();
    new_semaphore_acq_t();
    new_semaphore_acq_t(new_semaphore_t *semaphore, int64_t count);
    new_semaphore_acq_t(new_semaphore_acq_t &&movee);

    // Returns "how much" of the semaphore this acq has acquired or would acquire.
    int64_t count() const;

    // Changes "how much" of the semaphore this acq has acquired or would acquire.
    // If it's already acquired the semaphore, and new_count is bigger than the
    // current value of acquired_count(), it's possible that you'll make the
    // semaphore "overfull", meaning that current_ > capacity_.  That's not ideal,
    // but it's O.K.
    void change_count(int64_t new_count);

    // Initializes the object.
    void init(new_semaphore_t *semaphore, int64_t count);

    void reset();

    // Returns a signal that gets pulsed when this has successfully acquired the
    // semaphore.
    const signal_t *acquisition_signal() const { return &cond_; }

private:
    friend class new_semaphore_t;

    // The semaphore this acquires (or NULL if this hasn't acquired a semaphore yet).
    new_semaphore_t *semaphore_;

    // The count of "how much" of the semaphore we've acquired (if semaphore_ is
    // non-NULL).
    int64_t count_;

    // Gets pulsed when we have successfully acquired the semaphore.
    cond_t cond_;
    DISABLE_COPYING(new_semaphore_acq_t);
};

#endif  // CONCURRENCY_NEW_SEMAPHORE_HPP_
<commit_msg>Removed KSI about renaming new_semaphore_t.<commit_after>// Copyright 2014 RethinkDB, all rights reserved.
#ifndef CONCURRENCY_NEW_SEMAPHORE_HPP_
#define CONCURRENCY_NEW_SEMAPHORE_HPP_

#include "concurrency/cond_var.hpp"
#include "containers/intrusive_list.hpp"

// This semaphore obeys first-in-line/first-acquisition semantics.  The
// new_semaphore_acq_t's will receive access to the semaphore in the same order that
// such access was requested.  Also, there aren't problems with starvation.  Also, it
// doesn't have naked lock and unlock functions, you have to use new_semaphore_acq_t.

class new_semaphore_acq_t;

class new_semaphore_t {
public:
    explicit new_semaphore_t(int64_t capacity);
    ~new_semaphore_t();

    int64_t capacity() const { return capacity_; }
    int64_t current() const { return current_; }

    void set_capacity(int64_t new_capacity);

private:
    friend class new_semaphore_acq_t;
    void add_acquirer(new_semaphore_acq_t *acq);
    void remove_acquirer(new_semaphore_acq_t *acq);

    void pulse_waiters();

    // Normally, current_ <= capacity_, and capacity_ doesn't change.  current_ can
    // exceed capacity_ for three reasons.
    //   1. A call to change_acquired_count could force it to overflow.
    //   2. An acquirer will never be blocked while current_ is 0.
    //   3. An act of God could change capacity_ (currently unimplemented; hail Satan).
    int64_t capacity_;
    int64_t current_;

    intrusive_list_t<new_semaphore_acq_t> waiters_;

    DISABLE_COPYING(new_semaphore_t);
};

class new_semaphore_acq_t : public intrusive_list_node_t<new_semaphore_acq_t> {
public:
    // Construction is non-blocking, it gets you in line for the semaphore.  You need
    // to call acquisition_signal()->wait() in order to wait for your acquisition of the
    // semaphore.  Acquirers receive the semaphore in the same order that they've
    // acquired it.
    ~new_semaphore_acq_t();
    new_semaphore_acq_t();
    new_semaphore_acq_t(new_semaphore_t *semaphore, int64_t count);
    new_semaphore_acq_t(new_semaphore_acq_t &&movee);

    // Returns "how much" of the semaphore this acq has acquired or would acquire.
    int64_t count() const;

    // Changes "how much" of the semaphore this acq has acquired or would acquire.
    // If it's already acquired the semaphore, and new_count is bigger than the
    // current value of acquired_count(), it's possible that you'll make the
    // semaphore "overfull", meaning that current_ > capacity_.  That's not ideal,
    // but it's O.K.
    void change_count(int64_t new_count);

    // Initializes the object.
    void init(new_semaphore_t *semaphore, int64_t count);

    void reset();

    // Returns a signal that gets pulsed when this has successfully acquired the
    // semaphore.
    const signal_t *acquisition_signal() const { return &cond_; }

private:
    friend class new_semaphore_t;

    // The semaphore this acquires (or NULL if this hasn't acquired a semaphore yet).
    new_semaphore_t *semaphore_;

    // The count of "how much" of the semaphore we've acquired (if semaphore_ is
    // non-NULL).
    int64_t count_;

    // Gets pulsed when we have successfully acquired the semaphore.
    cond_t cond_;
    DISABLE_COPYING(new_semaphore_acq_t);
};

#endif  // CONCURRENCY_NEW_SEMAPHORE_HPP_
<|endoftext|>


<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/

#include "condor_common.h"
#include "image.h"
#include <sys/procfs.h>		// for /proc calls
#include <sys/mman.h>		// for mmap() test
#include "condor_debug.h"
#include "condor_syscalls.h"

/* a few notes:
 * this is a pretty rough port
 *
 * data_start_addr() is basically an educated guess based on dump(1)
 * it is probably not entirely correct, but does seem to work!
 *
 * stack_end_addr() is generally well known for sparc machines
 * however it doesn't seem to appear in solaris header files
 *
 * JmpBufSP_Index() was derived by dumping the jmp_buf, allocating a
 * large chunk of memory on the stack, and dumping the jmp_buf again
 * whichever value changed by about sizeof(chuck) is the stack pointer
 *
 */

/*
  Return starting address of the data segment
*/
#if defined(X86)
#include <sys/elf_386.h>
#else
#include <sys/elf_SPARC.h>
#endif
extern int _etext;
long
data_start_addr()
{
#if defined(X86)
	return (  (((long)&_etext) + ELF_386_MAXPGSZ) + 0x8 - 1 ) & ~(0x8-1);
#else
	return (  (((long)&_etext) + ELF_SPARC_MAXPGSZ) + 0x8 - 1 ) & ~(0x8-1);
#endif
}

/*
  Return ending address of the data segment
*/
long
data_end_addr()
{
	return (long)sbrk(0);
}

/*
  Return TRUE if the stack grows toward lower addresses, and FALSE
  otherwise.
*/
BOOL StackGrowsDown()
{
	return TRUE;
}

/*
  Return the index into the jmp_buf where the stack pointer is stored.
  Expect that the jmp_buf will be viewed as an array of integers for
  this.
*/
int JmpBufSP_Index()
{
#if defined(X86)
	return 4;
#else
	return 1;
#endif
}

/*
  Return starting address of stack segment.
*/
long
stack_start_addr()
{
	long	answer;

	jmp_buf env;
	(void)SETJMP( env );
	return JMP_BUF_SP(env) & ~1023; // Curr sp, rounded down
}

/*
  Return ending address of stack segment.
*/
long
stack_end_addr()
{
	/* return 0xF8000000; -- for sun4[c] */
#if defined(X86)
	return 0x8048000; /* -- for x86 */
#else
	#if defined(Solaris27)
		return 0xFFBF0000;
	#else
		return 0xF0000000;
	#endif
#endif
}

/*
  Patch any registers whose values should be different at restart
  time than they were at checkpoint time.
*/
void
patch_registers( void *generic_ptr )
{
	// Nothing needed
}

// static prmap_t *my_map = NULL;
static prmap_t my_map[ MAX_SEGS ];
static int	prmap_count = 0;
static int	text_loc = -1, stack_loc = -1, heap_loc = -1;
// static int      mmap_loc = -1;

/*
  Find the segment in my_map which contains the address in addr.
  Used to find the text segment.
*/
int
find_map_for_addr(caddr_t addr)
{
	int		i;

	for (i = 0; i < prmap_count; i++) {
		if (addr >= my_map[i].pr_vaddr &&
			addr <= my_map[i].pr_vaddr + my_map[i].pr_size){
			return i;
		}
	}
	return -1;
}

/*
  Return the number of segments to be checkpointed.  Note that this
  number includes the text segment, which should be ignored.  On error,
  returns -1.
*/
extern "C"   int SYSCALL(int ...);

int
num_segments( )
{
	int	fd;
	char	buf[100];

	int scm = SetSyscalls( SYS_LOCAL | SYS_UNMAPPED );
	sprintf(buf, "/proc/%d", SYSCALL(SYS_getpid));
	fd = SYSCALL(SYS_open, buf, O_RDWR, 0);
	if (fd < 0) {
		return -1;
	}
	SYSCALL(SYS_ioctl, fd, PIOCNMAP, &prmap_count);
	if (prmap_count > MAX_SEGS) {
		dprintf( D_ALWAYS, "Don't know how to grow segment map yet!\n" );
		Suicide();
	}
/*	if (my_map != NULL) {
		free(my_map);
	}
	my_map = (prmap_t *) malloc(sizeof(prmap_t) * (prmap_count + 1));  */

	SYSCALL(SYS_ioctl, fd, PIOCMAP, my_map);
	/* find the text segment by finding where this function is
	   located */
	text_loc = find_map_for_addr((caddr_t) num_segments);
	/* identify the stack segment by looking for the bottom of the stack,
	   because the top of the stack may be in the data area, often the
	   case for programs which utilize threads or co-routine packages. */
	if ( StackGrowsDown() )
		stack_loc = find_map_for_addr((caddr_t) stack_end_addr());
	else
		stack_loc = find_map_for_addr((caddr_t) stack_start_addr());
	heap_loc = find_map_for_addr((caddr_t) data_start_addr());
//	mmap_loc = find_map_for_addr((caddr_t) mmap);
	if (SYSCALL(SYS_close, fd) < 0) {
		dprintf(D_ALWAYS, "close: %s", strerror(errno));
	}
	SetSyscalls( scm );
	return prmap_count;
}

/*
  Assigns the bounds of the segment specified by seg_num to start
  and long, and the protections to prot.  Returns -1 on error, 1 if
  this segment is the text segment, 2 if this segment is the stack
  segment, 3 if this segment is in the data segment, and 0 otherwise.
*/
int
segment_bounds( int seg_num, RAW_ADDR &start, RAW_ADDR &end, int &prot )
{
	if (my_map == NULL)
		return -1;
	start = (long) my_map[seg_num].pr_vaddr;
	end = start + my_map[seg_num].pr_size;
	prot = my_map[seg_num].pr_mflags;
//	if (seg_num == mmap_loc)
//	  fprintf(stderr, "Checkpointing segment containing mmap.\n"
//		  "Segment %d (0x%x - 0x%x) contains mmap.\n",
//		  seg_num, my_map[seg_num].pr_vaddr,
//		  my_map[seg_num].pr_vaddr+my_map[seg_num].pr_size);
	if (seg_num == text_loc)
		return 1;
	else if (seg_num == stack_loc)
		return 2;
	else if (seg_num == heap_loc ||
		 ((unsigned)my_map[seg_num].pr_vaddr >= (unsigned)data_start_addr() &&
		  (unsigned)my_map[seg_num].pr_vaddr <= (unsigned)data_end_addr()))
	        return 3;
	return 0;
}

struct ma_flags {
	int	flag_val;
	char	*flag_name;
} MA_FLAGS[] = {{MA_READ, "MA_READ"},
				{MA_WRITE, "MA_WRITE"},
				{MA_EXEC, "MA_EXEC"},
				{MA_SHARED, "MA_SHARED"},
				{MA_BREAK, "MA_BREAK"},
				{MA_STACK, "MA_STACK"}};

/*
  For use in debugging only.  Displays the segment map of the current
  process.
*/
void
display_prmap()
{
	int		i, j;

	num_segments();
	for (i = 0; i < prmap_count; i++) {
	  dprintf( D_ALWAYS, "addr = 0x%p, size = 0x%x, offset = 0x%x",
		 my_map[i].pr_vaddr, my_map[i].pr_size, my_map[i].pr_off);
	  for (j = 0; j < sizeof(MA_FLAGS) / sizeof(MA_FLAGS[0]); j++) {
	    if (my_map[i].pr_mflags & MA_FLAGS[j].flag_val) {
	      dprintf( D_ALWAYS, " %s", MA_FLAGS[j].flag_name);
	    }
	  }
	  dprintf( D_ALWAYS, "\n");
	}
}
<commit_msg>Updated the top stack pointer for solaris 2.8.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/

#include "condor_common.h"
#include "image.h"
#include <sys/procfs.h>		// for /proc calls
#include <sys/mman.h>		// for mmap() test
#include "condor_debug.h"
#include "condor_syscalls.h"

/* a few notes:
 * this is a pretty rough port
 *
 * data_start_addr() is basically an educated guess based on dump(1)
 * it is probably not entirely correct, but does seem to work!
 *
 * stack_end_addr() is generally well known for sparc machines
 * however it doesn't seem to appear in solaris header files
 *
 * JmpBufSP_Index() was derived by dumping the jmp_buf, allocating a
 * large chunk of memory on the stack, and dumping the jmp_buf again
 * whichever value changed by about sizeof(chuck) is the stack pointer
 *
 */

/*
  Return starting address of the data segment
*/
#if defined(X86)
#include <sys/elf_386.h>
#else
#include <sys/elf_SPARC.h>
#endif
extern int _etext;
long
data_start_addr()
{
#if defined(X86)
	return (  (((long)&_etext) + ELF_386_MAXPGSZ) + 0x8 - 1 ) & ~(0x8-1);
#else
	return (  (((long)&_etext) + ELF_SPARC_MAXPGSZ) + 0x8 - 1 ) & ~(0x8-1);
#endif
}

/*
  Return ending address of the data segment
*/
long
data_end_addr()
{
	return (long)sbrk(0);
}

/*
  Return TRUE if the stack grows toward lower addresses, and FALSE
  otherwise.
*/
BOOL StackGrowsDown()
{
	return TRUE;
}

/*
  Return the index into the jmp_buf where the stack pointer is stored.
  Expect that the jmp_buf will be viewed as an array of integers for
  this.
*/
int JmpBufSP_Index()
{
#if defined(X86)
	return 4;
#else
	return 1;
#endif
}

/*
  Return starting address of stack segment.
*/
long
stack_start_addr()
{
	long	answer;

	jmp_buf env;
	(void)SETJMP( env );
	return JMP_BUF_SP(env) & ~1023; // Curr sp, rounded down
}

/*
  Return ending address of stack segment.
*/
long
stack_end_addr()
{
	/* return 0xF8000000; -- for sun4[c] */
#if defined(X86)
	return 0x8048000; /* -- for x86 */
#else
	#if defined(Solaris27) || defined(Solaris28)
		return 0xFFBF0000;
	#else
		return 0xF0000000;
	#endif
#endif
}

/*
  Patch any registers whose values should be different at restart
  time than they were at checkpoint time.
*/
void
patch_registers( void *generic_ptr )
{
	// Nothing needed
}

// static prmap_t *my_map = NULL;
static prmap_t my_map[ MAX_SEGS ];
static int	prmap_count = 0;
static int	text_loc = -1, stack_loc = -1, heap_loc = -1;
// static int      mmap_loc = -1;

/*
  Find the segment in my_map which contains the address in addr.
  Used to find the text segment.
*/
int
find_map_for_addr(caddr_t addr)
{
	int		i;

	for (i = 0; i < prmap_count; i++) {
		if (addr >= my_map[i].pr_vaddr &&
			addr <= my_map[i].pr_vaddr + my_map[i].pr_size){
			return i;
		}
	}
	return -1;
}

/*
  Return the number of segments to be checkpointed.  Note that this
  number includes the text segment, which should be ignored.  On error,
  returns -1.
*/
extern "C"   int SYSCALL(int ...);

int
num_segments( )
{
	int	fd;
	char	buf[100];

	int scm = SetSyscalls( SYS_LOCAL | SYS_UNMAPPED );
	sprintf(buf, "/proc/%d", SYSCALL(SYS_getpid));
	fd = SYSCALL(SYS_open, buf, O_RDWR, 0);
	if (fd < 0) {
		return -1;
	}
	SYSCALL(SYS_ioctl, fd, PIOCNMAP, &prmap_count);
	if (prmap_count > MAX_SEGS) {
		dprintf( D_ALWAYS, "Don't know how to grow segment map yet!\n" );
		Suicide();
	}
/*	if (my_map != NULL) {
		free(my_map);
	}
	my_map = (prmap_t *) malloc(sizeof(prmap_t) * (prmap_count + 1));  */

	SYSCALL(SYS_ioctl, fd, PIOCMAP, my_map);
	/* find the text segment by finding where this function is
	   located */
	text_loc = find_map_for_addr((caddr_t) num_segments);
	/* identify the stack segment by looking for the bottom of the stack,
	   because the top of the stack may be in the data area, often the
	   case for programs which utilize threads or co-routine packages. */
	if ( StackGrowsDown() )
		stack_loc = find_map_for_addr((caddr_t) stack_end_addr());
	else
		stack_loc = find_map_for_addr((caddr_t) stack_start_addr());
	heap_loc = find_map_for_addr((caddr_t) data_start_addr());
//	mmap_loc = find_map_for_addr((caddr_t) mmap);
	if (SYSCALL(SYS_close, fd) < 0) {
		dprintf(D_ALWAYS, "close: %s", strerror(errno));
	}
	SetSyscalls( scm );
	return prmap_count;
}

/*
  Assigns the bounds of the segment specified by seg_num to start
  and long, and the protections to prot.  Returns -1 on error, 1 if
  this segment is the text segment, 2 if this segment is the stack
  segment, 3 if this segment is in the data segment, and 0 otherwise.
*/
int
segment_bounds( int seg_num, RAW_ADDR &start, RAW_ADDR &end, int &prot )
{
	if (my_map == NULL)
		return -1;
	start = (long) my_map[seg_num].pr_vaddr;
	end = start + my_map[seg_num].pr_size;
	prot = my_map[seg_num].pr_mflags;
//	if (seg_num == mmap_loc)
//	  fprintf(stderr, "Checkpointing segment containing mmap.\n"
//		  "Segment %d (0x%x - 0x%x) contains mmap.\n",
//		  seg_num, my_map[seg_num].pr_vaddr,
//		  my_map[seg_num].pr_vaddr+my_map[seg_num].pr_size);
	if (seg_num == text_loc)
		return 1;
	else if (seg_num == stack_loc)
		return 2;
	else if (seg_num == heap_loc ||
		 ((unsigned)my_map[seg_num].pr_vaddr >= (unsigned)data_start_addr() &&
		  (unsigned)my_map[seg_num].pr_vaddr <= (unsigned)data_end_addr()))
	        return 3;
	return 0;
}

struct ma_flags {
	int	flag_val;
	char	*flag_name;
} MA_FLAGS[] = {{MA_READ, "MA_READ"},
				{MA_WRITE, "MA_WRITE"},
				{MA_EXEC, "MA_EXEC"},
				{MA_SHARED, "MA_SHARED"},
				{MA_BREAK, "MA_BREAK"},
				{MA_STACK, "MA_STACK"}};

/*
  For use in debugging only.  Displays the segment map of the current
  process.
*/
void
display_prmap()
{
	int		i, j;

	num_segments();
	for (i = 0; i < prmap_count; i++) {
	  dprintf( D_ALWAYS, "addr = 0x%p, size = 0x%x, offset = 0x%x",
		 my_map[i].pr_vaddr, my_map[i].pr_size, my_map[i].pr_off);
	  for (j = 0; j < sizeof(MA_FLAGS) / sizeof(MA_FLAGS[0]); j++) {
	    if (my_map[i].pr_mflags & MA_FLAGS[j].flag_val) {
	      dprintf( D_ALWAYS, " %s", MA_FLAGS[j].flag_name);
	    }
	  }
	  dprintf( D_ALWAYS, "\n");
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: vclxaccessiblestatusbar.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 15:27:53 $
 *
 *  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 ACCESSIBILITY_STANDARD_VCLXACCESSIBLESTATUSBAR_HXX
#define ACCESSIBILITY_STANDARD_VCLXACCESSIBLESTATUSBAR_HXX

#ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_
#include <toolkit/awt/vclxaccessiblecomponent.hxx>
#endif

#include <vector>

class StatusBar;

//  ----------------------------------------------------
//  class VCLXAccessibleStatusBar
//  ----------------------------------------------------

class VCLXAccessibleStatusBar : public VCLXAccessibleComponent
{
private:
    typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > > AccessibleChildren;

    AccessibleChildren      m_aAccessibleChildren;
    StatusBar*              m_pStatusBar;

protected:
    void                    UpdateShowing( sal_Int32 i, sal_Bool bShowing );
    void                    UpdateItemName( sal_Int32 i );
    void                    UpdateItemText( sal_Int32 i );

    void                    InsertChild( sal_Int32 i );
    void                    RemoveChild( sal_Int32 i );

    virtual void            ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent );

    // XComponent
    virtual void SAL_CALL   disposing();

public:
    VCLXAccessibleStatusBar( VCLXWindow* pVCLXWindow );
    ~VCLXAccessibleStatusBar();

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException);

    // XAccessibleContext
    virtual sal_Int32 SAL_CALL getAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);

    // XAccessibleComponent
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
};

#endif // ACCESSIBILITY_STANDARD_VCLXACCESSIBLESTATUSBAR_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.2.44); FILE MERGED 2008/04/01 14:58:50 thb 1.2.44.2: #i85898# Stripping all external header guards 2008/03/28 15:57:46 rt 1.2.44.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: vclxaccessiblestatusbar.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef ACCESSIBILITY_STANDARD_VCLXACCESSIBLESTATUSBAR_HXX
#define ACCESSIBILITY_STANDARD_VCLXACCESSIBLESTATUSBAR_HXX

#include <toolkit/awt/vclxaccessiblecomponent.hxx>

#include <vector>

class StatusBar;

//  ----------------------------------------------------
//  class VCLXAccessibleStatusBar
//  ----------------------------------------------------

class VCLXAccessibleStatusBar : public VCLXAccessibleComponent
{
private:
    typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > > AccessibleChildren;

    AccessibleChildren      m_aAccessibleChildren;
    StatusBar*              m_pStatusBar;

protected:
    void                    UpdateShowing( sal_Int32 i, sal_Bool bShowing );
    void                    UpdateItemName( sal_Int32 i );
    void                    UpdateItemText( sal_Int32 i );

    void                    InsertChild( sal_Int32 i );
    void                    RemoveChild( sal_Int32 i );

    virtual void            ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent );

    // XComponent
    virtual void SAL_CALL   disposing();

public:
    VCLXAccessibleStatusBar( VCLXWindow* pVCLXWindow );
    ~VCLXAccessibleStatusBar();

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException);

    // XAccessibleContext
    virtual sal_Int32 SAL_CALL getAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);

    // XAccessibleComponent
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
};

#endif // ACCESSIBILITY_STANDARD_VCLXACCESSIBLESTATUSBAR_HXX

<|endoftext|>