<commit_before>//
// Copyright (C) 2004-2006 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp.  All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////

#ifdef HAVE_SSL

// SYSTEM INCLUDES
#include <assert.h>

// APPLICATION INCLUDES

#include <os/OsDateTime.h>
#include <os/HostAdapterAddress.h>
#include <utl/UtlHashMapIterator.h>

#include <tapi/sipxtapi.h>
#include <os/OsSSLServerSocket.h>
#include <os/OsSSLConnectionSocket.h>

#include <net/SipServerBroker.h>
#include <net/SipTcpServer.h>
#include <net/SipUserAgent.h>
#include <net/SipTlsServer.h>

// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
//#define TEST_PRINT
// STATIC VARIABLE INITIALIZATIONS

/* //////////////////////////// PUBLIC //////////////////////////////////// */

/* ============================ CREATORS ================================== */

// Constructor
SipTlsServer::SipTlsServer(int port,
                           SipUserAgent* userAgent,
                           UtlBoolean bUseNextAvailablePort,
                           UtlString certNickname,
                           UtlString certPassword,
                           UtlString dbLocation,
                           const char*  szBindAddr) :
 SipProtocolServerBase(userAgent, "TLS", "SipTlsServer %d"),
 mCertNickname(certNickname),
 mCertPassword(certPassword),
 mDbLocation(dbLocation),
 mTlsInitCode(OS_SUCCESS)
{
    OsSysLog::add(FAC_SIP, PRI_DEBUG,
                  "SipTlsServer::_ port = %d, bUseNextAvailablePort = %d",
                  port, bUseNextAvailablePort);

    mServerPort = port ;
    mpServerBrokerListener = new SipServerBrokerListener(this);

#ifdef _DISABLE_MULTIPLE_INTERFACE_SUPPORT
   szBindAddr = "0.0.0.0" ;
#endif

    OsSysLog::add(FAC_SIP,PRI_DEBUG,"SipTlsServer::~ port %d", port);

    if (szBindAddr && 0 != strcmp(szBindAddr, "0.0.0.0"))
    {
        mDefaultIp = szBindAddr;
        createServerSocket(szBindAddr, mServerPort, bUseNextAvailablePort);
    }
    else
    {
        int numAddresses = MAX_IP_ADDRESSES;
        const HostAdapterAddress* adapterAddresses[MAX_IP_ADDRESSES];
        getAllLocalHostIps(adapterAddresses, numAddresses);

        for (int i = 0; i < numAddresses; i++)
        {
            createServerSocket(adapterAddresses[i]->mAddress.data(),
                               mServerPort,
                               bUseNextAvailablePort);
            if (0 == i)
            {
                // use the first IP address in the array
                // for the 'default ip'
                mDefaultIp = adapterAddresses[i]->mAddress.data();
            }
            delete adapterAddresses[i];
        }
    }

   mDefaultPort = SIP_TLS_PORT;
}

UtlBoolean SipTlsServer::startListener()
{
    UtlBoolean bRet(FALSE);
#       ifdef TEST_PRINT
        osPrintf("SIP Server binding to port %d\n", serverPort);
#       endif

    // iterate over the SipServerBroker map and call start
    UtlHashMapIterator iterator(mServerBrokers);
    UtlVoidPtr* pBrokerContainer = NULL;
    SipServerBroker* pBroker = NULL;
    UtlString* pKey = NULL;

    while(pKey = (UtlString*)iterator())
    {
        pBrokerContainer = (UtlVoidPtr*) iterator.value();
        if (pBrokerContainer)
        {
            pBroker = (SipServerBroker*)pBrokerContainer->getValue();
            if (pBroker)
            {
                pBroker->start();
                bRet = TRUE;
            }
        }
    }
    return bRet;
}

OsStatus SipTlsServer::createServerSocket(const char* szBindAddr,
                                int& port,
                                const UtlBoolean& bUseNextAvailablePort)
{
    OsStatus rc = OS_FAILED;

    if(portIsValid(port))
    {
#ifdef HAVE_SSL
        OsServerSocket* pServerSocket = new OsSSLServerSocket(64, port);
#else
        OsServerSocket* pServerSocket = new OsServerSocket(64, port);
#endif

        // If the socket is busy or unbindable and the user requested using the
        // next available port, try the next SIP_MAX_PORT_RANGE ports.
        if (bUseNextAvailablePort && !pServerSocket->isOk())
        {
            for (int i=1; i<=SIP_MAX_PORT_RANGE; i++)
            {
                delete pServerSocket ;
#ifdef HAVE_SSL
                pServerSocket = new OsSSLServerSocket(64, port+i);
#else
                pServerSocket = new OsServerSocket(64, port+i);
#endif
                if (pServerSocket->isOk())
                {
                    break ;
                }
            }
        }

        if (pServerSocket && pServerSocket->isOk())
        {
            mServerPort = pServerSocket->getLocalHostPort() ;

            port = pServerSocket->getLocalHostPort();
            SIPX_CONTACT_ADDRESS contact;
            strcpy(contact.cIpAddress, szBindAddr);
            contact.iPort = port;
            contact.eContactType = CONTACT_LOCAL;
            UtlString szAdapterName;
            memset((void*)szAdapterName.data(), 0, sizeof(szAdapterName)); // null out the string

            getContactAdapterName(szAdapterName, contact.cIpAddress);
            SAFE_STRNCPY(contact.cInterface, szAdapterName.data(), sizeof(contact.cInterface));
            contact.eTransportType = TRANSPORT_TLS;
            mSipUserAgent->addContactAddress(contact);

            // add address and port to the maps
            mServerSocketMap.insertKeyAndValue(new UtlString(szBindAddr),
                                               new UtlVoidPtr((void*)pServerSocket));
            mServerPortMap.insertKeyAndValue(new UtlString(szBindAddr),
                                                   new UtlInt(pServerSocket->getLocalHostPort()));
            mServerBrokers.insertKeyAndValue(new UtlString(szBindAddr),
                                              new UtlVoidPtr(new SipServerBroker((OsServerTask*)mpServerBrokerListener,
                                                                                pServerSocket)));

            rc = OS_SUCCESS;
        }
    }
    return rc;
}

void SipTlsServer::shutdownListener()
{
    requestShutdown();
    shutdownClients();
}

int SipTlsServer::run(void* runArgument)
{

    while (!isShuttingDown())
    {
        OsTask::delay(500); // this method really shouldn't do anything
    }

    return(0);
}
// Destructor
SipTlsServer::~SipTlsServer()
{
    waitUntilShutDown();
    if (mpServerBrokerListener)
    {
        mpServerBrokerListener->requestShutdown();
        delete mpServerBrokerListener;
    }
    {
        SipServerBroker* pBroker = NULL;
        UtlHashMapIterator iterator(this->mServerBrokers);
        UtlVoidPtr* pBrokerContainer = NULL;
        UtlString* pKey = NULL;

        while (pKey = (UtlString*)iterator())
        {
            pBrokerContainer = (UtlVoidPtr*)iterator.value();
            if (pBrokerContainer)
            {
                pBroker = (SipServerBroker*)pBrokerContainer->getValue();
                if (pBroker)
                {
                    pBroker->requestShutdown();
                    delete pBroker;
                }
            }
        }
        mServerBrokers.destroyAll();
    }

/*
    {
        OsSocket* pSocket = NULL;
        UtlHashMapIterator iterator(mServerSocketMap);
        UtlVoidPtr* pSocketContainer = NULL;
        UtlString* pKey = NULL;

        while (pKey = (UtlString*)iterator())
        {
            pSocketContainer = (UtlVoidPtr*)iterator.value();
            if (pSocketContainer)
            {
                pSocket = (OsSocket*)pSocketContainer->getValue();
                if (pSocket)
                {
                    delete pSocket;
                }
            }
        }
        mServerSocketMap.destroyAll();
    }
*/
    mServerSocketMap.destroyAll();
    mServerPortMap.destroyAll();

}

/* ============================ MANIPULATORS ============================== */

OsSocket* SipTlsServer::buildClientSocket(int hostPort, const char* hostAddress, const char* localIp)
{
    OsSocket* socket = NULL;
#ifdef HAVE_SSL
    socket = new OsSSLConnectionSocket(hostPort, hostAddress);
#else
    // Create the socket in non-blocking mode so it does not block
    // while conecting
    socket = new OsConnectionSocket(hostPort, hostAddress, FALSE, localIp);
#endif
   if (socket)
   {
      socket->makeBlocking();
   }
   return(socket);
}

/* ============================ ACCESSORS ================================= */

// The the local server port for this server
int SipTlsServer::getServerPort() const
{
    return mServerPort ;
}

/* ============================ INQUIRY =================================== */

/* //////////////////////////// PROTECTED ///////////////////////////////// */

/* //////////////////////////// PRIVATE /////////////////////////////////// */

/* ============================ FUNCTIONS ================================= */

#endif
<commit_msg>Fixed memory overwrite bug in SipTlsServer. UtlString.data() should never be zeroed manually, we never know how long the buffer is. Also after delete set variable to NULL.<commit_after>//
// Copyright (C) 2004-2006 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp.  All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////

#ifdef HAVE_SSL

// SYSTEM INCLUDES
#include <assert.h>

// APPLICATION INCLUDES

#include <os/OsDateTime.h>
#include <os/HostAdapterAddress.h>
#include <utl/UtlHashMapIterator.h>

#include <tapi/sipxtapi.h>
#include <os/OsSSLServerSocket.h>
#include <os/OsSSLConnectionSocket.h>

#include <net/SipServerBroker.h>
#include <net/SipTcpServer.h>
#include <net/SipUserAgent.h>
#include <net/SipTlsServer.h>

// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
//#define TEST_PRINT
// STATIC VARIABLE INITIALIZATIONS

/* //////////////////////////// PUBLIC //////////////////////////////////// */

/* ============================ CREATORS ================================== */

// Constructor
SipTlsServer::SipTlsServer(int port,
                           SipUserAgent* userAgent,
                           UtlBoolean bUseNextAvailablePort,
                           UtlString certNickname,
                           UtlString certPassword,
                           UtlString dbLocation,
                           const char*  szBindAddr) :
 SipProtocolServerBase(userAgent, "TLS", "SipTlsServer %d"),
 mCertNickname(certNickname),
 mCertPassword(certPassword),
 mDbLocation(dbLocation),
 mTlsInitCode(OS_SUCCESS)
{
    OsSysLog::add(FAC_SIP, PRI_DEBUG,
                  "SipTlsServer::_ port = %d, bUseNextAvailablePort = %d",
                  port, bUseNextAvailablePort);

    mServerPort = port ;
    mpServerBrokerListener = new SipServerBrokerListener(this);

#ifdef _DISABLE_MULTIPLE_INTERFACE_SUPPORT
   szBindAddr = "0.0.0.0" ;
#endif

    OsSysLog::add(FAC_SIP,PRI_DEBUG,"SipTlsServer::~ port %d", port);

    if (szBindAddr && 0 != strcmp(szBindAddr, "0.0.0.0"))
    {
        mDefaultIp = szBindAddr;
        createServerSocket(szBindAddr, mServerPort, bUseNextAvailablePort);
    }
    else
    {
        int numAddresses = MAX_IP_ADDRESSES;
        const HostAdapterAddress* adapterAddresses[MAX_IP_ADDRESSES];
        getAllLocalHostIps(adapterAddresses, numAddresses);

        for (int i = 0; i < numAddresses; i++)
        {
            createServerSocket(adapterAddresses[i]->mAddress.data(),
                               mServerPort,
                               bUseNextAvailablePort);
            if (0 == i)
            {
                // use the first IP address in the array
                // for the 'default ip'
                mDefaultIp = adapterAddresses[i]->mAddress.data();
            }
            delete adapterAddresses[i];
            adapterAddresses[i] = NULL;
        }
    }

   mDefaultPort = SIP_TLS_PORT;
}

UtlBoolean SipTlsServer::startListener()
{
    UtlBoolean bRet(FALSE);
#       ifdef TEST_PRINT
        osPrintf("SIP Server binding to port %d\n", serverPort);
#       endif

    // iterate over the SipServerBroker map and call start
    UtlHashMapIterator iterator(mServerBrokers);
    UtlVoidPtr* pBrokerContainer = NULL;
    SipServerBroker* pBroker = NULL;
    UtlString* pKey = NULL;

    while(pKey = (UtlString*)iterator())
    {
        pBrokerContainer = (UtlVoidPtr*) iterator.value();
        if (pBrokerContainer)
        {
            pBroker = (SipServerBroker*)pBrokerContainer->getValue();
            if (pBroker)
            {
                pBroker->start();
                bRet = TRUE;
            }
        }
    }
    return bRet;
}

OsStatus SipTlsServer::createServerSocket(const char* szBindAddr,
                                int& port,
                                const UtlBoolean& bUseNextAvailablePort)
{
    OsStatus rc = OS_FAILED;

    if(portIsValid(port))
    {
#ifdef HAVE_SSL
        OsServerSocket* pServerSocket = new OsSSLServerSocket(64, port);
#else
        OsServerSocket* pServerSocket = new OsServerSocket(64, port);
#endif

        // If the socket is busy or unbindable and the user requested using the
        // next available port, try the next SIP_MAX_PORT_RANGE ports.
        if (bUseNextAvailablePort && !pServerSocket->isOk())
        {
            for (int i=1; i<=SIP_MAX_PORT_RANGE; i++)
            {
                delete pServerSocket ;
#ifdef HAVE_SSL
                pServerSocket = new OsSSLServerSocket(64, port+i);
#else
                pServerSocket = new OsServerSocket(64, port+i);
#endif
                if (pServerSocket->isOk())
                {
                    break ;
                }
            }
        }

        if (pServerSocket && pServerSocket->isOk())
        {
            mServerPort = pServerSocket->getLocalHostPort() ;

            port = pServerSocket->getLocalHostPort();
            SIPX_CONTACT_ADDRESS contact;
            strcpy(contact.cIpAddress, szBindAddr);
            contact.iPort = port;
            contact.eContactType = CONTACT_LOCAL;
            UtlString szAdapterName;

            getContactAdapterName(szAdapterName, contact.cIpAddress);
            SAFE_STRNCPY(contact.cInterface, szAdapterName.data(), sizeof(contact.cInterface));
            contact.eTransportType = TRANSPORT_TLS;
            mSipUserAgent->addContactAddress(contact);

            // add address and port to the maps
            mServerSocketMap.insertKeyAndValue(new UtlString(szBindAddr),
                                               new UtlVoidPtr((void*)pServerSocket));
            mServerPortMap.insertKeyAndValue(new UtlString(szBindAddr),
                                                   new UtlInt(pServerSocket->getLocalHostPort()));
            mServerBrokers.insertKeyAndValue(new UtlString(szBindAddr),
                                              new UtlVoidPtr(new SipServerBroker((OsServerTask*)mpServerBrokerListener,
                                                                                pServerSocket)));

            rc = OS_SUCCESS;
        }
    }
    return rc;
}

void SipTlsServer::shutdownListener()
{
    requestShutdown();
    shutdownClients();
}

int SipTlsServer::run(void* runArgument)
{

    while (!isShuttingDown())
    {
        OsTask::delay(500); // this method really shouldn't do anything
    }

    return(0);
}
// Destructor
SipTlsServer::~SipTlsServer()
{
    waitUntilShutDown();
    if (mpServerBrokerListener)
    {
        mpServerBrokerListener->requestShutdown();
        delete mpServerBrokerListener;
    }
    {
        SipServerBroker* pBroker = NULL;
        UtlHashMapIterator iterator(this->mServerBrokers);
        UtlVoidPtr* pBrokerContainer = NULL;
        UtlString* pKey = NULL;

        while (pKey = (UtlString*)iterator())
        {
            pBrokerContainer = (UtlVoidPtr*)iterator.value();
            if (pBrokerContainer)
            {
                pBroker = (SipServerBroker*)pBrokerContainer->getValue();
                if (pBroker)
                {
                    pBroker->requestShutdown();
                    delete pBroker;
                }
            }
        }
        mServerBrokers.destroyAll();
    }

/*
    {
        OsSocket* pSocket = NULL;
        UtlHashMapIterator iterator(mServerSocketMap);
        UtlVoidPtr* pSocketContainer = NULL;
        UtlString* pKey = NULL;

        while (pKey = (UtlString*)iterator())
        {
            pSocketContainer = (UtlVoidPtr*)iterator.value();
            if (pSocketContainer)
            {
                pSocket = (OsSocket*)pSocketContainer->getValue();
                if (pSocket)
                {
                    delete pSocket;
                }
            }
        }
        mServerSocketMap.destroyAll();
    }
*/
    mServerSocketMap.destroyAll();
    mServerPortMap.destroyAll();

}

/* ============================ MANIPULATORS ============================== */

OsSocket* SipTlsServer::buildClientSocket(int hostPort, const char* hostAddress, const char* localIp)
{
    OsSocket* socket = NULL;
#ifdef HAVE_SSL
    socket = new OsSSLConnectionSocket(hostPort, hostAddress);
#else
    // Create the socket in non-blocking mode so it does not block
    // while conecting
    socket = new OsConnectionSocket(hostPort, hostAddress, FALSE, localIp);
#endif
   if (socket)
   {
      socket->makeBlocking();
   }
   return(socket);
}

/* ============================ ACCESSORS ================================= */

// The the local server port for this server
int SipTlsServer::getServerPort() const
{
    return mServerPort ;
}

/* ============================ INQUIRY =================================== */

/* //////////////////////////// PROTECTED ///////////////////////////////// */

/* //////////////////////////// PRIVATE /////////////////////////////////// */

/* ============================ FUNCTIONS ================================= */

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <functional>

using namespace std;

namespace {
ofstream outfile;
ifstream infile;

class Token {
public:
  explicit Token() {
    infile >> value;
    if (!infile) {
      infile.close();
      outfile.close();
      exit(0);
    }
  }

  string const& as_str() {
    return value;
  }

  bool make_nn(string const& name, char& nn) {
    int target = xtoi(value);
    if (0 > target || 0xFF < target) {
      cerr << "Error: " << name << " needs to be supplied with a value [0-FF]\n";
      return false;
    }
    nn = target;
    return true;
  }

  bool make_nnn(string const& name, char& lhs, char& rhs) {
    int target = xtoi(value);
    if (0 > target || 0xFFF < target) {
      cerr << "Error: " << name << " needs to be supplied with a value [0-FFF]\n";
      return false;
    }
    lhs = target >> 8;
    rhs = target & 0xFF;
    return true;
  }

  bool make_reg(string const& name, char& reg) {
    if (value.at(0) != 'r') {
      cerr << "Error: " << name << " needs to be supplied with a register r[0-F]\n";
      reg = -1;
      return false;
    }

    int target = xtoi(value.substr(1));
    if (0 > target || 0xF < target) {
      cerr << "Error: " << name << " needs to be supplied with a register r[0-F]\n";
      return false;
    }
    reg = target;
    return true;
  }

private:
  int xtoi(string const& x) {
    try {
      return stoi(x, 0, 16);
    } catch (exception &e) {
      return -1;
    }
  }

  string value;
};

bool write_bins(char lhs, char rhs) {
  outfile.write(static_cast<char*>(&lhs), 1);
  outfile.write(static_cast<char*>(&rhs), 1);
  return !outfile.fail();
}

bool cls() { return write_bins(0x00, 0xE0); }
bool ret() { return write_bins(0x00, 0xEE); }
bool jmp() {
  char lhs, rhs;
  return Token().make_nnn("JMP", lhs, rhs) &&
         write_bins(0x10 + lhs, rhs);
}
bool call() {
  char lhs, rhs;
  return Token().make_nnn("CALL", lhs, rhs) &&
         write_bins(0x20 + lhs, rhs);
}
bool ifn() {
  char xreg, nn;
  return Token().make_reg("IFN", xreg) &&
         Token().make_nn("IFN", nn) &&
         write_bins(0x30 + xreg, nn);
}
bool if_() {
  char xreg, nn;
  return Token().make_reg("IF", xreg) &&
         Token().make_nn("IF", nn) &&
         write_bins(0x40 + xreg, nn);
}

int help(string program_name) {
  cerr
    << "Usage: " << program_name << " FILE\n\n"
    << "Available commands\n"
    << "CLS        - 0x00E0\n"
    << "RET        - 0x00EE\n"
    << "JMP NNN    - 0x1NNN\n"
    << "CALL NNN   - 0x2NNN\n"
    << "IFN rX NN  - 0x3XNN\n"
    << "IF rX NN   - 0x4XNN\n"
    << "IFN rX rY  - 0x5XY0\n";

  return 1;
}

} // anonymous namespace

int main(int argc, char* argv[]) {
  if (argc != 2 || !strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) {
    return help(argv[0]);
  }

  infile = ifstream(argv[1], ios::binary);
  if (!infile) {
    cerr << argv[0] << ": Unable to open " << argv[1] << "\n";
    return 1;
  }

  stringstream ss;
  ss << argv[1] << ".out";
  string const outfile_name{ss.str()};
  outfile = ofstream(outfile_name, ios::binary);
  if (!outfile) {
    cerr << argv[0] << ": Unable to open " << outfile_name << "\n";
    return 1;
  }

  map<string const, function<bool()>> const op2fun {
    {"CLS",  cls},
    {"RET",  ret},
    {"JMP",  jmp},
    {"CALL", call},
    {"IFN",  ifn},
    {"IF",   if_},
  };

  for (;;) {
    // This constructor will exit when no more input is received
    Token tok;

    auto const fun{op2fun.find(tok.as_str())};
    if (fun == op2fun.end()) {
      cerr << "Unknown command '" << tok.as_str() << "'\n";
      return 1;
    }

    if (!fun->second()) {
      return 1;
    }
  }

  // Not reached
}
<commit_msg>rewrite and add 0x5XY0<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <functional>

using namespace std;

namespace {
ofstream outfile;
ifstream infile;

void exit_ok() {
  infile.close();
  outfile.close();
  exit(0);
}

void exit_err(string const& error) {
  cerr << error;
  infile.close();
  outfile.close();
  exit(1);
}

class Token {
public:
  explicit Token() {
    infile >> value;
    if (!infile) {
      exit_ok();
    }
  }

  enum type {
    REG,
    NN
  };

  string const& as_str() {
    return value;
  }

  void make_nn(string const& name, char& nn) {
    int target = xtoi(value);
    if (0 > target || 0xFF < target) {
      exit_err("Error: " + name + " needs to be supplied with a value [0-FF]\n");
    }
    nn = target;
  }

  void make_nnn(string const& name, char& lhs, char& rhs) {
    int target = xtoi(value);
    if (0 > target || 0xFFF < target) {
      exit_err("Error: " + name + " needs to be supplied with a value [0-FFF]\n");
    }
    lhs = target >> 8;
    rhs = target & 0xFF;
  }

  void make_reg(string const& name, char& reg) {
    if (value.at(0) != 'r') {
      exit_err("Error: " + name + " needs to be supplied with a register r[0-F]\n");
    }

    int target = xtoi(value.substr(1));
    if (0 > target || 0xF < target) {
      exit_err("Error: " + name + " needs to be supplied with a register r[0-F]\n");
    }
    reg = target;
  }

  void make_reg_or_nn(string const& name, char& reg_or_nn, type& t) {
    if (value.at(0) == 'r') {
      t = REG;
      make_reg(name, reg_or_nn);
    } else {
      t = NN;
      make_nn(name, reg_or_nn);
    }
  }

private:
  int xtoi(string const& x) {
    try {
      return stoi(x, 0, 16);
    } catch (exception &e) {
      return -1;
    }
  }

  string value;
};

void write_bins(char lhs, char rhs) {
  outfile.write(static_cast<char*>(&lhs), 1);
  outfile.write(static_cast<char*>(&rhs), 1);
  if (outfile.fail()) {
    exit_err("Error writing to disk");
  }
}

void cls() { write_bins(0x00, 0xE0); }
void ret() { write_bins(0x00, 0xEE); }
void jmp() {
  char lhs, rhs;
  Token().make_nnn("JMP", lhs, rhs);
  write_bins(0x10 + lhs, rhs);
}
void call() {
  char lhs, rhs;
  Token().make_nnn("CALL", lhs, rhs);
  write_bins(0x20 + lhs, rhs);
}
void ifn() {
  char xreg, nn;
  Token::type t;
  Token().make_reg("IFN", xreg);
  Token().make_reg_or_nn("IFN", nn, t);
  if (t == Token::NN) {
    write_bins(0x30 + xreg, nn);
  } else if (t == Token::REG) {
    write_bins(0x50 + xreg, nn << 4);
  } else {
    exit_err("IFN: Unknown type\n");
  }
}
void if_() {
  char xreg, nn;
  Token().make_reg("IF", xreg);
  Token().make_nn("IF", nn);
  write_bins(0x40 + xreg, nn);
}

int help(string program_name) {
  cerr
    << "Usage: " << program_name << " FILE\n\n"
    << "Available commands\n"
    << "CLS        - 0x00E0\n"
    << "RET        - 0x00EE\n"
    << "JMP NNN    - 0x1NNN\n"
    << "CALL NNN   - 0x2NNN\n"
    << "IFN rX NN  - 0x3XNN\n"
    << "IF rX NN   - 0x4XNN\n"
    << "IFN rX rY  - 0x5XY0\n";

  return 1;
}

} // anonymous namespace

int main(int argc, char* argv[]) {
  if (argc != 2 || !strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) {
    return help(argv[0]);
  }

  infile = ifstream(argv[1], ios::binary);
  if (!infile) {
    cerr << argv[0] << ": Unable to open " << argv[1] << "\n";
    return 1;
  }

  stringstream ss;
  ss << argv[1] << ".out";
  string const outfile_name{ss.str()};
  outfile = ofstream(outfile_name, ios::binary);
  if (!outfile) {
    cerr << argv[0] << ": Unable to open " << outfile_name << "\n";
    return 1;
  }

  map<string const, function<void()>> const op2fun {
    {"CLS",  cls},
    {"RET",  ret},
    {"JMP",  jmp},
    {"CALL", call},
    {"IFN",  ifn},
    {"IF",   if_},
  };

  for (;;) {
    // This constructor will exit when no more input is received
    Token tok;

    auto const fun{op2fun.find(tok.as_str())};
    if (fun == op2fun.end()) {
      exit_err("Unknown command '" + tok.as_str() + "'\n");
    }

    fun->second();
  }

  // Not reached
}
<|endoftext|>


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

#ifndef _RSCERROR_H
#include <rscerror.h>
#endif
#ifndef _RSCTOOLS_HXX
#include <rsctools.hxx>
#endif
#ifndef _RSCHASH_HXX
#include <rschash.hxx>
#endif
#ifndef _RSCCLOBJ_HXX
#include <rscclobj.hxx>
#endif

/****************** T Y P E S ********************************************/
typedef short RSCVAR;
#define VAR_POINTER     0x0001
#define VAR_HIDDEN      0x0002
#define VAR_NODATAINST  0x0004
#define VAR_NORC        0x0008
#define VAR_SVDYNAMIC   0x0010
#define VAR_NOENUM      0x0020
#define VAR_EXTENDABLE  0x0040  /* Auch die Ableitung einer Klasse kann angegeben werden */

/****************** C L A S S E S ****************************************/
/******************* R s c C l a s s *************************************/
class RscTop : public RefNode
{
    RscTop *        pSuperClass;
    RSCINST         aDfltInst;
    USHORT          nTypId;
    RscTop *        pRefClass;

protected:
                    RscTop( HASHID nId, USHORT nTypIdent,
                            RscTop * pSuperCl = NULL );

public:
    ByteString      aCallPar1;      // Klassenaufruf ohne Typen bis ResId
    ByteString      aCallPar2;      // Klassenaufruf ohne Typen ab ResId
    ByteString      aCallParType;   // Klassenaufruf mit Typen

            void    SetSuperClass( RscTop * pClass )
                    {
                        pSuperClass = pClass;
                    }
            RscTop* GetSuperClass() const
                    { return pSuperClass; }
                    // Gibt den Typidentifier zurueck
            USHORT  GetTypId() const
                    { return nTypId; };
                    // Gibt die Oberklasse zurueck
            BOOL    InHierarchy( RscTop * pClass );
            BOOL    IsCodeWriteable() const
                    {
                        return( 0 != aCallParType.Len() );
                    }
            void    SetCallPar( const ByteString & rPar1, const ByteString & rPar2,
                                const ByteString & rParType );
            void    SetRefClass( RscTop * pRef ) { pRefClass = pRef; }
            RscTop* GetRefClass() const { return pRefClass; }
    virtual RSCCLASS_TYPE GetClassType() const = 0;
            RSCINST GetDefault();

                    // Vorbereitung auf den dtor aufruf
                    // Da die Klassen gegenseitige Abhaengigkeiten
                    // aufweisen koennen, kann man im dtor nicht davon
                    // ausgehen, dass alle Klassenzeiger noch gueltig sind
    virtual void    Pre_dtor();

    virtual HASHID  GetConstant( USHORT );

    virtual RscTop *    GetTypeClass() const;

                    // Gibt die Groesse der Klasse in Bytes
    virtual USHORT  Size();

                    // Gibt die Referenz zurueck
    virtual ERRTYPE GetRef( const RSCINST & rInst, RscId * );

                    // Gibt die Referenz zurueck
    virtual ERRTYPE SetRef( const RSCINST & rInst, const RscId & rRefId );

                    // Variable anlegen
    virtual ERRTYPE SetVariable( HASHID nVarName, RscTop * pClass,
                                 RSCINST * pDflt = NULL,
                                 RSCVAR nVarType = 0, USHORT nMask = 0,
                                 HASHID nDataBaseName = HASH_NONAME );

                    // Zaehlt alle Variablen auf
    virtual void    EnumVariables( void * pData, VarEnumCallbackProc );

                    // Liefert Instanz der Variablen zurueck
                    // pData, pClass im return koennen NULL sein
    virtual RSCINST GetVariable( const RSCINST & rInst, HASHID nVarName,
                                 const RSCINST & rInitInst,
                                 BOOL nInitDflt = FALSE,
                                 RscTop * pCreateClass = NULL );
    virtual RSCINST GetCopyVar( const RSCINST & rInst, HASHID nVarName );

    virtual RSCINST GetTupelVar( const RSCINST & rInst, USHORT nPos,
                                 const RSCINST & rInitInst );

                    // Liefert Instanz aus einem Feld zurueck
                    // pGetInst im return kann NULL sein
    virtual ERRTYPE GetElement( const RSCINST & rInst, const RscId & rEleName,
                                RscTop *pCreateClass, const RSCINST & rCreateInst,
                                RSCINST * pGetInst );

                    // Liefert Instanz aus einem Feld zurueck
                    // pGetInst im return kann NULL sein
    virtual ERRTYPE GetValueEle( const RSCINST & rInst, INT32 lValue,
                                RscTop * pCreateClass,
                                RSCINST * pGetInst );

                    // Liefert Instanz aus einem Feld zurueck
                    // pGetInst im return kann NULL sein
    virtual ERRTYPE GetArrayEle( const RSCINST & rInst, HASHID nId,
                                RscTop * pCreateClass,
                                RSCINST * pGetInst );

    virtual RSCINST SearchEle( const RSCINST & rInst, const RscId & rEleName,
                               RscTop * pClass );

                    // Liefert Instanz an der Position zurueck
    virtual RSCINST GetPosEle( const RSCINST & rInst, USHORT nPos );

                    // verschiebt eine Instanz
    virtual ERRTYPE MovePosEle( const RSCINST & rInst, USHORT nDestPos,
                                USHORT nSourcePos );

                    // aendert RscId an Position
    virtual ERRTYPE SetPosRscId( const RSCINST & rInst, USHORT nPos,
                                 const RscId & rRscId);

                    // Liefert Information ueber Instanz
                    // an der Position zurueck
    virtual SUBINFO_STRUCT GetInfoEle( const RSCINST & rInst, USHORT nPos );

                    // Anzahl der Eintraege
    virtual USHORT GetCount( const RSCINST & rInst );

                    // Eine Zuweisung an eine Variable
    virtual ERRTYPE SetNumber( const RSCINST & rInst, INT32 lValue );

                    // Eine Zuweisung an eine Variable
    virtual ERRTYPE SetBool( const RSCINST & rInst, BOOL bValue );

                    // Eine Zuweisung an eine Variable
    virtual ERRTYPE SetConst( const RSCINST & rInst, HASHID nValueId,
                              INT32 nValue );

                    // Eine Zuweisung an eine Variable
    virtual ERRTYPE SetNotConst( const RSCINST & rInst, HASHID nId );

    virtual ERRTYPE SetString( const RSCINST & rInst, char * pStr );

    virtual ERRTYPE GetNumber( const RSCINST & rInst, INT32 * pN );

    virtual ERRTYPE GetBool( const RSCINST & rInst, BOOL * pB );

    virtual ERRTYPE GetConst( const RSCINST & rInst, HASHID * pH );

    virtual ERRTYPE GetString( const RSCINST & rInst, char ** ppStr );

    virtual RSCINST Create( RSCINST * pInst,
                            const RSCINST & rDefInst, BOOL bOwnClass = FALSE );

                    // Instanz zerstoeren
    virtual void    Destroy( const RSCINST & rInst );

                    // prueft auf konsistenz
    virtual BOOL    IsConsistent( const RSCINST & rInst,
                                  RscInconsList * pList = NULL );

                    // Alles auf Default setzen
    virtual void    SetToDefault( const RSCINST & rInst );

                    // Ist Eingabe = Default
    virtual BOOL    IsDefault( const RSCINST & rInst );

                    // Gleiche Werte auf Default setzen
    virtual BOOL    IsValueDefault( const RSCINST & rInst, CLASS_DATA pDef );

                    // Instanz auf Default setzen
    virtual void    SetDefault( const RSCINST & rInst, HASHID nVarId );

                    // Default zu einer Variablen holen
    virtual RSCINST GetDefault( HASHID nVarId );

    virtual void    Delete( const RSCINST & rInst, RscTop * pClass,
                            const RscId & rId );

    virtual void    DeletePos( const RSCINST & rInst, USHORT nPos );

                    // Schreibt den Kopf und das Ende einer Resource
                    // Script Datei
    virtual void    WriteSrcHeader( const RSCINST & rInst, FILE * fOutput,
                                    RscTypCont * pTC, USHORT nTab,
                                    const RscId & aId, const char * );
    virtual void    WriteSrc( const RSCINST & rInst, FILE * fOutput,
                              RscTypCont * pTC, USHORT nTab,const char * );
    virtual ERRTYPE WriteRcHeader( const RSCINST & rInst, RscWriteRc & aMem,
                                   RscTypCont * pTC, const RscId & aId,
                                    USHORT nDeep, BOOL bExtra );
    virtual ERRTYPE WriteRc( const RSCINST & rInst, RscWriteRc & aMem,
                             RscTypCont * pTC, USHORT nDeep, BOOL bExtra );

    // Weiterleitung an Superklassen wird unterbunden
    virtual ERRTYPE WriteHxxHeader( const RSCINST & rInst, FILE * fOutput,
                                    RscTypCont * pTC, const RscId & rId );
    virtual ERRTYPE WriteHxx( const RSCINST & rInst, FILE * fOutput,
                              RscTypCont * pTC, const RscId &rId );
    virtual ERRTYPE WriteCxxHeader( const RSCINST & rInst, FILE * fOutput,
                                    RscTypCont * pTC, const RscId &rId );
    virtual ERRTYPE WriteCxx( const RSCINST & rInst, FILE * fOutput,
                              RscTypCont * pTC, const RscId &rId );

            void WriteSyntaxHeader( FILE * fOutput, RscTypCont * pTC  );
    virtual void WriteSyntax( FILE * fOutput, RscTypCont * pTC );

    virtual void    WriteRcAccess( FILE * fOutput, RscTypCont * pTC,
                                    const char * );
    virtual void    WriteRcCtor( FILE * fOutput, RscTypCont * pTC );
};

#endif //_RSCTOP_HXX
<commit_msg>INTEGRATION: CWS res32bit (1.3.18); FILE MERGED 2004/10/27 17:50:54 pl 1.3.18.2: minor updates 2004/10/22 13:54:29 pl 1.3.18.1: #i34513# free rsc of 32 bit constraints<commit_after>/*************************************************************************
 *
 *  $RCSfile: rsctop.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2005-01-03 17:23:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _RSCTOP_HXX
#define _RSCTOP_HXX

#ifndef _RSCERROR_H
#include <rscerror.h>
#endif
#ifndef _RSCTOOLS_HXX
#include <rsctools.hxx>
#endif
#ifndef _RSCHASH_HXX
#include <rschash.hxx>
#endif
#ifndef _RSCCLOBJ_HXX
#include <rscclobj.hxx>
#endif

/****************** T Y P E S ********************************************/
typedef sal_uInt32 RSCVAR;
#define VAR_POINTER     0x0001
#define VAR_HIDDEN      0x0002
#define VAR_NODATAINST  0x0004
#define VAR_NORC        0x0008
#define VAR_SVDYNAMIC   0x0010
#define VAR_NOENUM      0x0020
#define VAR_EXTENDABLE  0x0040  /* Auch die Ableitung einer Klasse kann angegeben werden */

/****************** C L A S S E S ****************************************/
/******************* R s c C l a s s *************************************/
class RscTop : public RefNode
{
    RscTop *        pSuperClass;
    RSCINST         aDfltInst;
    sal_uInt32          nTypId;
    RscTop *        pRefClass;

protected:
                    RscTop( Atom nId, sal_uInt32 nTypIdent,
                            RscTop * pSuperCl = NULL );

public:
    ByteString      aCallPar1;      // Klassenaufruf ohne Typen bis ResId
    ByteString      aCallPar2;      // Klassenaufruf ohne Typen ab ResId
    ByteString      aCallParType;   // Klassenaufruf mit Typen

            void    SetSuperClass( RscTop * pClass )
                    {
                        pSuperClass = pClass;
                    }
            RscTop* GetSuperClass() const
                    { return pSuperClass; }
                    // Gibt den Typidentifier zurueck
            sal_uInt32  GetTypId() const
                    { return nTypId; };
                    // Gibt die Oberklasse zurueck
            BOOL    InHierarchy( RscTop * pClass );
            BOOL    IsCodeWriteable() const
                    {
                        return( 0 != aCallParType.Len() );
                    }
            void    SetCallPar( const ByteString & rPar1, const ByteString & rPar2,
                                const ByteString & rParType );
            void    SetRefClass( RscTop * pRef ) { pRefClass = pRef; }
            RscTop* GetRefClass() const { return pRefClass; }
    virtual RSCCLASS_TYPE GetClassType() const = 0;
            RSCINST GetDefault();

                    // Vorbereitung auf den dtor aufruf
                    // Da die Klassen gegenseitige Abhaengigkeiten
                    // aufweisen koennen, kann man im dtor nicht davon
                    // ausgehen, dass alle Klassenzeiger noch gueltig sind
    virtual void    Pre_dtor();

    virtual Atom    GetConstant( sal_uInt32 );

    virtual RscTop *    GetTypeClass() const;

                    // Gibt die Groesse der Klasse in Bytes
    virtual sal_uInt32  Size();

                    // Gibt die Referenz zurueck
    virtual ERRTYPE GetRef( const RSCINST & rInst, RscId * );

                    // Gibt die Referenz zurueck
    virtual ERRTYPE SetRef( const RSCINST & rInst, const RscId & rRefId );

                    // Variable anlegen
    virtual ERRTYPE SetVariable( Atom nVarName, RscTop * pClass,
                                 RSCINST * pDflt = NULL,
                                 RSCVAR nVarType = 0, sal_uInt32 nMask = 0,
                                 Atom nDataBaseName = InvalidAtom );

                    // Zaehlt alle Variablen auf
    virtual void    EnumVariables( void * pData, VarEnumCallbackProc );

                    // Liefert Instanz der Variablen zurueck
                    // pData, pClass im return koennen NULL sein
    virtual RSCINST GetVariable( const RSCINST & rInst, Atom nVarName,
                                 const RSCINST & rInitInst,
                                 BOOL nInitDflt = FALSE,
                                 RscTop * pCreateClass = NULL );
    virtual RSCINST GetCopyVar( const RSCINST & rInst, Atom nVarName );

    virtual RSCINST GetTupelVar( const RSCINST & rInst, sal_uInt32 nPos,
                                 const RSCINST & rInitInst );

                    // Liefert Instanz aus einem Feld zurueck
                    // pGetInst im return kann NULL sein
    virtual ERRTYPE GetElement( const RSCINST & rInst, const RscId & rEleName,
                                RscTop *pCreateClass, const RSCINST & rCreateInst,
                                RSCINST * pGetInst );

                    // Liefert Instanz aus einem Feld zurueck
                    // pGetInst im return kann NULL sein
    virtual ERRTYPE GetValueEle( const RSCINST & rInst, INT32 lValue,
                                RscTop * pCreateClass,
                                RSCINST * pGetInst );

                    // Liefert Instanz aus einem Feld zurueck
                    // pGetInst im return kann NULL sein
    virtual ERRTYPE GetArrayEle( const RSCINST & rInst, Atom nId,
                                RscTop * pCreateClass,
                                RSCINST * pGetInst );

    virtual RSCINST SearchEle( const RSCINST & rInst, const RscId & rEleName,
                               RscTop * pClass );

                    // Liefert Instanz an der Position zurueck
    virtual RSCINST GetPosEle( const RSCINST & rInst, sal_uInt32 nPos );

                    // verschiebt eine Instanz
    virtual ERRTYPE MovePosEle( const RSCINST & rInst, sal_uInt32 nDestPos,
                                sal_uInt32 nSourcePos );

                    // aendert RscId an Position
    virtual ERRTYPE SetPosRscId( const RSCINST & rInst, sal_uInt32 nPos,
                                 const RscId & rRscId);

                    // Liefert Information ueber Instanz
                    // an der Position zurueck
    virtual SUBINFO_STRUCT GetInfoEle( const RSCINST & rInst, sal_uInt32 nPos );

                    // Anzahl der Eintraege
    virtual sal_uInt32 GetCount( const RSCINST & rInst );

                    // Eine Zuweisung an eine Variable
    virtual ERRTYPE SetNumber( const RSCINST & rInst, INT32 lValue );

                    // Eine Zuweisung an eine Variable
    virtual ERRTYPE SetBool( const RSCINST & rInst, BOOL bValue );

                    // Eine Zuweisung an eine Variable
    virtual ERRTYPE SetConst( const RSCINST & rInst, Atom nValueId,
                              INT32 nValue );

                    // Eine Zuweisung an eine Variable
    virtual ERRTYPE SetNotConst( const RSCINST & rInst, Atom nId );

    virtual ERRTYPE SetString( const RSCINST & rInst, const char * pStr );

    virtual ERRTYPE GetNumber( const RSCINST & rInst, INT32 * pN );

    virtual ERRTYPE GetBool( const RSCINST & rInst, BOOL * pB );

    virtual ERRTYPE GetConst( const RSCINST & rInst, Atom * pH );

    virtual ERRTYPE GetString( const RSCINST & rInst, char ** ppStr );

    virtual RSCINST Create( RSCINST * pInst,
                            const RSCINST & rDefInst, BOOL bOwnClass = FALSE );

                    // Instanz zerstoeren
    virtual void    Destroy( const RSCINST & rInst );

                    // prueft auf konsistenz
    virtual BOOL    IsConsistent( const RSCINST & rInst,
                                  RscInconsList * pList = NULL );

                    // Alles auf Default setzen
    virtual void    SetToDefault( const RSCINST & rInst );

                    // Ist Eingabe = Default
    virtual BOOL    IsDefault( const RSCINST & rInst );

                    // Gleiche Werte auf Default setzen
    virtual BOOL    IsValueDefault( const RSCINST & rInst, CLASS_DATA pDef );

                    // Instanz auf Default setzen
    virtual void    SetDefault( const RSCINST & rInst, Atom nVarId );

                    // Default zu einer Variablen holen
    virtual RSCINST GetDefault( Atom nVarId );

    virtual void    Delete( const RSCINST & rInst, RscTop * pClass,
                            const RscId & rId );

    virtual void    DeletePos( const RSCINST & rInst, sal_uInt32 nPos );

                    // Schreibt den Kopf und das Ende einer Resource
                    // Script Datei
    virtual void    WriteSrcHeader( const RSCINST & rInst, FILE * fOutput,
                                    RscTypCont * pTC, sal_uInt32 nTab,
                                    const RscId & aId, const char * );
    virtual void    WriteSrc( const RSCINST & rInst, FILE * fOutput,
                              RscTypCont * pTC, sal_uInt32 nTab,const char * );
    virtual ERRTYPE WriteRcHeader( const RSCINST & rInst, RscWriteRc & aMem,
                                   RscTypCont * pTC, const RscId & aId,
                                    sal_uInt32 nDeep, BOOL bExtra );
    virtual ERRTYPE WriteRc( const RSCINST & rInst, RscWriteRc & aMem,
                             RscTypCont * pTC, sal_uInt32 nDeep, BOOL bExtra );

    // Weiterleitung an Superklassen wird unterbunden
    virtual ERRTYPE WriteHxxHeader( const RSCINST & rInst, FILE * fOutput,
                                    RscTypCont * pTC, const RscId & rId );
    virtual ERRTYPE WriteHxx( const RSCINST & rInst, FILE * fOutput,
                              RscTypCont * pTC, const RscId &rId );
    virtual ERRTYPE WriteCxxHeader( const RSCINST & rInst, FILE * fOutput,
                                    RscTypCont * pTC, const RscId &rId );
    virtual ERRTYPE WriteCxx( const RSCINST & rInst, FILE * fOutput,
                              RscTypCont * pTC, const RscId &rId );

            void WriteSyntaxHeader( FILE * fOutput, RscTypCont * pTC  );
    virtual void WriteSyntax( FILE * fOutput, RscTypCont * pTC );

    virtual void    WriteRcAccess( FILE * fOutput, RscTypCont * pTC,
                                    const char * );
    virtual void    WriteRcCtor( FILE * fOutput, RscTypCont * pTC );
};

#endif //_RSCTOP_HXX
<|endoftext|>


<commit_before>#ifndef V_SMC_PARTICLE_HPP
#define V_SMC_PARTICLE_HPP

#include <limits>
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <mkl_vml.h>
#include <mkl_vsl.h>
#include <gsl/gsl_rng.hp>
#include <gsl/gsl_randist.h>
#include <vDist/utilities/service.hpp>

namespace vSMC {

enum ResampleScheme {MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC};

template <class PartContainer>
class ParticleSet
{
    public :

    Particle (std::size_t N,
            void (*copy)(std::size_t, std::size_t, PartContainer &)) :
        particle_num(N), particle_set(N), weight(N), log_weight(N),
        weight_r1m(0), weight_r2m(0), replication(N), copy_particle(copy)
    {
        vsldSSNewTask(&ess_task, 1, N, VSL_SS_MATRIX_STORAGE_COLS,
                weight, NULL, NULL);
        vsldSSEditMoments(ess_task, &weight_r1m, &weight_r2m,
                NULL, NULL, NULL, NULL, NULL);
        std::time_t curr_time = std::time(NULL);
        std::size_t max_int = std::numeric_limits<int>::max();
        std::size_t rng_seed = curr_time % max_int + 1;
        rng_gsl = gsl_rng_alloc(gsl_rng_mt19937);
        gsl_rng_set(rng_gsl, rng_seed);
    }

    ~Particle ()
    {
        vslSSDeleteTask(ess_task);
        gsl_rng_free(rng_gsl);
    }

    inline double ESS ();

    inline void SetLogWeight (const double *new_weight);
    inline void AddLogWeight (const double *inc_weight);

    inline void Resample (ResampleScheme scheme);

    private :

    typedef vDist::internal::Buffer<double> dBuffer;
    typedef vDist::internal::Buffer<std::size_t> uBuffer;

    std::size_t particle_num;
    PartContainer particle_set;
    dBuffer weight;
    dBuffer log_weight;
    uBuffer replication;
    double weight_r1m;
    double weight_r2m;

    VSLSSTaskPtr ess_task;
    gsl_rng *rng_gsl;

    void (*copy_particle) (
            std::size_t n1, std::size_t n2, PartContainer &particles);

    inline void normalize_weight ();
    inline void normalize_log_weight ();

    inline void resample_multinomial ();
    inline void resample_residual ();
    inline void resample_stratified ();
    inline void resample_systematic ();
    inline void resample_do ();
};

template <class PartContainer>
double ParticleSet<PartContainer>::ESS ()
{
    vdExp(particle_num, log_weight, weight);
    vsldSSCompute(ess_task, VSL_SS_MEAN|VSL_SS_2R_MOM, VSL_SS_METHOD_TBS);

    return particle_num * weight_r1m * weight_r1m / weight_r2m;
}

template <class PartContainer>
double ParticleSet<PartContainer>::SetLogWeight (const double *new_weight)
{
    cblas_dcopy(particle_num, new_weight, 1, log_weight, 1);
    normalize_log_weight();
}

template <class PartContainer>
double ParticleSet<PartContainer>::AddLogWeight (const double *inc_weight)
{
    vdAdd(particle_num, log_weight, inc_weight, log_weight);
    normalize_log_weight();
}

template <class PartContainer>
void ParticleSet<PartContainer>::Resample (ResampleScheme scheme)
{
    switch (scheme) {
        case MULTINOMIAL :
            resample_multinomial();
            break;
        case RESIDUAL :
            resample_residual();
            break;
        case STRATIFIED :
            resample_stratified();
            break;
        case SYSTEMATIC :
            resample_systematic();
            break;
        default :
            resample_residual();
    }
}

template <class PartContainer>
void ParticleSet<PartContainer>::resample_multinomial ()
{
    resample_do();
}

template <class PartContainer>
void ParticleSet<PartContainer>::resample_residual ()
{
    resample_do();
}

template <class PartContainer>
void ParticleSet<PartContainer>::resample_stratified ()
{
    resample_do();
}

template <class PartContainer>
void ParticleSet<PartContainer>::resample_systematic ()
{
    resample_do();
}

template <class PartContainer>
void ParticleSet<PartContainer>::resample_do ()
{
    std::size_t from = 0;
    std::size_t time = 0;

    for (std::size_t i = 0; i != particle_num; ++i)
    {
        if (!replication[i]) { // replication[i] has zero child
            if (time == replication[from]) {
                // all childs of replication[from] are already copied
                time = 0;
                ++from;
                while (!replication[from])
                    ++from;
            }
            (*copy_particle)(from, i, partile_set);
            ++time;
        }
    }
}

} // namespace vSMC

#endif // V_SMC_PARTICLE_HPP
<commit_msg>remove normalize_weight<commit_after>#ifndef V_SMC_PARTICLE_HPP
#define V_SMC_PARTICLE_HPP

#include <limits>
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <mkl_vml.h>
#include <mkl_vsl.h>
#include <gsl/gsl_rng.hp>
#include <gsl/gsl_randist.h>
#include <vDist/utilities/service.hpp>

namespace vSMC {

enum ResampleScheme {MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC};

template <class PartContainer>
class ParticleSet
{
    public :

    Particle (std::size_t N,
            void (*copy)(std::size_t, std::size_t, PartContainer &)) :
        particle_num(N), particle_set(N), weight(N), log_weight(N),
        weight_r1m(0), weight_r2m(0), replication(N), copy_particle(copy)
    {
        vsldSSNewTask(&ess_task, 1, N, VSL_SS_MATRIX_STORAGE_COLS,
                weight, NULL, NULL);
        vsldSSEditMoments(ess_task, &weight_r1m, &weight_r2m,
                NULL, NULL, NULL, NULL, NULL);
        std::time_t curr_time = std::time(NULL);
        std::size_t max_int = std::numeric_limits<int>::max();
        std::size_t rng_seed = curr_time % max_int + 1;
        rng_gsl = gsl_rng_alloc(gsl_rng_mt19937);
        gsl_rng_set(rng_gsl, rng_seed);
    }

    ~Particle ()
    {
        vslSSDeleteTask(ess_task);
        gsl_rng_free(rng_gsl);
    }

    inline double ESS ();

    inline void SetLogWeight (const double *new_weight);
    inline void AddLogWeight (const double *inc_weight);

    inline void Resample (ResampleScheme scheme);

    private :

    typedef vDist::internal::Buffer<double> dBuffer;
    typedef vDist::internal::Buffer<std::size_t> uBuffer;

    std::size_t particle_num;
    PartContainer particle_set;
    dBuffer weight;
    dBuffer log_weight;
    uBuffer replication;
    double weight_r1m;
    double weight_r2m;

    VSLSSTaskPtr ess_task;
    gsl_rng *rng_gsl;

    void (*copy_particle) (
            std::size_t n1, std::size_t n2, PartContainer &particles);

    inline void normalize_log_weight ();

    inline void resample_multinomial ();
    inline void resample_residual ();
    inline void resample_stratified ();
    inline void resample_systematic ();
    inline void resample_do ();
};

template <class PartContainer>
double ParticleSet<PartContainer>::ESS ()
{
    vdExp(particle_num, log_weight, weight);
    vsldSSCompute(ess_task, VSL_SS_MEAN|VSL_SS_2R_MOM, VSL_SS_METHOD_TBS);

    return particle_num * weight_r1m * weight_r1m / weight_r2m;
}

template <class PartContainer>
double ParticleSet<PartContainer>::SetLogWeight (const double *new_weight)
{
    cblas_dcopy(particle_num, new_weight, 1, log_weight, 1);
    normalize_log_weight();
}

template <class PartContainer>
double ParticleSet<PartContainer>::AddLogWeight (const double *inc_weight)
{
    vdAdd(particle_num, log_weight, inc_weight, log_weight);
    normalize_log_weight();
}

template <class PartContainer>
double ParticleSet<PartContainer>::normalize_log_weight ()
{
}

template <class PartContainer>
void ParticleSet<PartContainer>::Resample (ResampleScheme scheme)
{
    switch (scheme) {
        case MULTINOMIAL :
            resample_multinomial();
            break;
        case RESIDUAL :
            resample_residual();
            break;
        case STRATIFIED :
            resample_stratified();
            break;
        case SYSTEMATIC :
            resample_systematic();
            break;
        default :
            resample_residual();
    }
}

template <class PartContainer>
void ParticleSet<PartContainer>::resample_multinomial ()
{
    resample_do();
}

template <class PartContainer>
void ParticleSet<PartContainer>::resample_residual ()
{
    resample_do();
}

template <class PartContainer>
void ParticleSet<PartContainer>::resample_stratified ()
{
    resample_do();
}

template <class PartContainer>
void ParticleSet<PartContainer>::resample_systematic ()
{
    resample_do();
}

template <class PartContainer>
void ParticleSet<PartContainer>::resample_do ()
{
    std::size_t from = 0;
    std::size_t time = 0;

    for (std::size_t i = 0; i != particle_num; ++i)
    {
        if (!replication[i]) { // replication[i] has zero child
            if (time == replication[from]) {
                // all childs of replication[from] are already copied
                time = 0;
                ++from;
                while (!replication[from])
                    ++from;
            }
            (*copy_particle)(from, i, partile_set);
            ++time;
        }
    }
}

} // namespace vSMC

#endif // V_SMC_PARTICLE_HPP
<|endoftext|>


<commit_before>#include <RcppArmadillo.h>

#include "bootstrappers.h"
#include "gmwm_logic.h"

// Used for scales_cpp
#include "wave_variance.h"

#include "analytical_matrix_derivatives.h"

#include "model_selection.h"

#include "ts_model_cpp.h"

//#include "automatic_models.h"
using namespace Rcpp;

//[[Rcpp::export]]
std::map<int, std::vector<std::string> > master_model(){

  std::map<int, std::vector<std::string> > models;

  // 4AR1() + WN()
  models[0].push_back("AR1");
  models[0].push_back("AR1");
  models[0].push_back("AR1");
  models[0].push_back("AR1");
  models[0].push_back("WN");

  // 4AR1()
  models[1].push_back("AR1");
  models[1].push_back("AR1");
  models[1].push_back("AR1");
  models[1].push_back("AR1");

  // AR1() + WN()
  models[2].push_back("AR1");
  models[2].push_back("AR1");
  models[2].push_back("AR1");
  models[2].push_back("WN");

  // 3AR1()
  models[3].push_back("AR1");
  models[3].push_back("AR1");
  models[3].push_back("AR1");

  // 2AR1()+WN()
  models[4].push_back("AR1");
  models[4].push_back("AR1");
  models[4].push_back("WN");

  // 2AR1()
  models[5].push_back("AR1");
  models[5].push_back("AR1");

  // AR1()
  models[6].push_back("AR1");

  // WN()
  models[7].push_back("WN");

  return models;
}

// [[Rcpp::export]]
arma::mat auto_select(const arma::vec& data,
                      std::string model_type,
                      double alpha,
                      std::string compute_v, unsigned int K, unsigned int H,
                      unsigned int G,
                      bool robust, double eff, bool bs_optimism){

  // Number of data points
  unsigned int N = data.n_elem;

  // Keep track of models parsed
  unsigned int count = 0;

  // Create a map
  std::map<int, std::vector<std::string> > models = master_model();

  // Make an iterator to iterator through it
  std::map<int, std::vector<std::string> >::iterator iter;
  iter = models.begin();

  // Get the first model
  std::vector<std::string> desc = iter->second;

  // Increment iterator
  iter++;

  // Build the fields off of the first model's description
  arma::vec theta = model_theta(desc);
  arma::field<arma::vec> objdesc = model_objdesc(desc);

  // Build matrix to store results
  arma::mat results(2, models.size());

  // Obtain the largest models information
  arma::field<arma::mat> master = gmwm_master_cpp(data,
                                                theta,
                                                desc,
                                                objdesc,
                                                model_type,
                                                true, //starting
                                                alpha,
                                                "fast", // compute V
                                                K, H,
                                                G,
                                                robust, eff);

  // Theta update
  theta = master(0);

  // Define WV Empirical
  arma::vec wv_empir = master(2);

  // Get bootstrapped V
  arma::mat V = cov_bootstrapper(theta, desc, objdesc, N, robust, eff, H, false); // Bootstrapped V (largest model)

  // Get the original "FAST" matrix
  arma::mat orgV = master(6); // Original V

  // Take the inverse
  arma::mat omega = inv(orgV); // Original V => Omega

  // Get expect_diff for guesses with DR
  double expect_diff = arma::as_scalar(master(7));

  // Obtain the theoretical WV
  arma::vec theo = master(8);

  // Obtain the obj_value of the function
  double obj_value = arma::as_scalar(master(10));

  // Calculate the values of the Scales
  arma::vec scales = scales_cpp(floor(log2(N)));

  /* A note to someone in the future...
   * Yes, there is a difference in order between the diff (wv_empir-theo) for D_matrix
   *  and the model_score diff (theo-wv_empir).
   */
  if(bs_optimism){

    arma::mat cov_nu_nu_theta = optimism_bootstrapper(theta,
                                                      desc, objdesc,
                                                      scales, model_type,
                                                      N, robust, eff, alpha,
                                                      H);

    double optimism = 2*sum(diagvec(cov_nu_nu_theta * omega));

    arma::vec temp(2);
    temp(0) = obj_value + optimism;
    temp(1) = optimism;
    results.col(count) = temp;
  }else{
    // Take derivatives
    arma::mat A = derivative_first_matrix(theta, desc, objdesc, scales);

    // Create the D Matrix (note this is in the analytical_matrix_derivaties.cpp file)
    arma::mat D = D_matrix(theta, desc, objdesc, scales, omega*(wv_empir - theo));

    // Calculate the model score according to model selection criteria paper
    results.col(count) = model_score(A, D, omega, V,  obj_value);
  }

  count++;

  while(iter != models.end()){
    // Get the first model
    std::vector<std::string> desc = iter->second;

    // Build the fields off of the first model's description
    theta = model_theta(desc);
    objdesc = model_objdesc(desc);

    // Run the update version of the GMWM
    arma::field<arma::mat> update = gmwm_update_cpp(theta,
                                                      desc,
                                                      objdesc,
                                                      model_type,
                                                      N, expect_diff,
                                                      orgV, scales, wv_empir,
                                                      true, //starting
                                                      "fast",
                                                      K,
                                                      H,
                                                      G,
                                                      robust,
                                                      eff);

    // Theta update
    theta = update(0);

    // Update theo
    theo = update(3);

    // Update objective function
    obj_value = arma::as_scalar(update(5));

    /* A note to someone in the future...
     * Yes, there is a difference in order between the diff (wv_empir-theo) for D_matrix
     *  and the model_score diff (theo-wv_empir).
     */
    if(bs_optimism){

      arma::mat cov_nu_nu_theta = optimism_bootstrapper(theta,
                                                        desc, objdesc,
                                                        scales, model_type,
                                                        N, robust, eff, alpha,
                                                        H);

      double optimism = 2*sum(diagvec(cov_nu_nu_theta * omega));

      arma::vec temp(2);
      temp(0) = obj_value + optimism;
      temp(1) = optimism;
      results.col(count) = temp;
    }else{
      // Take derivatives
      arma::mat A = derivative_first_matrix(theta, desc, objdesc, scales);

      // Create the D Matrix (note this is in the analytical_matrix_derivaties.cpp file)
      arma::mat D = D_matrix(theta, desc, objdesc, scales, omega*(wv_empir - theo));

      // Calculate the model score according to model selection criteria paper
      results.col(count) = model_score(A, D, omega, V,  obj_value);
    }

    // Increment iterator
    iter++;

    // Increase count
    count++;
  }

  return results;
}<commit_msg>different auto_model<commit_after>#include <RcppArmadillo.h>

#include "bootstrappers.h"
#include "gmwm_logic.h"

// Used for scales_cpp
#include "wave_variance.h"

#include "analytical_matrix_derivatives.h"

#include "model_selection.h"

#include "ts_model_cpp.h"

//#include "automatic_models.h"
using namespace Rcpp;

// std::map<int, std::vector<std::string> > master_model(){
//
//   std::map<int, std::vector<std::string> > models;
//
//   // 4AR1() + WN()
//   models[0].push_back("AR1");
//   models[0].push_back("AR1");
//   models[0].push_back("AR1");
//   models[0].push_back("AR1");
//   models[0].push_back("WN");
//
//   // 4AR1()
//   models[1].push_back("AR1");
//   models[1].push_back("AR1");
//   models[1].push_back("AR1");
//   models[1].push_back("AR1");
//
//   // AR1() + WN()
//   models[2].push_back("AR1");
//   models[2].push_back("AR1");
//   models[2].push_back("AR1");
//   models[2].push_back("WN");
//
//   // 3AR1()
//   models[3].push_back("AR1");
//   models[3].push_back("AR1");
//   models[3].push_back("AR1");
//
//
//   // 2AR1()+WN()
//   models[4].push_back("AR1");
//   models[4].push_back("AR1");
//   models[4].push_back("WN");
//
//   // 2AR1()
//   models[5].push_back("AR1");
//   models[5].push_back("AR1");
//
//   // AR1()
//   models[6].push_back("AR1");
//
//   // WN()
//   models[7].push_back("WN");
//
//   return models;
// }

//[[Rcpp::export]]
std::map<int, std::vector<std::string> > master_model(){

  std::map<int, std::vector<std::string> > models;

  // 3AR1() + WN() + RW()
  models[0].push_back("AR1");
  models[0].push_back("AR1");
  models[0].push_back("AR1");
  models[0].push_back("WN");
  models[0].push_back("RW");

  // 3AR1() + RW()
  models[1].push_back("AR1");
  models[1].push_back("AR1");
  models[1].push_back("AR1");
  models[1].push_back("RW");

  // 3AR1() + WN()
  models[2].push_back("AR1");
  models[2].push_back("AR1");
  models[2].push_back("AR1");
  models[2].push_back("WN");

  // 3AR1()
  models[3].push_back("AR1");
  models[3].push_back("AR1");
  models[3].push_back("AR1");

  // 2AR1() + WN() + RW()
  models[4].push_back("AR1");
  models[4].push_back("AR1");
  models[4].push_back("WN");
  models[4].push_back("RW");

  // 2AR1() + RW()
  models[5].push_back("AR1");
  models[5].push_back("AR1");
  models[5].push_back("RW");

  // 2AR1() + WN()
  models[6].push_back("AR1");
  models[6].push_back("AR1");
  models[6].push_back("WN");

  // 2AR1()
  models[7].push_back("AR1");
  models[7].push_back("AR1");

  // AR1() + WN() + RW()
  models[8].push_back("AR1");
  models[8].push_back("WN");
  models[8].push_back("RW");

  // AR1() + RW()
  models[9].push_back("AR1");
  models[9].push_back("RW");

  // AR1() + WN()
  models[10].push_back("AR1");
  models[10].push_back("AR1");
  models[10].push_back("WN");

  // WN() + RW()
  models[11].push_back("WN");
  models[11].push_back("RW");

  // WN()
  models[12].push_back("WN");

  // RW()
  models[13].push_back("RW");

  // AR1()
  models[14].push_back("AR1");

  return models;
}

// [[Rcpp::export]]
arma::mat auto_select(const arma::vec& data,
                      std::string model_type,
                      double alpha,
                      std::string compute_v, unsigned int K, unsigned int H,
                      unsigned int G,
                      bool robust, double eff, bool bs_optimism){

  // Number of data points
  unsigned int N = data.n_elem;

  // Keep track of models parsed
  unsigned int count = 0;

  // Create a map
  std::map<int, std::vector<std::string> > models = master_model();

  // Make an iterator to iterator through it
  std::map<int, std::vector<std::string> >::iterator iter;
  iter = models.begin();

  // Get the first model
  std::vector<std::string> desc = iter->second;

  // Increment iterator
  iter++;

  // Build the fields off of the first model's description
  arma::vec theta = model_theta(desc);
  arma::field<arma::vec> objdesc = model_objdesc(desc);

  // Build matrix to store results
  arma::mat results(2, models.size());

  // Obtain the largest models information
  arma::field<arma::mat> master = gmwm_master_cpp(data,
                                                theta,
                                                desc,
                                                objdesc,
                                                model_type,
                                                true, //starting
                                                alpha,
                                                "fast", // compute V
                                                K, H,
                                                G,
                                                robust, eff);

  // Theta update
  theta = master(0);

  // Define WV Empirical
  arma::vec wv_empir = master(2);

  // Get bootstrapped V
  arma::mat V = cov_bootstrapper(theta, desc, objdesc, N, robust, eff, H, false); // Bootstrapped V (largest model)

  // Get the original "FAST" matrix
  arma::mat orgV = master(6); // Original V

  // Take the inverse
  arma::mat omega = inv(orgV); // Original V => Omega

  // Get expect_diff for guesses with DR
  double expect_diff = arma::as_scalar(master(7));

  // Obtain the theoretical WV
  arma::vec theo = master(8);

  // Obtain the obj_value of the function
  double obj_value = arma::as_scalar(master(10));

  // Calculate the values of the Scales
  arma::vec scales = scales_cpp(floor(log2(N)));

  /* A note to someone in the future...
   * Yes, there is a difference in order between the diff (wv_empir-theo) for D_matrix
   *  and the model_score diff (theo-wv_empir).
   */
  if(bs_optimism){

    arma::mat cov_nu_nu_theta = optimism_bootstrapper(theta,
                                                      desc, objdesc,
                                                      scales, model_type,
                                                      N, robust, eff, alpha,
                                                      H);

    double optimism = 2*sum(diagvec(cov_nu_nu_theta * omega));

    arma::vec temp(2);
    temp(0) = obj_value + optimism;
    temp(1) = optimism;
    results.col(count) = temp;
  }else{
    // Take derivatives
    arma::mat A = derivative_first_matrix(theta, desc, objdesc, scales);

    // Create the D Matrix (note this is in the analytical_matrix_derivaties.cpp file)
    arma::mat D = D_matrix(theta, desc, objdesc, scales, omega*(wv_empir - theo));

    // Calculate the model score according to model selection criteria paper
    results.col(count) = model_score(A, D, omega, V,  obj_value);
  }

  count++;

  while(iter != models.end()){
    // Get the first model
    std::vector<std::string> desc = iter->second;

    // Build the fields off of the first model's description
    theta = model_theta(desc);
    objdesc = model_objdesc(desc);

    // Run the update version of the GMWM
    arma::field<arma::mat> update = gmwm_update_cpp(theta,
                                                      desc,
                                                      objdesc,
                                                      model_type,
                                                      N, expect_diff,
                                                      orgV, scales, wv_empir,
                                                      true, //starting
                                                      "fast",
                                                      K,
                                                      H,
                                                      G,
                                                      robust,
                                                      eff);

    // Theta update
    theta = update(0);

    // Update theo
    theo = update(3);

    // Update objective function
    obj_value = arma::as_scalar(update(5));

    /* A note to someone in the future...
     * Yes, there is a difference in order between the diff (wv_empir-theo) for D_matrix
     *  and the model_score diff (theo-wv_empir).
     */
    if(bs_optimism){

      arma::mat cov_nu_nu_theta = optimism_bootstrapper(theta,
                                                        desc, objdesc,
                                                        scales, model_type,
                                                        N, robust, eff, alpha,
                                                        H);

      double optimism = 2*sum(diagvec(cov_nu_nu_theta * omega));

      arma::vec temp(2);
      temp(0) = obj_value + optimism;
      temp(1) = optimism;
      results.col(count) = temp;
    }else{
      // Take derivatives
      arma::mat A = derivative_first_matrix(theta, desc, objdesc, scales);

      // Create the D Matrix (note this is in the analytical_matrix_derivaties.cpp file)
      arma::mat D = D_matrix(theta, desc, objdesc, scales, omega*(wv_empir - theo));

      // Calculate the model score according to model selection criteria paper
      results.col(count) = model_score(A, D, omega, V,  obj_value);
    }

    // Increment iterator
    iter++;

    // Increase count
    count++;
  }

  return results;
}<|endoftext|>


<commit_before>#include "bitmap/TGA.h"
#include <assert.h>

using namespace Framework;

Framework::CBitmap CTGA::ReadBitmap(CStream& stream)
{
	TGA_HEADER header;
	stream.Read(&header, sizeof(TGA_HEADER));

	if(header.imageType != 0x02)
	{
		throw std::runtime_error("Unsupported TGA file.");
	}

	if(header.bits != 32)
	{
		throw std::runtime_error("Unsupported TGA file.");
	}

	bool originIsTop = (header.descriptor & 0x20) != 0;
	bool originIsRight = (header.descriptor & 0x10) != 0;

	assert(!originIsRight);

	CBitmap bitmap(header.width, header.height, 32);

	if(originIsTop)
	{
		stream.Read(bitmap.GetPixels(), bitmap.GetPixelsSize());
	}
	else
	{
		for(unsigned int y = 0; y < header.height; y++)
		{
			uint8* dstLinePtr = bitmap.GetPixels() + bitmap.GetPitch() * (header.height - y - 1);
			stream.Read(dstLinePtr, bitmap.GetPitch());
		}
	}

	{
		uint8* pixelsPtr = bitmap.GetPixels();
		for(unsigned int i = 0; i < bitmap.GetPixelsSize() / 4; i++)
		{
			std::swap(pixelsPtr[0], pixelsPtr[2]);
			pixelsPtr += 4;
		}
	}

	return bitmap;
}
<commit_msg>Compilation fix.<commit_after>#include "bitmap/TGA.h"
#include <stdexcept>
#include <assert.h>

using namespace Framework;

Framework::CBitmap CTGA::ReadBitmap(CStream& stream)
{
	TGA_HEADER header;
	stream.Read(&header, sizeof(TGA_HEADER));

	if(header.imageType != 0x02)
	{
		throw std::runtime_error("Unsupported TGA file.");
	}

	if(header.bits != 32)
	{
		throw std::runtime_error("Unsupported TGA file.");
	}

	bool originIsTop = (header.descriptor & 0x20) != 0;
	bool originIsRight = (header.descriptor & 0x10) != 0;

	assert(!originIsRight);

	CBitmap bitmap(header.width, header.height, 32);

	if(originIsTop)
	{
		stream.Read(bitmap.GetPixels(), bitmap.GetPixelsSize());
	}
	else
	{
		for(unsigned int y = 0; y < header.height; y++)
		{
			uint8* dstLinePtr = bitmap.GetPixels() + bitmap.GetPitch() * (header.height - y - 1);
			stream.Read(dstLinePtr, bitmap.GetPitch());
		}
	}

	{
		uint8* pixelsPtr = bitmap.GetPixels();
		for(unsigned int i = 0; i < bitmap.GetPixelsSize() / 4; i++)
		{
			std::swap(pixelsPtr[0], pixelsPtr[2]);
			pixelsPtr += 4;
		}
	}

	return bitmap;
}
<|endoftext|>


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

#ifndef AUTODOC_X_PARSING_HXX
#define AUTODOC_X_PARSING_HXX

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS

#include <iostream>

namespace autodoc
{

class X_Parser_Ifc
{
  public:
    // TYPES
    enum E_Event
    {
        x_Any                       = 0,
        x_InvalidChar,
        x_UnexpectedToken,
        x_UnexpectedEOF,
        x_UnspecifiedSyntaxError
    };

    // LIFECYCLE
    virtual             ~X_Parser_Ifc() {}

    // INQUIRY
    virtual E_Event     GetEvent() const = 0;
    virtual void        GetInfo(
                            ostream &           o_rOutputMedium ) const = 0;
};

}   // namespace autodoc

ostream &           operator<<(
                        ostream &           o_rOut,
                        const autodoc::X_Parser_Ifc &
                                            i_rException );

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.146); FILE MERGED 2005/09/05 13:09:43 rt 1.1.1.1.146.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: x_parsing.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 16:27:57 $
 *
 *  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 AUTODOC_X_PARSING_HXX
#define AUTODOC_X_PARSING_HXX

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS

#include <iostream>

namespace autodoc
{

class X_Parser_Ifc
{
  public:
    // TYPES
    enum E_Event
    {
        x_Any                       = 0,
        x_InvalidChar,
        x_UnexpectedToken,
        x_UnexpectedEOF,
        x_UnspecifiedSyntaxError
    };

    // LIFECYCLE
    virtual             ~X_Parser_Ifc() {}

    // INQUIRY
    virtual E_Event     GetEvent() const = 0;
    virtual void        GetInfo(
                            ostream &           o_rOutputMedium ) const = 0;
};

}   // namespace autodoc

ostream &           operator<<(
                        ostream &           o_rOut,
                        const autodoc::X_Parser_Ifc &
                                            i_rException );

#endif

<|endoftext|>


<commit_before>#include <stdlib.h>
#include "ros/ros.h"
#include <mongodb_store/message_store.h>
#include <boost/foreach.hpp>
#include <strands_navigation_msgs/NavStatistics.h>
#include <strands_navigation_msgs/TopologicalMap.h>
#include <strands_navigation_msgs/TopologicalNode.h>
#include <strands_executive_msgs/AddTask.h>
#include <std_msgs/Empty.h>
#include "CFrelementSet.h"
#include <time.h>

#define MAX_EDGES 10000

const mongo::BSONObj EMPTY_BSON_OBJ;

using namespace mongodb_store;
using namespace std;

ros::NodeHandle *n;
ros::Publisher  taskPub;
bool debug = false;
ros::ServiceClient taskAdder;

CFrelementSet frelementSet;
string nodeName;
uint32_t 	times[100000];
unsigned char 	state[100000];
float wheel[1000];
int numNodes = 0;
float lastWheel = 0;

void recalculateModels()
{
	numNodes = frelementSet.numFrelements;
	float explorationRatio = 0.5;
	float entropy[1],probability[1];
	uint32_t times[1];
	times[0] = 0;//TODO current time
	for (int i=0;i<numNodes;i++)
	{
		frelementSet.frelements[i]->estimateEntropy(times,entropy,1,1);
		frelementSet.frelements[i]->estimate(times,probability,1,1);
		lastWheel += explorationRatio*entropy[0]+(1-explorationRatio)*probability[0];
		wheel[i] = lastWheel;
	}
	printf("Wheel: ");
	for (int i=0;i<numNodes;i++) printf("%.3f ",wheel[i]);
	printf("%.3f \n",lastWheel);
}

/*loads nodes from the map description*/
void loadMap(const strands_navigation_msgs::TopologicalMap::ConstPtr& msg)
{

  	for (int i=0;i<msg->nodes.size();i++)
	{
		printf("MAP: %s.\n",msg->nodes[i].name.c_str());
		frelementSet.add(msg->nodes[i].name.c_str(),times,state,0);
	}
	numNodes = frelementSet.numFrelements;
	recalculateModels();
}

/*loads nodes from the map description*/
void getCurrentNode(const strands_navigation_msgs::TopologicalNode::ConstPtr& msg)
{
	nodeName = msg->name;
	printf("Current %s.\n",nodeName.c_str());
}

void addResult(const char *name,unsigned char state)
{
	uint32_t times[1];
	unsigned char signal[1];
	signal[0] = state;
	frelementSet.add(nodeName.c_str(),times,signal,1);
}

void interacted(const std_msgs::Empty::ConstPtr& msg)
{
	addResult(nodeName.c_str(),1);
}

void timeOut(const std_msgs::Empty::ConstPtr& msg)
{
	addResult(nodeName.c_str(),0);
}

/*recalculates models*/
void recalculate(const std_msgs::Empty::ConstPtr& msg)
{
	recalculateModels();
}

/*generates a task - invoked every minute*/
int generateTasks()
{
 time_t t;
 srand((unsigned int)time(&t));
	for (int i=0;i<2;i++)
	{
		int node = 0;
		if (numNodes > 0){
			float randomNum = (float)rand()/RAND_MAX*lastWheel;
			for (int p = 0;p<numNodes && randomNum > wheel[p];p++) node = p;
		}
		strands_executive_msgs::AddTask taskAdd;
		strands_executive_msgs::Task task;
		task.start_node_id = frelementSet.frelements[node]->id;
		task.action = "wait_action";
		task.start_after = ros::Time::now()+ros::Duration(180*i);
		task.end_before  = ros::Time::now()+ros::Duration(180*(i+1)-1);
		task.max_duration = ros::Duration(10);
		taskAdd.request.task = task;
		if (taskAdder.call(taskAdd))
		{
			ROS_INFO("Task ID: %ld", taskAdd.response.task_id);
		}
		printf("Time slot: %i-%i %i %s \n",180*i,180*(i+1)-1,numNodes,frelementSet.frelements[node]->id);
	}
}

int main(int argc,char* argv[])
{
	ros::init(argc, argv, "infremen");
	n = new ros::NodeHandle();
	ros::Subscriber  topoMapSub = n->subscribe("/topological_map", 1000, loadMap);
	//ros::Subscriber  currentNodeSub = n->subscribe("/current_node", 1000, getCurrentNode);
	//ros::Subscriber  interfaceSub = n->subscribe("/info_terminal", 1000, interacted);
	//ros::Subscriber  recalculateSub = n->subscribe("/recalculate", 1000, recalculate);
//	taskPub = n->advertise<strands_executive_msgs::Task>("/taskTopic", 1000, recalculate);
	taskAdder = n->serviceClient<strands_executive_msgs::AddTask>("/task_executor/add_task");
	int periodicity = 20*60*7;
	int iii = periodicity-5*20;
	while (ros::ok())
	{
		ros::spinOnce();
		usleep(50000);
		if (iii++>periodicity){
			 generateTasks();
			 iii=0;
		}
	}
	return 0;
}
<commit_msg>Scheduling in place<commit_after>#include <stdlib.h>
#include "ros/ros.h"
#include <mongodb_store/message_store.h>
#include <boost/foreach.hpp>
#include <strands_navigation_msgs/NavStatistics.h>
#include <strands_navigation_msgs/TopologicalMap.h>
#include <strands_navigation_msgs/TopologicalNode.h>
#include <strands_executive_msgs/AddTask.h>
#include <std_msgs/Empty.h>
#include "CFrelementSet.h"
#include <time.h>

#define MAX_EDGES 10000

const mongo::BSONObj EMPTY_BSON_OBJ;

using namespace mongodb_store;
using namespace std;

ros::NodeHandle *n;
ros::Publisher  taskPub;
bool debug = false;
ros::ServiceClient taskAdder;

CFrelementSet frelementSet;
string nodeName;
uint32_t 	times[100000];
unsigned char 	state[100000];
float wheel[1000];
int numNodes = 0;
float lastWheel = 0;

void recalculateModels()
{
	numNodes = frelementSet.numFrelements;
	float explorationRatio = 0.5;
	float entropy[1],probability[1];
	uint32_t times[1];
	times[0] = 0;//TODO current time
	for (int i=0;i<numNodes;i++)
	{
		frelementSet.frelements[i]->estimateEntropy(times,entropy,1,1);
		frelementSet.frelements[i]->estimate(times,probability,1,1);
		lastWheel += explorationRatio*entropy[0]+(1-explorationRatio)*probability[0];
		wheel[i] = lastWheel;
	}
	printf("Wheel: ");
	for (int i=0;i<numNodes;i++) printf("%.3f ",wheel[i]);
	printf("%.3f \n",lastWheel);
}

/*loads nodes from the map description*/
void loadMap(const strands_navigation_msgs::TopologicalMap::ConstPtr& msg)
{

  	for (int i=0;i<msg->nodes.size();i++)
	{
		printf("MAP: %s.\n",msg->nodes[i].name.c_str());
		frelementSet.add(msg->nodes[i].name.c_str(),times,state,0);
	}
	numNodes = frelementSet.numFrelements;
	recalculateModels();
}

/*loads nodes from the map description*/
void getCurrentNode(const std_msgs::String::ConstPtr& msg)
{
	nodeName = msg->name;
	printf("Current %s.\n",nodeName.c_str());
}

void addResult(const char *name,unsigned char state)
{
	uint32_t times[1];
	unsigned char signal[1];
	signal[0] = state;
	frelementSet.add(nodeName.c_str(),times,signal,1);
}

void interacted(const std_msgs::Empty::ConstPtr& msg)
{
	addResult(nodeName.c_str(),1);
}

void timeOut(const std_msgs::Empty::ConstPtr& msg)
{
	addResult(nodeName.c_str(),0);
}

/*recalculates models*/
void recalculate(const std_msgs::Empty::ConstPtr& msg)
{
	recalculateModels();
}

/*generates a task - invoked every minute*/
int generateTasks()
{
 time_t t;
 srand((unsigned int)time(&t));
	for (int i=0;i<2;i++)
	{
		int node = 0;
		if (numNodes > 0){
			float randomNum = (float)rand()/RAND_MAX*lastWheel;
			for (int p = 0;p<numNodes && randomNum > wheel[p];p++) node = p;
		}
		strands_executive_msgs::AddTask taskAdd;
		strands_executive_msgs::Task task;
		task.start_node_id = frelementSet.frelements[node]->id;
		task.action = "wait_action";
		task.start_after = ros::Time::now()+ros::Duration(180*i);
		task.end_before  = ros::Time::now()+ros::Duration(180*(i+1)-1);
		task.max_duration = ros::Duration(10);
		taskAdd.request.task = task;
		if (taskAdder.call(taskAdd))
		{
			ROS_INFO("Task ID: %ld", taskAdd.response.task_id);
		}
		printf("Time slot: %i-%i %i %s \n",180*i,180*(i+1)-1,numNodes,frelementSet.frelements[node]->id);
	}
}

int main(int argc,char* argv[])
{
	ros::init(argc, argv, "infremen");
	n = new ros::NodeHandle();
	ros::Subscriber  topoMapSub = n->subscribe("/topological_map", 1000, loadMap);
	ros::Subscriber  currentNodeSub = n->subscribe("/current_node", 1000, getCurrentNode);
	//ros::Subscriber  interfaceSub = n->subscribe("/info_terminal", 1000, interacted);
	//ros::Subscriber  recalculateSub = n->subscribe("/recalculate", 1000, recalculate);
//	taskPub = n->advertise<strands_executive_msgs::Task>("/taskTopic", 1000, recalculate);
	taskAdder = n->serviceClient<strands_executive_msgs::AddTask>("/task_executor/add_task");
	int periodicity = 20*60*7;
	int iii = periodicity-5*20;
	while (ros::ok())
	{
		ros::spinOnce();
		usleep(50000);
		if (iii++>periodicity){
			 generateTasks();
			 iii=0;
		}
	}
	return 0;
}
<|endoftext|>