<commit_before>#include <functional>
#include <future>
#include "kernel.h"
#include "raster.h"
#include "columndefinition.h"
#include "table.h"
#include "basetable.h"
#include "flattable.h"
#include "symboltable.h"
#include "ilwisoperation.h"
#include "unarymath.h"

using namespace Ilwis;
using namespace BaseOperations;

UnaryMath::UnaryMath() {

}

UnaryMath::UnaryMath(quint64 metaid, const Ilwis::OperationExpression& expr, const QString &outpDom, UnaryFunction fun) :
    OperationImplementation(metaid, expr),
    _case(otSPATIAL),
    _number(rUNDEF),
    _outputDomain(outpDom),
    _unaryFun(fun)
{

}

bool UnaryMath::execute(ExecutionContext *ctx, SymbolTable& symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;

    if ( _case == otSPATIAL) {
        BoxedAsyncFunc unaryFun = [&](const BoundingBox& box) -> bool {
            PixelIterator iterIn(_inputGC, _box);
            PixelIterator iterOut(_outputGC, BoundingBox(_box.size()));

            double v_in = 0;
            for_each(iterOut, iterOut.end(), [&](double& v){
                if ( (v_in = *iterIn) != rUNDEF) {
                    v = _unaryFun(v_in);
                }
                ++iterIn;
            });
            return true;
        };

        bool resource = OperationHelperRaster::execute(ctx, unaryFun, _outputGC);

        if ( resource && ctx != 0) {
            QVariant value;
            value.setValue<IRasterCoverage>(_outputGC);
            ctx->setOutput(symTable,value,_outputGC->name(), itRASTER,_outputGC->source() );
        }
    } else if (_case == otNUMBER) {
        double v = _unaryFun(_number);
        ctx->setOutput(symTable, QVariant(v), sUNDEF, itDOUBLE, Resource());

    } else if (  _case == otTABLE) {
        std::vector<QVariant> data = _inputTable->column(_inColumn);
        std::vector<QVariant> dataOut(data.size());
        auto iterOut = dataOut.begin();
        for(const QVariant& val : data) {
            *iterOut = _unaryFun(val.toDouble());
            ++iterOut;
        }
        _outputTable->column(_outColumn,dataOut);
        if ( _outputTable.isValid()) {
            QVariant var;
            var.setValue<ITable>(_outputTable);
            ctx->setOutput(symTable,var, _outputTable->name(),itTABLE,_outputTable->source(),_outColumn);
            return true;
        }
    }

    return true;
}

OperationImplementation::State UnaryMath::prepare(ExecutionContext *,const SymbolTable&)
{
    IlwisTypes ptype = _expression.parm(0).valuetype();

    if ( ptype & itNUMBER ) {
        _case = otNUMBER;
        bool ok;
        _number = _expression.parm(0).value().toDouble(&ok);
        if (!ok) {
            ERROR2(ERR_NO_OBJECT_TYPE_FOR_2,"Numerical value", "UnaryMath operation");
            _number = rUNDEF;
            return sPREPAREFAILED;
        }
        return sPREPARED;

    } else if ( ptype == itRASTER) {
        QString raster = _expression.parm(0).value();

        if (!_inputGC.prepare(raster)) {
            ERROR2(ERR_COULD_NOT_LOAD_2,raster,"");
            return sPREPAREFAILED;
        }
        OperationHelperRaster helper;
        _box = helper.initialize(_inputGC, _outputGC, itRASTERSIZE | itENVELOPE | itCOORDSYSTEM | itGEOREF);
        if ( !_outputGC.isValid()) {
            ERROR1(ERR_NO_INITIALIZED_1, "output rastercoverage");
            return sPREPAREFAILED;
        }
        QString outputName = _expression.parm(0,false).value();
        if ( outputName != sUNDEF)
            _outputGC->name(outputName);

        IDomain dom;
        if(!dom.prepare(_outputDomain))
            return sPREPAREFAILED;

        _outputGC->datadef().domain(dom);
        _unaryFun = sin;

        _case = otSPATIAL;
        return sPREPARED;
    } else if ( hasType(ptype, itTABLE)) {
        _case = otTABLE;
        QString table = _expression.parm(0).value();
        if (!_inputTable.prepare(table)) {
            ERROR2(ERR_COULD_NOT_LOAD_2,table,"");
            return sPREPAREFAILED;
        }
        _inColumn = _inputTable->columndefinition(0).name();
        if ( _expression.parameterCount() == 2){
            _inColumn = _expression.parm(1).value();
        }
        _outColumn = "column_" + QString::number(_inputTable->columnCount());
        if (!hasType(_inputTable->columndefinition(_inColumn).datadef().domain<>()->valueType(), itNUMBER)) {
            ERROR2(ERR_NOT_COMPATIBLE2, TR("column"), _expression.name());
            return sPREPAREFAILED;
        }
        QString outName = _expression.parm(0, false).value();
        if ( table != outName) {
            if ( table != outName) {
                if (outName == sUNDEF){
                    IFlatTable  ftable;
                    ftable.prepare();
                    _outputTable = ftable;
                }
            } else if(!_outputTable.prepare(outName)) {// output table doesnt need to exists
                _outputTable.prepare(QString("ilwis://internalcatalog/%1").arg(outName), _inputTable->ilwisType());
                _outputTable->name(outName);

            }
        } else
            _outputTable = _inputTable;
        IDomain dom;
        if(!dom.prepare(_outputDomain))
            return sPREPAREFAILED;
        ColumnDefinition def(_outColumn, dom);
        _outputTable->addColumn(def);
        return sPREPARED;

    }
    return sNOTPREPARED;
}

Resource UnaryMath::populateMetadata(const QString& item, const QString& longname, const QString& outputDom) {
    Resource resource(QUrl(item), itOPERATIONMETADATA);
    int index = item.lastIndexOf("/");
    QString name = item.mid(index);
    resource.addProperty("syntax", QString("%1(rastercoverage|double)").arg(name));
    resource.addProperty("description",TR("generates a new numrical rastercoverage/featurecoverage based on the operation, applied to all the pixels"));
    resource.addProperty("longname",longname);
    resource.addProperty("namespace","ilwis");
    resource.addProperty("inparameters","1|2");
    resource.addProperty("pin_1_type", itRASTER|itTABLE);
    resource.addProperty("pin_1_name", TR("input rastercoverage"));
    resource.addProperty("pin_1_domain","value");
    resource.addProperty("pin_2_type", itSTRING);
    resource.addProperty("pin_2_name", TR("column name in case of the table calculations"));
    resource.addProperty("pin_2_domain","value");
    resource.addProperty("outparameters",1);
    resource.addProperty("pout_1_type", itRASTER|itTABLE);
    resource.addProperty("pout_1_name", TR("output rastercoverage"));
    resource.addProperty("pout_1_domain",outputDom);
    resource.prepare();
    QString url = resource.url().toString();
    url += "=" + QString::number(resource.id());
    resource.setUrl(url);

    return resource;

}

<commit_msg>for some odd (unneeded) reason the unaryfunction was set to default 'sin'.<commit_after>#include <functional>
#include <future>
#include "kernel.h"
#include "raster.h"
#include "columndefinition.h"
#include "table.h"
#include "basetable.h"
#include "flattable.h"
#include "symboltable.h"
#include "ilwisoperation.h"
#include "unarymath.h"

using namespace Ilwis;
using namespace BaseOperations;

UnaryMath::UnaryMath() {

}

UnaryMath::UnaryMath(quint64 metaid, const Ilwis::OperationExpression& expr, const QString &outpDom, UnaryFunction fun) :
    OperationImplementation(metaid, expr),
    _case(otSPATIAL),
    _number(rUNDEF),
    _outputDomain(outpDom),
    _unaryFun(fun)
{

}

bool UnaryMath::execute(ExecutionContext *ctx, SymbolTable& symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;

    if ( _case == otSPATIAL) {
        BoxedAsyncFunc unaryFun = [&](const BoundingBox& box) -> bool {
            PixelIterator iterIn(_inputGC, _box);
            PixelIterator iterOut(_outputGC, BoundingBox(_box.size()));

            double v_in = 0;
            for_each(iterOut, iterOut.end(), [&](double& v){
                if ( (v_in = *iterIn) != rUNDEF) {
                    v = _unaryFun(v_in);
                }
                ++iterIn;
            });
            return true;
        };

        bool resource = OperationHelperRaster::execute(ctx, unaryFun, _outputGC);

        if ( resource && ctx != 0) {
            QVariant value;
            value.setValue<IRasterCoverage>(_outputGC);
            ctx->setOutput(symTable,value,_outputGC->name(), itRASTER,_outputGC->source() );
        }
    } else if (_case == otNUMBER) {
        double v = _unaryFun(_number);
        ctx->setOutput(symTable, QVariant(v), sUNDEF, itDOUBLE, Resource());

    } else if (  _case == otTABLE) {
        std::vector<QVariant> data = _inputTable->column(_inColumn);
        std::vector<QVariant> dataOut(data.size());
        auto iterOut = dataOut.begin();
        for(const QVariant& val : data) {
            *iterOut = _unaryFun(val.toDouble());
            ++iterOut;
        }
        _outputTable->column(_outColumn,dataOut);
        if ( _outputTable.isValid()) {
            QVariant var;
            var.setValue<ITable>(_outputTable);
            ctx->setOutput(symTable,var, _outputTable->name(),itTABLE,_outputTable->source(),_outColumn);
            return true;
        }
    }

    return true;
}

OperationImplementation::State UnaryMath::prepare(ExecutionContext *,const SymbolTable&)
{
    IlwisTypes ptype = _expression.parm(0).valuetype();

    if ( ptype & itNUMBER ) {
        _case = otNUMBER;
        bool ok;
        _number = _expression.parm(0).value().toDouble(&ok);
        if (!ok) {
            ERROR2(ERR_NO_OBJECT_TYPE_FOR_2,"Numerical value", "UnaryMath operation");
            _number = rUNDEF;
            return sPREPAREFAILED;
        }
        return sPREPARED;

    } else if ( ptype == itRASTER) {
        QString raster = _expression.parm(0).value();

        if (!_inputGC.prepare(raster)) {
            ERROR2(ERR_COULD_NOT_LOAD_2,raster,"");
            return sPREPAREFAILED;
        }
        OperationHelperRaster helper;
        _box = helper.initialize(_inputGC, _outputGC, itRASTERSIZE | itENVELOPE | itCOORDSYSTEM | itGEOREF);
        if ( !_outputGC.isValid()) {
            ERROR1(ERR_NO_INITIALIZED_1, "output rastercoverage");
            return sPREPAREFAILED;
        }
        QString outputName = _expression.parm(0,false).value();
        if ( outputName != sUNDEF)
            _outputGC->name(outputName);

        IDomain dom;
        if(!dom.prepare(_outputDomain))
            return sPREPAREFAILED;

        _outputGC->datadef().domain(dom);
        _case = otSPATIAL;
        return sPREPARED;
    } else if ( hasType(ptype, itTABLE)) {
        _case = otTABLE;
        QString table = _expression.parm(0).value();
        if (!_inputTable.prepare(table)) {
            ERROR2(ERR_COULD_NOT_LOAD_2,table,"");
            return sPREPAREFAILED;
        }
        _inColumn = _inputTable->columndefinition(0).name();
        if ( _expression.parameterCount() == 2){
            _inColumn = _expression.parm(1).value();
        }
        _outColumn = "column_" + QString::number(_inputTable->columnCount());
        if (!hasType(_inputTable->columndefinition(_inColumn).datadef().domain<>()->valueType(), itNUMBER)) {
            ERROR2(ERR_NOT_COMPATIBLE2, TR("column"), _expression.name());
            return sPREPAREFAILED;
        }
        QString outName = _expression.parm(0, false).value();
        if ( table != outName) {
            if ( table != outName) {
                if (outName == sUNDEF){
                    IFlatTable  ftable;
                    ftable.prepare();
                    _outputTable = ftable;
                }
            } else if(!_outputTable.prepare(outName)) {// output table doesnt need to exists
                _outputTable.prepare(QString("ilwis://internalcatalog/%1").arg(outName), _inputTable->ilwisType());
                _outputTable->name(outName);

            }
        } else
            _outputTable = _inputTable;
        IDomain dom;
        if(!dom.prepare(_outputDomain))
            return sPREPAREFAILED;
        ColumnDefinition def(_outColumn, dom);
        _outputTable->addColumn(def);
        return sPREPARED;

    }
    return sNOTPREPARED;
}

Resource UnaryMath::populateMetadata(const QString& item, const QString& longname, const QString& outputDom) {
    Resource resource(QUrl(item), itOPERATIONMETADATA);
    int index = item.lastIndexOf("/");
    QString name = item.mid(index);
    resource.addProperty("syntax", QString("%1(rastercoverage|double)").arg(name));
    resource.addProperty("description",TR("generates a new numrical rastercoverage/featurecoverage based on the operation, applied to all the pixels"));
    resource.addProperty("longname",longname);
    resource.addProperty("namespace","ilwis");
    resource.addProperty("inparameters","1|2");
    resource.addProperty("pin_1_type", itRASTER|itTABLE);
    resource.addProperty("pin_1_name", TR("input rastercoverage"));
    resource.addProperty("pin_1_domain","value");
    resource.addProperty("pin_2_type", itSTRING);
    resource.addProperty("pin_2_name", TR("column name in case of the table calculations"));
    resource.addProperty("pin_2_domain","value");
    resource.addProperty("outparameters",1);
    resource.addProperty("pout_1_type", itRASTER|itTABLE);
    resource.addProperty("pout_1_name", TR("output rastercoverage"));
    resource.addProperty("pout_1_domain",outputDom);
    resource.prepare();
    QString url = resource.url().toString();
    url += "=" + QString::number(resource.id());
    resource.setUrl(url);

    return resource;

}

<|endoftext|>


<commit_before>/*
 * QDigiDocClient
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include "Application.h"

#ifdef Q_OS_WIN32
#include <QtCore/QDebug>
#include <QtCore/qt_windows.h>
#endif

int main( int argc, char *argv[] )
{
#if QT_VERSION > QT_VERSION_CHECK(5, 6, 0)
	QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, true);
#ifdef Q_OS_WIN32
	char **newv = (char**)malloc((argc + 3) * sizeof(*newv));
	memmove(newv, argv, sizeof(*newv) * argc);
	newv[argc++] = (char*)"-platform";
	newv[argc++] = (char*)"windows:dpiawareness=1";
	newv[argc] = 0;
	argv = newv;

	HDC screen = GetDC(0);
	qreal dpi = GetDeviceCaps(screen, LOGPIXELSY);
	qreal scale = dpi / qreal(96);
	qputenv("QT_SCALE_FACTOR", QByteArray::number(scale));
	ReleaseDC(NULL, screen);
	qDebug() << "Current DPI:" << dpi << " setting scale:" << scale;
#else
	QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
#endif
#endif

	DdCliApplication cliApp( argc, argv );
	if( cliApp.isDiagnosticRun() )
	{
		return cliApp.run();
	}

	return Application( argc, argv ).run();
}
<commit_msg>Workaround Windows 8.1 DPI settings (#97)<commit_after>/*
 * QDigiDocClient
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include "Application.h"

#ifdef Q_OS_WIN32
#include <QtCore/QDebug>
#include <QtCore/qt_windows.h>
#endif

int main( int argc, char *argv[] )
{
#if QT_VERSION > QT_VERSION_CHECK(5, 6, 0)
	QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, true);
#ifdef Q_OS_WIN32
	char **newv = (char**)malloc((argc + 3) * sizeof(*newv));
	memmove(newv, argv, sizeof(*newv) * argc);
	newv[argc++] = (char*)"-platform";
	newv[argc++] = (char*)"windows:dpiawareness=1";
	newv[argc] = 0;
	argv = newv;

	SetProcessDPIAware();
	HDC screen = GetDC(0);
	qreal dpix = GetDeviceCaps(screen, LOGPIXELSX);
	qreal dpiy = GetDeviceCaps(screen, LOGPIXELSY);
	qreal scale = dpiy / qreal(96);
	qputenv("QT_SCALE_FACTOR", QByteArray::number(scale));
	ReleaseDC(NULL, screen);
	qDebug() << "Current DPI x: " << dpix << " y: " << dpiy << " setting scale:" << scale;
#else
	QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
#endif
#endif

	DdCliApplication cliApp( argc, argv );
	if( cliApp.isDiagnosticRun() )
	{
		return cliApp.run();
	}

	return Application( argc, argv ).run();
}
<|endoftext|>


<commit_before>//
// Copyright (C) 2006-2012 SIPez LLC.  All rights reserved.
//
// 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.
//
// $$
///////////////////////////////////////////////////////////////////////////////

#include "rtcp/RtcpConfig.h"

#undef WANT_RTCP_LOG_MESSAGES
#undef DROP_SOME_PACKETS

// SYSTEM INCLUDES
#include <assert.h>

#ifdef _VXWORKS /* [ */
#include <iosLib.h>
#include <netinet/in.h>
#endif /* _VXWORKS ] */

#ifdef WIN32 /* [ */
#include <winsock2.h>
#   ifndef WINCE
#       include <io.h>
#   endif
#endif /* WIN32 ] */

#ifdef __pingtel_on_posix__ /* [ */
#include "os/OsIntTypes.h"
#include <sys/types.h>
#include <netinet/in.h>
#endif /* __pingtel_on_posix__ ] */

// APPLICATION INCLUDES
#include "os/OsDefs.h"
#include "mp/MpMisc.h"
#include "mp/MpBuf.h"
#include "mp/MprToNet.h"
#include "mp/NetInTask.h"
#include "mp/MprFromNet.h"
#include "mp/dmaTask.h"

// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS

#ifdef ENABLE_PACKET_HACKING /* [ */
int MprToNet::sDebug1 = 0;
int MprToNet::sDebug2 = 0;
int MprToNet::sDebug3 = 0;
int MprToNet::sDebug4 = 0;
int MprToNet::sDebug5 = 0;
#endif /* ENABLE_PACKET_HACKING ] */

static int doPadRtp = 1;

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

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

// Constructor
MprToNet::MprToNet()
:  mpFromNetPal(NULL)
,  mRtcpPackets(0)
,  mRtcpFrameCount(0)
,  mRtcpFrameLimit(500)
#ifdef DEBUG /* [ */
,  mRtpSampleCounter(0)
#endif /* DEBUG ] */
,  mTimestampDelta(0)
,  mSeqNum(0)
,  mSSRC(0)
,  mpRtpSocket(NULL)
,  mpRtcpSocket(NULL)
,  mNumRtpWriteErrors(0)
,  mNumRtcpWriteErrors(0)
#ifdef INCLUDE_RTCP /* [ */
,  mpiRTPAccumulator(NULL)
#endif /* INCLUDE_RTCP ] */

{
}

// Destructor
MprToNet::~MprToNet()
{
#ifdef INCLUDE_RTCP /* [ */

//  Release the reference held to the RTP Accumulator interface used to
//  RTP outbound stream statistics
    if(mpiRTPAccumulator)
    {
        mpiRTPAccumulator->Release();
        mpiRTPAccumulator = NULL;
    }
#endif /* INCLUDE_RTCP ] */
    if (0 != mNumRtpWriteErrors) {
        osPrintf("MprToNet: %d network write errors on RTP socket!\n",
            mNumRtpWriteErrors);
    }
    if (0 != mNumRtcpWriteErrors) {
        osPrintf("MprToNet: %d network write errors on RTCP socket!\n",
            mNumRtcpWriteErrors);
    }
}

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

// Set the outbound RTP and RTCP sockets.
OsStatus MprToNet::setSockets(OsSocket& rRtpSocket, OsSocket& rRtcpSocket)
{
   mpRtpSocket  = &rRtpSocket;
   mpRtcpSocket = &rRtcpSocket;

   return OS_SUCCESS;
}

// Clear the outbound RTP and RTCP sockets.
OsStatus MprToNet::resetSockets(void)
{
   mpRtpSocket  = NULL;
   mpRtcpSocket = NULL;

   return OS_SUCCESS;
}

void MprToNet::setSSRC(int iSSRC)
{
   mSSRC = iSSRC;
   mSeqNum = rand_timer32() | 0xfc00;
   mTimestampDelta = rand_timer32();
}

#ifdef INCLUDE_RTCP /* [ */
void MprToNet::setRTPAccumulator(ISetSenderStatistics *piRTPAccumulator)
{
   mpiRTPAccumulator = piRTPAccumulator;
   if(mpiRTPAccumulator)
   {
       mpiRTPAccumulator->SetRTPTimestamp(mTimestampDelta);
   }
}

#endif /* INCLUDE_RTCP ] */

#ifdef DROP_SOME_PACKETS // [
static int dropLimit = 1<<30;
static int dropCount = 0;

extern "C" {
extern int dropEvery(int limit);
}

int dropEvery(int limit)
{
   int save = dropLimit;
   if (limit < 0) limit = 1<<30;
   if (limit > 0) {
      dropLimit = limit;
      dropCount = 0;
   }
   return save;
}
#endif // DROP_SOME_PACKETS ]

int MprToNet::writeRtp(int payloadType, UtlBoolean markerState,
                       const unsigned char* payloadData, int payloadOctets,
                       unsigned int timestamp, void* csrcList)
{
   MpRtpBufPtr pRtpPacket;
   char paddingLength;

   // Nothing to do when no socket specified.
   if (mpRtpSocket == NULL)
      return 0;

   // Allocate new RTP packet.
   pRtpPacket = MpMisc.RtpPool->getBuffer();

   // Get rid of packet sequence number.
   mSeqNum++;

   // Fill packet RTP header.
   pRtpPacket->setRtpVersion(2);
   pRtpPacket->setRtpPayloadType(payloadType);
   pRtpPacket->setPayloadSize(payloadOctets);
   if (markerState)
      pRtpPacket->enableRtpMarker();
   else
      pRtpPacket->disableRtpMarker();
   pRtpPacket->disableRtpExtension();
   pRtpPacket->setRtpSequenceNumber(mSeqNum);
   pRtpPacket->setRtpTimestamp(mTimestampDelta + timestamp);
   pRtpPacket->setRtpSSRC(mSSRC);
   pRtpPacket->setRtpCSRCCount(0);

#ifdef ENABLE_PACKET_HACKING /* [ */
   adjustRtpPacket(pRtpPacket->getRtpHeader());
#endif /* ENABLE_PACKET_HACKING ] */

   // Calculate number of padding bytes
   paddingLength = doPadRtp ? ((4 - (payloadOctets & 3))&3) : 0;

   if (paddingLength>0)
      pRtpPacket->enableRtpPadding();
   else
      pRtpPacket->disableRtpPadding();

   if (csrcList != NULL)
   {
      int csrcSize = pRtpPacket->getRtpCSRCCount() * sizeof(RtpSRC);
      // TODO:: implement CSRC list.
      assert(csrcSize == 0);
   }

   //////////////////////////////////////////////////////
   // Next part of code should separated from previous //
   //////////////////////////////////////////////////////

   char *pBuf;
   unsigned int numBytesSent;
   MpUdpBufPtr pUdpPacket;

   // Allocate UDP packet
   pUdpPacket = MpMisc.UdpPool->getBuffer();
   pBuf = pUdpPacket->getDataWritePtr();

   // Set size of data to send
   assert(pUdpPacket->getMaximumPacketSize() >= sizeof(RtpHeader)+payloadOctets+paddingLength);
   pUdpPacket->setPacketSize(sizeof(RtpHeader)+payloadOctets+paddingLength);

   // Copy RTP header to UDP packet
   memcpy(pBuf, &pRtpPacket->getRtpHeader(), sizeof(RtpHeader));
   pBuf += sizeof(RtpHeader);

   // TODO:: Copy CSRC list here.

   // Copy payload to UDP packet
   memcpy(pBuf, payloadData, payloadOctets);
   pBuf += payloadOctets;

   // Fill padding
   switch (paddingLength) {
   case 3:
      pBuf[1] = 0;           // fall through
   case 2:
      pBuf[0] = 0;           // fall through
   case 1:
      pBuf[paddingLength-1] = paddingLength;  // fall through
   case 0:
      break;
   }

#ifdef INCLUDE_RTCP /* [ */
   // Update the Accumulated statistics kept for an inbound RTP packet.
   // These statistics comprise a Sender Report that is sent out periodically
   // to the originating site
   if(mpiRTPAccumulator)
   {
       mpiRTPAccumulator->IncrementCounts(payloadOctets);
   }
#endif /* INCLUDE_RTCP ] */

   const char* writeBytes = pUdpPacket->getDataPtr();
   int packetSize = pUdpPacket->getPacketSize();

#ifdef DROP_SOME_PACKETS /* [ */
   if (dropCount++ == dropLimit) {
      dropCount = 0;
      numBytesSent = pUdpPacket->getPacketSize();
   }
   // Socket can get set asynchronously to NULL when RTP send is stopped.  So check immediately before accessing socket.
   else if(mpRtpSocket)
   {
      numBytesSent = mpRtpSocket->write(writeBytes, packetSize);
   }
   else
   {
       numBytesSent = 0;
   }
#else /* DROP_SOME_PACKETS ] [*/

   // Socket can get set asynchronously to NULL when RTP send is stopped.  So check immediately before accessing socket.
   if(mpRtpSocket)
   {
      numBytesSent = mpRtpSocket->write(writeBytes, packetSize);
   }
   else
   {
       numBytesSent = 0;
   }
#endif /* DROP_SOME_PACKETS ] */

#ifdef TEST_PRINT
   UtlString remoteIp("null socket");
   int remotePort;
   if(mpRtpSocket)
   {
      mpRtpSocket->getRemoteHostIp(&remoteIp, &remotePort);
   }
   OsSysLog::add(FAC_MP, PRI_DEBUG, "MprToNet::writeRtp payload: %d send to address: %s port: %d numBytesSent: %d errno: %d",
      payloadType, remoteIp.data(), remotePort, numBytesSent, errno);
#endif

   if (numBytesSent != pUdpPacket->getPacketSize()) {
      switch (errno) {
         /* insert other benign errno values here */
            case 0:
            case 55: // Network disconnected, continue and hope it comes back
               break;
            default:
               // close(fd);  MAYBE: mpRtpSocket->close() ?
               // mpRtpSocket = NULL;
               break;
      }

   }
   return (pUdpPacket->getPacketSize() == numBytesSent) ? pUdpPacket->getPacketSize() : numBytesSent;
}

#ifdef ENABLE_PACKET_HACKING /* [ */
extern "C" {
extern int sTRA(int a, int b, int c);
extern int setToRtpAdjustment(int a, int b, int c);
};

int setToRtpAdjustment(int ssrc, int seq, int ts)
{
   MprToNet::sDebug1 = ssrc;
   MprToNet::sDebug2 = seq;
   MprToNet::sDebug3 = ts;
   return 0;
}

int sTRA(int a, int b, int c) {return setToRtpAdjustment(a,b,c);}
#endif /* ENABLE_PACKET_HACKING ] */

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

OsStatus MprToNet::setRtpPal(MprFromNet* pal)
{
   mpFromNetPal = pal;
   return OS_SUCCESS;
}

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

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

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

#ifdef ENABLE_PACKET_HACKING /* [ */
void MprToNet::adjustRtpPacket(struct RtpHeader* rp)
{
   struct RtpHeader rh;

   memcpy((char *) &rh, (char *) rp, sizeof(struct RtpHeader));
   // rh.vpxcc = rh.vpxcc;
   // rh.mpt = rh.mpt;
   rh.ssrc = ntohl(rh.ssrc) - sDebug1;
   rh.seq = ntohs(rh.seq) - sDebug2;
   rh.timestamp = ntohl(rh.timestamp) - sDebug3;
   rh.ssrc = htonl(rh.ssrc);
   rh.seq = htons(rh.seq);
   rh.timestamp = htonl(rh.timestamp);
   memcpy((char *) rp, (char *) &rh, sizeof(struct RtpHeader));
}
#endif /* ENABLE_PACKET_HACKING ] */

/* ============================ FUNCTIONS ================================= */
<commit_msg>assert that ToNet gets a buffer from the pool<commit_after>//
// Copyright (C) 2006-2012 SIPez LLC.  All rights reserved.
//
// 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.
//
// $$
///////////////////////////////////////////////////////////////////////////////

#include "rtcp/RtcpConfig.h"

#undef WANT_RTCP_LOG_MESSAGES
#undef DROP_SOME_PACKETS

// SYSTEM INCLUDES
#include <assert.h>

#ifdef _VXWORKS /* [ */
#include <iosLib.h>
#include <netinet/in.h>
#endif /* _VXWORKS ] */

#ifdef WIN32 /* [ */
#include <winsock2.h>
#   ifndef WINCE
#       include <io.h>
#   endif
#endif /* WIN32 ] */

#ifdef __pingtel_on_posix__ /* [ */
#include "os/OsIntTypes.h"
#include <sys/types.h>
#include <netinet/in.h>
#endif /* __pingtel_on_posix__ ] */

// APPLICATION INCLUDES
#include "os/OsDefs.h"
#include "mp/MpMisc.h"
#include "mp/MpBuf.h"
#include "mp/MprToNet.h"
#include "mp/NetInTask.h"
#include "mp/MprFromNet.h"
#include "mp/dmaTask.h"

// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS

#ifdef ENABLE_PACKET_HACKING /* [ */
int MprToNet::sDebug1 = 0;
int MprToNet::sDebug2 = 0;
int MprToNet::sDebug3 = 0;
int MprToNet::sDebug4 = 0;
int MprToNet::sDebug5 = 0;
#endif /* ENABLE_PACKET_HACKING ] */

static int doPadRtp = 1;

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

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

// Constructor
MprToNet::MprToNet()
:  mpFromNetPal(NULL)
,  mRtcpPackets(0)
,  mRtcpFrameCount(0)
,  mRtcpFrameLimit(500)
#ifdef DEBUG /* [ */
,  mRtpSampleCounter(0)
#endif /* DEBUG ] */
,  mTimestampDelta(0)
,  mSeqNum(0)
,  mSSRC(0)
,  mpRtpSocket(NULL)
,  mpRtcpSocket(NULL)
,  mNumRtpWriteErrors(0)
,  mNumRtcpWriteErrors(0)
#ifdef INCLUDE_RTCP /* [ */
,  mpiRTPAccumulator(NULL)
#endif /* INCLUDE_RTCP ] */

{
}

// Destructor
MprToNet::~MprToNet()
{
#ifdef INCLUDE_RTCP /* [ */

//  Release the reference held to the RTP Accumulator interface used to
//  RTP outbound stream statistics
    if(mpiRTPAccumulator)
    {
        mpiRTPAccumulator->Release();
        mpiRTPAccumulator = NULL;
    }
#endif /* INCLUDE_RTCP ] */
    if (0 != mNumRtpWriteErrors) {
        osPrintf("MprToNet: %d network write errors on RTP socket!\n",
            mNumRtpWriteErrors);
    }
    if (0 != mNumRtcpWriteErrors) {
        osPrintf("MprToNet: %d network write errors on RTCP socket!\n",
            mNumRtcpWriteErrors);
    }
}

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

// Set the outbound RTP and RTCP sockets.
OsStatus MprToNet::setSockets(OsSocket& rRtpSocket, OsSocket& rRtcpSocket)
{
   mpRtpSocket  = &rRtpSocket;
   mpRtcpSocket = &rRtcpSocket;

   return OS_SUCCESS;
}

// Clear the outbound RTP and RTCP sockets.
OsStatus MprToNet::resetSockets(void)
{
   mpRtpSocket  = NULL;
   mpRtcpSocket = NULL;

   return OS_SUCCESS;
}

void MprToNet::setSSRC(int iSSRC)
{
   mSSRC = iSSRC;
   mSeqNum = rand_timer32() | 0xfc00;
   mTimestampDelta = rand_timer32();
}

#ifdef INCLUDE_RTCP /* [ */
void MprToNet::setRTPAccumulator(ISetSenderStatistics *piRTPAccumulator)
{
   mpiRTPAccumulator = piRTPAccumulator;
   if(mpiRTPAccumulator)
   {
       mpiRTPAccumulator->SetRTPTimestamp(mTimestampDelta);
   }
}

#endif /* INCLUDE_RTCP ] */

#ifdef DROP_SOME_PACKETS // [
static int dropLimit = 1<<30;
static int dropCount = 0;

extern "C" {
extern int dropEvery(int limit);
}

int dropEvery(int limit)
{
   int save = dropLimit;
   if (limit < 0) limit = 1<<30;
   if (limit > 0) {
      dropLimit = limit;
      dropCount = 0;
   }
   return save;
}
#endif // DROP_SOME_PACKETS ]

int MprToNet::writeRtp(int payloadType, UtlBoolean markerState,
                       const unsigned char* payloadData, int payloadOctets,
                       unsigned int timestamp, void* csrcList)
{
   MpRtpBufPtr pRtpPacket;
   char paddingLength;

   // Nothing to do when no socket specified.
   if (mpRtpSocket == NULL)
      return 0;

   // Allocate new RTP packet.
   pRtpPacket = MpMisc.RtpPool->getBuffer();
   assert(pRtpPacket.isValid());

   // Get rid of packet sequence number.
   mSeqNum++;

   // Fill packet RTP header.
   pRtpPacket->setRtpVersion(2);
   pRtpPacket->setRtpPayloadType(payloadType);
   pRtpPacket->setPayloadSize(payloadOctets);
   if (markerState)
      pRtpPacket->enableRtpMarker();
   else
      pRtpPacket->disableRtpMarker();
   pRtpPacket->disableRtpExtension();
   pRtpPacket->setRtpSequenceNumber(mSeqNum);
   pRtpPacket->setRtpTimestamp(mTimestampDelta + timestamp);
   pRtpPacket->setRtpSSRC(mSSRC);
   pRtpPacket->setRtpCSRCCount(0);

#ifdef ENABLE_PACKET_HACKING /* [ */
   adjustRtpPacket(pRtpPacket->getRtpHeader());
#endif /* ENABLE_PACKET_HACKING ] */

   // Calculate number of padding bytes
   paddingLength = doPadRtp ? ((4 - (payloadOctets & 3))&3) : 0;

   if (paddingLength>0)
      pRtpPacket->enableRtpPadding();
   else
      pRtpPacket->disableRtpPadding();

   if (csrcList != NULL)
   {
      int csrcSize = pRtpPacket->getRtpCSRCCount() * sizeof(RtpSRC);
      // TODO:: implement CSRC list.
      assert(csrcSize == 0);
   }

   //////////////////////////////////////////////////////
   // Next part of code should separated from previous //
   //////////////////////////////////////////////////////

   char *pBuf;
   unsigned int numBytesSent;
   MpUdpBufPtr pUdpPacket;

   // Allocate UDP packet
   pUdpPacket = MpMisc.UdpPool->getBuffer();
   pBuf = pUdpPacket->getDataWritePtr();

   // Set size of data to send
   assert(pUdpPacket->getMaximumPacketSize() >= sizeof(RtpHeader)+payloadOctets+paddingLength);
   pUdpPacket->setPacketSize(sizeof(RtpHeader)+payloadOctets+paddingLength);

   // Copy RTP header to UDP packet
   memcpy(pBuf, &pRtpPacket->getRtpHeader(), sizeof(RtpHeader));
   pBuf += sizeof(RtpHeader);

   // TODO:: Copy CSRC list here.

   // Copy payload to UDP packet
   memcpy(pBuf, payloadData, payloadOctets);
   pBuf += payloadOctets;

   // Fill padding
   switch (paddingLength) {
   case 3:
      pBuf[1] = 0;           // fall through
   case 2:
      pBuf[0] = 0;           // fall through
   case 1:
      pBuf[paddingLength-1] = paddingLength;  // fall through
   case 0:
      break;
   }

#ifdef INCLUDE_RTCP /* [ */
   // Update the Accumulated statistics kept for an inbound RTP packet.
   // These statistics comprise a Sender Report that is sent out periodically
   // to the originating site
   if(mpiRTPAccumulator)
   {
       mpiRTPAccumulator->IncrementCounts(payloadOctets);
   }
#endif /* INCLUDE_RTCP ] */

   const char* writeBytes = pUdpPacket->getDataPtr();
   int packetSize = pUdpPacket->getPacketSize();

#ifdef DROP_SOME_PACKETS /* [ */
   if (dropCount++ == dropLimit) {
      dropCount = 0;
      numBytesSent = pUdpPacket->getPacketSize();
   }
   // Socket can get set asynchronously to NULL when RTP send is stopped.  So check immediately before accessing socket.
   else if(mpRtpSocket)
   {
      numBytesSent = mpRtpSocket->write(writeBytes, packetSize);
   }
   else
   {
       numBytesSent = 0;
   }
#else /* DROP_SOME_PACKETS ] [*/

   // Socket can get set asynchronously to NULL when RTP send is stopped.  So check immediately before accessing socket.
   if(mpRtpSocket)
   {
      numBytesSent = mpRtpSocket->write(writeBytes, packetSize);
   }
   else
   {
       numBytesSent = 0;
   }
#endif /* DROP_SOME_PACKETS ] */

#ifdef TEST_PRINT
   UtlString remoteIp("null socket");
   int remotePort;
   if(mpRtpSocket)
   {
      mpRtpSocket->getRemoteHostIp(&remoteIp, &remotePort);
   }
   OsSysLog::add(FAC_MP, PRI_DEBUG, "MprToNet::writeRtp payload: %d send to address: %s port: %d numBytesSent: %d errno: %d",
      payloadType, remoteIp.data(), remotePort, numBytesSent, errno);
#endif

   if (numBytesSent != pUdpPacket->getPacketSize()) {
      switch (errno) {
         /* insert other benign errno values here */
            case 0:
            case 55: // Network disconnected, continue and hope it comes back
               break;
            default:
               // close(fd);  MAYBE: mpRtpSocket->close() ?
               // mpRtpSocket = NULL;
               break;
      }

   }
   return (pUdpPacket->getPacketSize() == numBytesSent) ? pUdpPacket->getPacketSize() : numBytesSent;
}

#ifdef ENABLE_PACKET_HACKING /* [ */
extern "C" {
extern int sTRA(int a, int b, int c);
extern int setToRtpAdjustment(int a, int b, int c);
};

int setToRtpAdjustment(int ssrc, int seq, int ts)
{
   MprToNet::sDebug1 = ssrc;
   MprToNet::sDebug2 = seq;
   MprToNet::sDebug3 = ts;
   return 0;
}

int sTRA(int a, int b, int c) {return setToRtpAdjustment(a,b,c);}
#endif /* ENABLE_PACKET_HACKING ] */

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

OsStatus MprToNet::setRtpPal(MprFromNet* pal)
{
   mpFromNetPal = pal;
   return OS_SUCCESS;
}

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

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

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

#ifdef ENABLE_PACKET_HACKING /* [ */
void MprToNet::adjustRtpPacket(struct RtpHeader* rp)
{
   struct RtpHeader rh;

   memcpy((char *) &rh, (char *) rp, sizeof(struct RtpHeader));
   // rh.vpxcc = rh.vpxcc;
   // rh.mpt = rh.mpt;
   rh.ssrc = ntohl(rh.ssrc) - sDebug1;
   rh.seq = ntohs(rh.seq) - sDebug2;
   rh.timestamp = ntohl(rh.timestamp) - sDebug3;
   rh.ssrc = htonl(rh.ssrc);
   rh.seq = htons(rh.seq);
   rh.timestamp = htonl(rh.timestamp);
   memcpy((char *) rp, (char *) &rh, sizeof(struct RtpHeader));
}
#endif /* ENABLE_PACKET_HACKING ] */

/* ============================ FUNCTIONS ================================= */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: QTableConnectionData.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: oj $ $Date: 2002-02-06 08:15:30 $
 *
 *  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 DBAUI_QTABLECONNECTIONDATA_HXX
#define DBAUI_QTABLECONNECTIONDATA_HXX

#ifndef DBAUI_TABLECONNECTIONDATA_HXX
#include "TableConnectionData.hxx"
#endif
#ifndef DBAUI_TABLEFIELDDESC_HXX
#include "TableFieldDescription.hxx"
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif
#ifndef _RTTI_HXX
#include <tools/rtti.hxx>
#endif
//#ifndef DBAUI_QUERYCONTROLLER_HXX
//#include "querycontroller.hxx"
//#endif

namespace dbaui
{
    class OQueryTableConnectionData : public OTableConnectionData
    {
        sal_Int32       m_nFromEntryIndex;
        sal_Int32       m_nDestEntryIndex;
        EJoinType       m_eJoinType;

        ETableFieldType m_eFromType;
        ETableFieldType m_eDestType;

        // meine Basisklasse merkt sich leider nur die Fensternamen (was hier das selbe wie die Aliasnamen ist), ich aber brauche
        // auch Zugriff auf die realen Tabellennamen. Damit ich mir nicht die Fenster dazu merken muss (das waere schmutzig, da die
        // TabConDatas normalerweise vom Dokument verwaltet werden und voellig losgeloest von der Repraesentation der Tabellen als
        // Fenster sein sollten), habe ich zwei ::rtl::OUString-Member
        ::rtl::OUString m_strSourceTableName;
        ::rtl::OUString m_strDestTableName;

    protected:
        // fuer das Anlegen und Duplizieren von Lines vom eigenen Typ
        virtual OConnectionLineDataRef CreateLineDataObj();
        virtual OConnectionLineDataRef CreateLineDataObj( const OConnectionLineData& rConnLineData );

        OQueryTableConnectionData& operator=( const OQueryTableConnectionData& rConnData );
    public:
        TYPEINFO();
        OQueryTableConnectionData();
        OQueryTableConnectionData( const OQueryTableConnectionData& rConnData );
        OQueryTableConnectionData( const ::rtl::OUString& strSourceTable, const ::rtl::OUString& strDestTable,
            const ::rtl::OUString& strSourceAlias, const ::rtl::OUString& strDestAlias, const ::rtl::OUString& rConnName=::rtl::OUString());
        virtual ~OQueryTableConnectionData();

        virtual void CopyFrom(const OTableConnectionData& rSource);
        virtual OTableConnectionData* NewInstance() const;

        /** Update create a new connection

            @return true if successful
        */
        virtual BOOL Update();

        ::rtl::OUString GetTableName(EConnectionSide nWhich) const;
        ::rtl::OUString GetAliasName(EConnectionSide nWhich) const;

        sal_Int32       GetFieldIndex(EConnectionSide nWhich) const { return nWhich==JTCS_TO ? m_nDestEntryIndex : m_nFromEntryIndex; }
        void            SetFieldIndex(EConnectionSide nWhich, sal_Int32 nVal) { if (nWhich==JTCS_TO) m_nDestEntryIndex=nVal; else m_nFromEntryIndex=nVal; }

        ETableFieldType GetFieldType(EConnectionSide nWhich) const { return nWhich==JTCS_TO ? m_eDestType : m_eFromType; }
        void            SetFieldType(EConnectionSide nWhich, ETableFieldType eType) { if (nWhich==JTCS_TO) m_eDestType=eType; else m_eFromType=eType; }

        void            InitFromDrag(const OTableFieldDescRef& rDragLeft, const OTableFieldDescRef& rDragRight);

        EJoinType       GetJoinType() const { return m_eJoinType; };
        void            SetJoinType(const EJoinType& eJT) { m_eJoinType = eJT; };

    };

}
#endif // DBAUI_QTABLECONNECTIONDATA_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.480); FILE MERGED 2005/09/05 17:35:29 rt 1.5.480.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: QTableConnectionData.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:21: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 DBAUI_QTABLECONNECTIONDATA_HXX
#define DBAUI_QTABLECONNECTIONDATA_HXX

#ifndef DBAUI_TABLECONNECTIONDATA_HXX
#include "TableConnectionData.hxx"
#endif
#ifndef DBAUI_TABLEFIELDDESC_HXX
#include "TableFieldDescription.hxx"
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif
#ifndef _RTTI_HXX
#include <tools/rtti.hxx>
#endif
//#ifndef DBAUI_QUERYCONTROLLER_HXX
//#include "querycontroller.hxx"
//#endif

namespace dbaui
{
    class OQueryTableConnectionData : public OTableConnectionData
    {
        sal_Int32       m_nFromEntryIndex;
        sal_Int32       m_nDestEntryIndex;
        EJoinType       m_eJoinType;

        ETableFieldType m_eFromType;
        ETableFieldType m_eDestType;

        // meine Basisklasse merkt sich leider nur die Fensternamen (was hier das selbe wie die Aliasnamen ist), ich aber brauche
        // auch Zugriff auf die realen Tabellennamen. Damit ich mir nicht die Fenster dazu merken muss (das waere schmutzig, da die
        // TabConDatas normalerweise vom Dokument verwaltet werden und voellig losgeloest von der Repraesentation der Tabellen als
        // Fenster sein sollten), habe ich zwei ::rtl::OUString-Member
        ::rtl::OUString m_strSourceTableName;
        ::rtl::OUString m_strDestTableName;

    protected:
        // fuer das Anlegen und Duplizieren von Lines vom eigenen Typ
        virtual OConnectionLineDataRef CreateLineDataObj();
        virtual OConnectionLineDataRef CreateLineDataObj( const OConnectionLineData& rConnLineData );

        OQueryTableConnectionData& operator=( const OQueryTableConnectionData& rConnData );
    public:
        TYPEINFO();
        OQueryTableConnectionData();
        OQueryTableConnectionData( const OQueryTableConnectionData& rConnData );
        OQueryTableConnectionData( const ::rtl::OUString& strSourceTable, const ::rtl::OUString& strDestTable,
            const ::rtl::OUString& strSourceAlias, const ::rtl::OUString& strDestAlias, const ::rtl::OUString& rConnName=::rtl::OUString());
        virtual ~OQueryTableConnectionData();

        virtual void CopyFrom(const OTableConnectionData& rSource);
        virtual OTableConnectionData* NewInstance() const;

        /** Update create a new connection

            @return true if successful
        */
        virtual BOOL Update();

        ::rtl::OUString GetTableName(EConnectionSide nWhich) const;
        ::rtl::OUString GetAliasName(EConnectionSide nWhich) const;

        sal_Int32       GetFieldIndex(EConnectionSide nWhich) const { return nWhich==JTCS_TO ? m_nDestEntryIndex : m_nFromEntryIndex; }
        void            SetFieldIndex(EConnectionSide nWhich, sal_Int32 nVal) { if (nWhich==JTCS_TO) m_nDestEntryIndex=nVal; else m_nFromEntryIndex=nVal; }

        ETableFieldType GetFieldType(EConnectionSide nWhich) const { return nWhich==JTCS_TO ? m_eDestType : m_eFromType; }
        void            SetFieldType(EConnectionSide nWhich, ETableFieldType eType) { if (nWhich==JTCS_TO) m_eDestType=eType; else m_eFromType=eType; }

        void            InitFromDrag(const OTableFieldDescRef& rDragLeft, const OTableFieldDescRef& rDragRight);

        EJoinType       GetJoinType() const { return m_eJoinType; };
        void            SetJoinType(const EJoinType& eJT) { m_eJoinType = eJT; };

    };

}
#endif // DBAUI_QTABLECONNECTIONDATA_HXX
<|endoftext|>


<commit_before>/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

#include <typeinfo>

#include <geos/geom/util/CoordinateOperation.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/LinearRing.h>
#include <geos/geom/LineString.h>
#include <geos/geom/Point.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/GeometryFactory.h>

namespace geos {
namespace geom { // geos.geom
namespace util { // geos.geom.util

Geometry*
CoordinateOperation::edit(const Geometry *geometry,
		const GeometryFactory *factory)
{
		const LinearRing *ring = dynamic_cast<const LinearRing *>(geometry);
		if (ring) {
			const CoordinateSequence *coords = ring->getCoordinatesRO();
			CoordinateSequence *newCoords = edit(coords,geometry);
            // LinearRing instance takes over ownership of newCoords instance
			return factory->createLinearRing(newCoords);
		}
		const LineString *line = dynamic_cast<const LineString *>(geometry);
		if (line) {
			const CoordinateSequence *coords = line->getCoordinatesRO();
			CoordinateSequence *newCoords = edit(coords,geometry);
			return factory->createLineString(newCoords);
		}
		if (typeid(*geometry)==typeid(Point)) {
			CoordinateSequence *coords = geometry->getCoordinates();
			CoordinateSequence *newCoords = edit(coords,geometry);
			delete coords;
			return factory->createPoint(newCoords);
		}

		return geometry->clone();
}

} // namespace geos.geom.util
} // namespace geos.geom
} // namespace geos
<commit_msg>Windows: workaround Visual Studio 2015 bug: error C2614: 'std::bad_typeid', https://connect.microsoft.com/VisualStudio/feedback/details/1600701/type-info-does-not-compile-with-has-exceptions-0<commit_after>/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

#ifndef _WIN32
#include <typeinfo>
#endif

#include <geos/geom/util/CoordinateOperation.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/LinearRing.h>
#include <geos/geom/LineString.h>
#include <geos/geom/Point.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/GeometryFactory.h>

namespace geos {
namespace geom { // geos.geom
namespace util { // geos.geom.util

Geometry*
CoordinateOperation::edit(const Geometry *geometry,
		const GeometryFactory *factory)
{
		const LinearRing *ring = dynamic_cast<const LinearRing *>(geometry);
		if (ring) {
			const CoordinateSequence *coords = ring->getCoordinatesRO();
			CoordinateSequence *newCoords = edit(coords,geometry);
            // LinearRing instance takes over ownership of newCoords instance
			return factory->createLinearRing(newCoords);
		}
		const LineString *line = dynamic_cast<const LineString *>(geometry);
		if (line) {
			const CoordinateSequence *coords = line->getCoordinatesRO();
			CoordinateSequence *newCoords = edit(coords,geometry);
			return factory->createLineString(newCoords);
		}
		if (typeid(*geometry)==typeid(Point)) {
			CoordinateSequence *coords = geometry->getCoordinates();
			CoordinateSequence *newCoords = edit(coords,geometry);
			delete coords;
			return factory->createPoint(newCoords);
		}

		return geometry->clone();
}

} // namespace geos.geom.util
} // namespace geos.geom
} // namespace geos
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////////
// Name:        VIAGDALOptionsDlg.cpp
// Author:      XX
// Created:     XX/XX/XX
// Copyright:   XX
/////////////////////////////////////////////////////////////////////////////

#ifdef __GNUG__
    #pragma implementation "VIAGDALOptionsDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#include "VIAGDALOptionsDlg.h"
#include <gdal_priv.h>
#include "vtlib/vtlib.h"
#include <wx/filename.h>
#include <wx/stdpaths.h>

// WDR: class implementations

//----------------------------------------------------------------------------
// CVIAGDALOptionsDlg
//----------------------------------------------------------------------------

CVIAGDALOptionsDlg::CVIAGDALOptionsDlg( wxWindow *parent) : VIAGDALOptionsDlgBase(parent)
{
    m_ScaleFactor = wxString::Format(_("%0.2f"), 1.0);
	m_XSampleInterval = wxString::Format(_("%0.2f"), 10.0);
	m_YSampleInterval = wxString::Format(_("%0.2f"), 10.0);
}

void CVIAGDALOptionsDlg::Setup(int iDriverIndex)
{
    GDALDriver *pDriver = GetGDALDriverManager()->GetDriver(iDriverIndex);
    wxString DataTypes(pDriver->GetMetadataItem(GDAL_DMD_CREATIONDATATYPES), wxConvUTF8);
	wxFileName HelpTopic(wxStandardPaths::Get().GetConfigDir(), wxEmptyString);
#ifdef __WXMSW__
	HelpTopic.RemoveLastDir(); // Strip off the app name appended by wxWindows
#endif
	HelpTopic.AppendDir(wxT("VirtualOutlooks"));
	HelpTopic.AppendDir(wxT("CommonData"));
    HelpTopic.AppendDir(wxT("frmts"));
    HelpTopic.SetFullName(wxString(pDriver->GetMetadataItem(GDAL_DMD_HELPTOPIC), wxConvUTF8));
    char *pToken;
	int iPos;

	if (HelpTopic.FileExists())
		m_pHtmlWindow->LoadPage(HelpTopic.GetFullPath());

    pToken = strtok((char *)DataTypes.GetData(), " ");
    while( pToken != NULL )
    {
        m_pDataTypeChoice->Append(wxString(pToken, wxConvUTF8));
        pToken = strtok( NULL, " ");
    }
	if (-1 != (iPos = m_pDataTypeChoice->FindString(wxT("Float32"))))
		m_pDataTypeChoice->SetSelection(iPos);
	else
		m_pDataTypeChoice->SetSelection(0);
}

<commit_msg>Changed path for GDAL html help files.<commit_after>/////////////////////////////////////////////////////////////////////////////
// Name:        VIAGDALOptionsDlg.cpp
// Author:      XX
// Created:     XX/XX/XX
// Copyright:   XX
/////////////////////////////////////////////////////////////////////////////

#ifdef __GNUG__
    #pragma implementation "VIAGDALOptionsDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#include "VIAGDALOptionsDlg.h"
#include <gdal_priv.h>
#include "vtlib/vtlib.h"
#include <wx/filename.h>
#include <wx/stdpaths.h>

// WDR: class implementations

//----------------------------------------------------------------------------
// CVIAGDALOptionsDlg
//----------------------------------------------------------------------------

CVIAGDALOptionsDlg::CVIAGDALOptionsDlg( wxWindow *parent) : VIAGDALOptionsDlgBase(parent)
{
    m_ScaleFactor = wxString::Format(_("%0.2f"), 1.0);
	m_XSampleInterval = wxString::Format(_("%0.2f"), 10.0);
	m_YSampleInterval = wxString::Format(_("%0.2f"), 10.0);
}

void CVIAGDALOptionsDlg::Setup(int iDriverIndex)
{
    GDALDriver *pDriver = GetGDALDriverManager()->GetDriver(iDriverIndex);
    wxString DataTypes(pDriver->GetMetadataItem(GDAL_DMD_CREATIONDATATYPES), wxConvUTF8);
	wxFileName HelpTopic(wxStandardPaths::Get().GetConfigDir(), wxEmptyString);
#ifdef __WXMSW__
	HelpTopic.RemoveLastDir(); // Strip off the app name appended by wxWindows
#endif
	HelpTopic.AppendDir(wxT("VTP"));
	HelpTopic.AppendDir(wxT("CommonData"));
    HelpTopic.AppendDir(wxT("frmts"));
    HelpTopic.SetFullName(wxString(pDriver->GetMetadataItem(GDAL_DMD_HELPTOPIC), wxConvUTF8));
    char *pToken;
	int iPos;

	if (HelpTopic.FileExists())
		m_pHtmlWindow->LoadPage(HelpTopic.GetFullPath());

    pToken = strtok((char *)DataTypes.GetData(), " ");
    while( pToken != NULL )
    {
        m_pDataTypeChoice->Append(wxString(pToken, wxConvUTF8));
        pToken = strtok( NULL, " ");
    }
	if (-1 != (iPos = m_pDataTypeChoice->FindString(wxT("Float32"))))
		m_pDataTypeChoice->SetSelection(iPos);
	else
		m_pDataTypeChoice->SetSelection(0);
}

<|endoftext|>


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

#include "thunder/tensor.hpp"

#include <random>

#include "gtest/gtest.h"
#include "thunder/storage.hpp"

namespace thunder {
namespace {

template< typename T >
void sortTest() {
  ::std::random_device rd;
  ::std::mt19937 gen(rd());
  ::std::uniform_real_distribution< double > dist(-1.0, 1.0);

  T t1(10, 20, 7);
  Tensor< typename T::size_storage > t1_index;

  for (typename T::reference_iterator begin = t1.reference_begin(),
           end = t1.reference_end(); begin != end; ++begin) {
    *begin = static_cast< typename T::value_type >(dist(gen));
  }

  T t1_sorted = T::sort(t1, 1);
  for (int i = 0; i < t1.size(0); ++i) {
    for (int j = 0; j < t1.size(1) - 1; ++j) {
      for (int k = 0; k < t1.size(2); ++k) {
        EXPECT_LE(t1_sorted(i, j, k), t1_sorted(i, j + 1, k));
      }
    }
  }

  T t1_revert = T::sort(t1, 1, true);
  for (int i = 0; i < t1.size(0); ++i) {
    for (int j = 0; j < t1.size(1) - 1; ++j) {
      for (int k = 0; k < t1.size(2); ++k) {
        EXPECT_GE(t1_revert(i, j, k), t1_revert(i, j + 1, k));
      }
    }
  }

  t1_sorted = T::sort(t1, 1, &t1_index);
  for (int i = 0; i < t1.dimension(); ++i) {
    EXPECT_EQ(t1_index.size(i), t1.size(i));
  }
  for (int i = 0; i < t1.size(0); ++i) {
    for (int j = 0; j < t1.size(1); ++j) {
      for (int k = 0; k < t1.size(2); ++k) {
        EXPECT_FLOAT_EQ(t1_sorted(i, j, k), t1(i, t1_index(i, j, k), k));
      }
    }
  }
  for (int i = 0; i < t1.size(0); ++i) {
    for (int j = 0; j < t1.size(1) - 1; ++j) {
      for (int k = 0; k < t1.size(2); ++k) {
        EXPECT_LE(t1_sorted(i, j, k), t1_sorted(i, j + 1, k));
      }
    }
  }

  t1_revert = T::sort(t1, 1, &t1_index, true);
  for (int i = 0; i < t1.dimension(); ++i) {
    EXPECT_EQ(t1_index.size(i), t1.size(i));
  }
  for (int i = 0; i < t1.size(0); ++i) {
    for (int j = 0; j < t1.size(1); ++j) {
      for (int k = 0; k < t1.size(2); ++k) {
        EXPECT_FLOAT_EQ(t1_revert(i, j, k), t1(i, t1_index(i, j, k), k));
      }
    }
  }
  for (int i = 0; i < t1.size(0); ++i) {
    for (int j = 0; j < t1.size(1) - 1; ++j) {
      for (int k = 0; k < t1.size(2); ++k) {
        EXPECT_GE(t1_revert(i, j, k), t1_revert(i, j + 1, k));
      }
    }
  }

  T t2({3, 10, 20, 7}, {5200, 408, 19, 2});
  Tensor< typename T::size_storage > t2_index;

  for (typename T::reference_iterator begin = t2.reference_begin(),
           end = t2.reference_end(); begin != end; ++begin) {
    *begin = static_cast< typename T::value_type >(dist(gen));
  }

  T t2_sorted = T::sort(t2, 2);
  for (int l = 0; l < t2.size(0); ++l) {
    for (int i = 0; i < t2.size(1); ++i) {
      for (int j = 0; j < t2.size(2) - 1; ++j) {
        for (int k = 0; k < t2.size(3); ++k) {
          EXPECT_LE(t2_sorted(l, i, j, k), t2_sorted(l, i, j + 1, k));
        }
      }
    }
  }

  T t2_revert = T::sort(t2, 2, true);
  for (int l = 0; l < t2.size(0); ++l) {
    for (int i = 0; i < t2.size(1); ++i) {
      for (int j = 0; j < t2.size(2) - 1; ++j) {
        for (int k = 0; k < t2.size(3); ++k) {
          EXPECT_GE(t2_revert(l, i, j, k), t2_revert(l, i, j + 1, k));
        }
      }
    }
  }

  t2_sorted = T::sort(t2, 2, &t2_index);
  for (int i = 0; i < t2.dimension(); ++i) {
    EXPECT_EQ(t2_index.size(i), t2.size(i));
  }
  for (int l = 0; l < t2.size(0); ++l) {
    for (int i = 0; i < t2.size(1); ++i) {
      for (int j = 0; j < t2.size(2); ++j) {
        for (int k = 0; k < t2.size(3); ++k) {
          EXPECT_FLOAT_EQ(
              t2_sorted(l, i, j, k), t2(l, i, t2_index(l, i, j, k), k));
        }
      }
    }
  }
  for (int l = 0; l < t2.size(0); ++l) {
    for (int i = 0; i < t2.size(1); ++i) {
      for (int j = 0; j < t2.size(2) - 1; ++j) {
        for (int k = 0; k < t2.size(3); ++k) {
          EXPECT_LE(t2_sorted(l, i, j, k), t2_sorted(l, i, j + 1, k));
        }
      }
    }
  }

  t2_revert = T::sort(t2, 2, &t2_index, true);
  for (int i = 0; i < t2.dimension(); ++i) {
    EXPECT_EQ(t2_index.size(i), t2.size(i));
  }
  for (int l = 0; l < t2.size(0); ++l) {
    for (int i = 0; i < t2.size(1); ++i) {
      for (int j = 0; j < t2.size(2); ++j) {
        for (int k = 0; k < t2.size(3); ++k) {
          EXPECT_FLOAT_EQ(
              t2_revert(l, i, j, k), t2(l, i, t2_index(l, i, j, k), k));
        }
      }
    }
  }
  for (int l = 0; l < t2.size(0); ++l) {
    for (int i = 0; i < t2.size(1); ++i) {
      for (int j = 0; j < t2.size(2) - 1; ++j) {
        for (int k = 0; k < t2.size(3); ++k) {
          EXPECT_GE(t2_revert(l, i, j, k), t2_revert(l, i, j + 1, k));
        }
      }
    }
  }
}

TEST(TensorTest, sortTest) {
  sortTest< DoubleTensor >();
  sortTest< FloatTensor >();
}

}  // namespace
}  // namespace thunder
<commit_msg>Fixing header issue<commit_after>/*
 * \copyright Copyright 2014 - 2015 Xiang Zhang All Rights Reserved.
 * \license @{
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @}
 */

#include "thunder/tensor.hpp"

#include <random>

#include "gtest/gtest.h"

namespace thunder {
namespace {

template< typename T >
void sortTest() {
  ::std::random_device rd;
  ::std::mt19937 gen(rd());
  ::std::uniform_real_distribution< double > dist(-1.0, 1.0);

  T t1(10, 20, 7);
  Tensor< typename T::size_storage > t1_index;

  for (typename T::reference_iterator begin = t1.reference_begin(),
           end = t1.reference_end(); begin != end; ++begin) {
    *begin = static_cast< typename T::value_type >(dist(gen));
  }

  T t1_sorted = T::sort(t1, 1);
  for (int i = 0; i < t1.size(0); ++i) {
    for (int j = 0; j < t1.size(1) - 1; ++j) {
      for (int k = 0; k < t1.size(2); ++k) {
        EXPECT_LE(t1_sorted(i, j, k), t1_sorted(i, j + 1, k));
      }
    }
  }

  T t1_revert = T::sort(t1, 1, true);
  for (int i = 0; i < t1.size(0); ++i) {
    for (int j = 0; j < t1.size(1) - 1; ++j) {
      for (int k = 0; k < t1.size(2); ++k) {
        EXPECT_GE(t1_revert(i, j, k), t1_revert(i, j + 1, k));
      }
    }
  }

  t1_sorted = T::sort(t1, 1, &t1_index);
  for (int i = 0; i < t1.dimension(); ++i) {
    EXPECT_EQ(t1_index.size(i), t1.size(i));
  }
  for (int i = 0; i < t1.size(0); ++i) {
    for (int j = 0; j < t1.size(1); ++j) {
      for (int k = 0; k < t1.size(2); ++k) {
        EXPECT_FLOAT_EQ(t1_sorted(i, j, k), t1(i, t1_index(i, j, k), k));
      }
    }
  }
  for (int i = 0; i < t1.size(0); ++i) {
    for (int j = 0; j < t1.size(1) - 1; ++j) {
      for (int k = 0; k < t1.size(2); ++k) {
        EXPECT_LE(t1_sorted(i, j, k), t1_sorted(i, j + 1, k));
      }
    }
  }

  t1_revert = T::sort(t1, 1, &t1_index, true);
  for (int i = 0; i < t1.dimension(); ++i) {
    EXPECT_EQ(t1_index.size(i), t1.size(i));
  }
  for (int i = 0; i < t1.size(0); ++i) {
    for (int j = 0; j < t1.size(1); ++j) {
      for (int k = 0; k < t1.size(2); ++k) {
        EXPECT_FLOAT_EQ(t1_revert(i, j, k), t1(i, t1_index(i, j, k), k));
      }
    }
  }
  for (int i = 0; i < t1.size(0); ++i) {
    for (int j = 0; j < t1.size(1) - 1; ++j) {
      for (int k = 0; k < t1.size(2); ++k) {
        EXPECT_GE(t1_revert(i, j, k), t1_revert(i, j + 1, k));
      }
    }
  }

  T t2({3, 10, 20, 7}, {5200, 408, 19, 2});
  Tensor< typename T::size_storage > t2_index;

  for (typename T::reference_iterator begin = t2.reference_begin(),
           end = t2.reference_end(); begin != end; ++begin) {
    *begin = static_cast< typename T::value_type >(dist(gen));
  }

  T t2_sorted = T::sort(t2, 2);
  for (int l = 0; l < t2.size(0); ++l) {
    for (int i = 0; i < t2.size(1); ++i) {
      for (int j = 0; j < t2.size(2) - 1; ++j) {
        for (int k = 0; k < t2.size(3); ++k) {
          EXPECT_LE(t2_sorted(l, i, j, k), t2_sorted(l, i, j + 1, k));
        }
      }
    }
  }

  T t2_revert = T::sort(t2, 2, true);
  for (int l = 0; l < t2.size(0); ++l) {
    for (int i = 0; i < t2.size(1); ++i) {
      for (int j = 0; j < t2.size(2) - 1; ++j) {
        for (int k = 0; k < t2.size(3); ++k) {
          EXPECT_GE(t2_revert(l, i, j, k), t2_revert(l, i, j + 1, k));
        }
      }
    }
  }

  t2_sorted = T::sort(t2, 2, &t2_index);
  for (int i = 0; i < t2.dimension(); ++i) {
    EXPECT_EQ(t2_index.size(i), t2.size(i));
  }
  for (int l = 0; l < t2.size(0); ++l) {
    for (int i = 0; i < t2.size(1); ++i) {
      for (int j = 0; j < t2.size(2); ++j) {
        for (int k = 0; k < t2.size(3); ++k) {
          EXPECT_FLOAT_EQ(
              t2_sorted(l, i, j, k), t2(l, i, t2_index(l, i, j, k), k));
        }
      }
    }
  }
  for (int l = 0; l < t2.size(0); ++l) {
    for (int i = 0; i < t2.size(1); ++i) {
      for (int j = 0; j < t2.size(2) - 1; ++j) {
        for (int k = 0; k < t2.size(3); ++k) {
          EXPECT_LE(t2_sorted(l, i, j, k), t2_sorted(l, i, j + 1, k));
        }
      }
    }
  }

  t2_revert = T::sort(t2, 2, &t2_index, true);
  for (int i = 0; i < t2.dimension(); ++i) {
    EXPECT_EQ(t2_index.size(i), t2.size(i));
  }
  for (int l = 0; l < t2.size(0); ++l) {
    for (int i = 0; i < t2.size(1); ++i) {
      for (int j = 0; j < t2.size(2); ++j) {
        for (int k = 0; k < t2.size(3); ++k) {
          EXPECT_FLOAT_EQ(
              t2_revert(l, i, j, k), t2(l, i, t2_index(l, i, j, k), k));
        }
      }
    }
  }
  for (int l = 0; l < t2.size(0); ++l) {
    for (int i = 0; i < t2.size(1); ++i) {
      for (int j = 0; j < t2.size(2) - 1; ++j) {
        for (int k = 0; k < t2.size(3); ++k) {
          EXPECT_GE(t2_revert(l, i, j, k), t2_revert(l, i, j + 1, k));
        }
      }
    }
  }
}

TEST(TensorTest, sortTest) {
  sortTest< DoubleTensor >();
  sortTest< FloatTensor >();
}

}  // namespace
}  // namespace thunder
<|endoftext|>


<commit_before>/*
 * TransposeConnTest.cpp
 *
 *  Created on: Jul 31, 2013
 *      Author: Pete Schultz
 */

/*
 * test_transpose_transpose.cpp
 *
 * Tests whether TransposeConn transposes the weights correctly by taking
 * the transpose twice and checking whether the result is identical to the
 * original.  Based on an old unit test that stopped getting maintained.
 */

#include <float.h>
#include <columns/buildandrun.hpp>

using namespace PV;

int testTransposeOfTransposeWeights(KernelConn * originalMap, TransposeConn * transpose, TransposeConn * transposeOfTranspose, const char * message);
int testWeightsEqual(HyPerConn * conn1, HyPerConn * conn2);
int testPatchesEqual(PVPatch * patch1, PVPatch * patch2, int index, const char * conn1name, const char * conn2name);
int verifyEqual(int val1, int val2, const char * description, const char * name1, const char * name2, int status_in);
int testDataPatchEqual(pvdata_t * w1, pvdata_t * w2, int patchSize, const char * name1, const char * name2, int status_in);
int dumpWeights(KernelConn * kconn, FILE * stream);

int main(int argc, char * argv[]) {
   InterColComm * icComm = new InterColComm(&argc, &argv);
   PVParams * params = new PVParams("input/TransposeConnTest.params", 2*(INITIAL_LAYER_ARRAY_SIZE+INITIAL_CONNECTION_ARRAY_SIZE), icComm);

   // Don't call buildandrun because it will delete hc before returning. (I could use the customexit hook)
   HyPerCol * hc = build(argc, argv, NULL, params);
   hc->run(0); // Weight values are initialized when run calls allocateDataStructures

   int status = PV_SUCCESS;

   KernelConn * originalMap = NULL;
   TransposeConn * transpose = NULL;
   TransposeConn * transposeOfTranspose = NULL;

   originalMap = dynamic_cast<KernelConn *>(hc->getConnFromName("Original Map for One to One Test"));
   transpose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose for One to One Test of TransposeConn"));
   transposeOfTranspose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose of Transpose for One to One Test of TransposeConn"));
   status = testTransposeOfTransposeWeights(originalMap, transpose, transposeOfTranspose, "One-to-one case, TransposeConn");

   originalMap = dynamic_cast<KernelConn *>(hc->getConnFromName("Original Map for Many to One Test"));
   transpose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose for Many to One Test of TransposeConn"));
   transposeOfTranspose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose of Transpose for Many to One Test of TransposeConn"));
   status = testTransposeOfTransposeWeights(originalMap, transpose, transposeOfTranspose, "Many-to-one case, TransposeConn");

   originalMap = dynamic_cast<KernelConn *>(hc->getConnFromName("Original Map for One to Many Test"));
   transpose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose for One to Many Test of TransposeConn"));
   transposeOfTranspose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose of Transpose for One to Many Test of TransposeConn"));
   status = testTransposeOfTransposeWeights(originalMap, transpose, transposeOfTranspose, "One-to-many case, TransposeConn");

   originalMap = dynamic_cast<KernelConn *>(hc->getConnFromName("Original Map for One to One Test"));
   transpose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose for One to One Test of FeedbackConn"));
   transposeOfTranspose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose of Transpose for One to One Test of FeedbackConn"));
   status = testTransposeOfTransposeWeights(originalMap, transpose, transposeOfTranspose, "One-to-one case, FeedbackConn");

   originalMap = dynamic_cast<KernelConn *>(hc->getConnFromName("Original Map for Many to One Test"));
   transpose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose for Many to One Test of FeedbackConn"));
   transposeOfTranspose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose of Transpose for Many to One Test of FeedbackConn"));
   status = testTransposeOfTransposeWeights(originalMap, transpose, transposeOfTranspose, "Many-to-one case, FeedbackConn");

   originalMap = dynamic_cast<KernelConn *>(hc->getConnFromName("Original Map for One to Many Test"));
   transpose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose for One to Many Test of FeedbackConn"));
   transposeOfTranspose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose of Transpose for One to Many Test of FeedbackConn"));
   status = testTransposeOfTransposeWeights(originalMap, transpose, transposeOfTranspose, "One-to-many case, FeedbackConn");

   delete hc;
   return status;
}

int manyToOneForTransposeConn(int argc, char * argv[]) {
   HyPerCol * hc = new HyPerCol("column", argc, argv);
   // Layers
   const char * layerAname = "Layer A";
   const char * layerB1to1name = "Layer B One to one";
   const char * layerB_ManyTo1Name = "Layer B Many to one";
   const char * layerB1toManyName = "Layer B One to many";
   const char * originalConnName = "Many to one original map";
   const char * transposeConnName = "Many to one transpose";
   const char * transposeOfTransposeConnName = "Many to one double transpose";

   ANNLayer * layerA = new ANNLayer(layerAname, hc);
   assert(layerA);
   ANNLayer * layerB_ManyTo1 = new ANNLayer(layerB_ManyTo1Name, hc);
   assert(layerB_ManyTo1);
   new ANNLayer(layerB1to1name, hc); // This layer and the next are unused in this test, but get created anyway
   new ANNLayer(layerB1toManyName, hc); // to cause the params to be read, so we don't get unused-parameter warnings.

   // Connections
   InitWeights * initwgt = new InitUniformRandomWeights();
   KernelConn * originalMapManyto1 = new KernelConn(originalConnName, hc, layerAname, layerB_ManyTo1Name, NULL, initwgt);
   assert(originalMapManyto1);
   TransposeConn * transposeManyto1 = new TransposeConn(transposeConnName, hc, layerB_ManyTo1Name, layerAname, originalConnName);
   assert(transposeManyto1);
   TransposeConn * transposeOfTransposeManyto1 = new TransposeConn(transposeOfTransposeConnName, hc, layerAname, layerB_ManyTo1Name, transposeConnName);
   assert(transposeOfTransposeManyto1);

   hc->run(0); // Weight values are initialized when run calls allocateDataStructures

   int status = testTransposeOfTransposeWeights(originalMapManyto1, transposeManyto1, transposeOfTransposeManyto1, "Many-to-one case, TransposeConn");
   delete hc;
   return status;
}

int testTransposeOfTransposeWeights(KernelConn * originalMap, TransposeConn * transpose, TransposeConn * transposeOfTranspose, const char * message) {
   int status = testWeightsEqual(originalMap, transposeOfTranspose);
   if( status == PV_SUCCESS ) {
      printf("%s: TestTransposeConn passed.\n", message);
   }
   else {
      fprintf(stderr, "%s: TestTransposeConn failed.\n", message);
      dumpWeights(originalMap, stdout);
      dumpWeights(transpose, stdout);
      dumpWeights(transposeOfTranspose, stdout);
   }
   return status;
}

int testWeightsEqual(HyPerConn * conn1, HyPerConn * conn2) {
   int status = PV_SUCCESS;

   status = verifyEqual(conn1->xPatchSize(), conn2->xPatchSize(), "nxp", conn1->getName(), conn2->getName(), status);
   status = verifyEqual(conn1->yPatchSize(), conn2->yPatchSize(), "nyp", conn1->getName(), conn2->getName(), status);
   status = verifyEqual(conn1->fPatchSize(), conn2->fPatchSize(), "nfp", conn1->getName(), conn2->getName(), status);
   status = verifyEqual(conn1->numberOfAxonalArborLists(), conn2->numberOfAxonalArborLists(), "numAxonalArbors", conn1->getName(), conn2->getName(), status);
   status = verifyEqual(conn1->getNumWeightPatches(), conn2->getNumWeightPatches(), "numWeightPatches", conn1->getName(), conn2->getName(), status);
   status = verifyEqual(conn1->getNumDataPatches(), conn2->getNumDataPatches(), "numDataPatches", conn1->getName(), conn2->getName(), status);

   if (status != PV_SUCCESS) return status;

   int numWeightPatches = conn1->getNumWeightPatches();
   assert(numWeightPatches == conn2->getNumWeightPatches());
   for( int patchindex = 0; patchindex < numWeightPatches; patchindex++ ) {
      int status1 = testPatchesEqual( conn1->getWeights(patchindex, LOCAL), conn2->getWeights(patchindex, LOCAL), patchindex, conn1->getName(), conn2->getName());
      if( status1 != PV_SUCCESS ) {
         status = status1;
         break;
      }
   }

   if (status != PV_SUCCESS) return status;

   int numArbors = conn1->numberOfAxonalArborLists();
   assert(numArbors == conn2->numberOfAxonalArborLists());
   int numDataPatches = conn1->getNumDataPatches();
   assert(numDataPatches == conn2->getNumDataPatches());
   int patchSize = conn1->xPatchSize()*conn1->yPatchSize()*conn1->fPatchSize();
   assert(patchSize == conn2->xPatchSize()*conn2->yPatchSize()*conn2->fPatchSize());
   for (int arbor=0; arbor<numArbors; arbor++) {
      for (int dataindex = 0; dataindex < numDataPatches; dataindex++) {
         pvdata_t * w1 = conn1->get_wDataStart(arbor)+patchSize*dataindex;
         pvdata_t * w2 = conn2->get_wDataStart(arbor)+patchSize*dataindex;
         status = testDataPatchEqual(w1, w2, patchSize, conn1->getName(), conn2->getName(), status);
         if (status != PV_SUCCESS) break;
      }
   }
   return status;
}

int testPatchesEqual(PVPatch * patch1, PVPatch * patch2, int index, const char * conn1name, const char * conn2name) {
   int status = PV_SUCCESS;
   status = verifyEqual(patch1->nx, patch2->nx, "nx", conn1name, conn2name, status);
   status = verifyEqual(patch1->ny, patch2->ny, "ny", conn1name, conn2name, status);
   status = verifyEqual(patch1->offset, patch2->offset, "offset", conn1name, conn2name, status);

   return status;
}

int verifyEqual(int val1, int val2, const char * description, const char * name1, const char * name2, int status_in) {
   int status_out = status_in;
   if (val1 != val2) {
      fprintf(stderr, "TransposeConnTest: %s of \"%s\" and \"%s\" are not equal (%d versus %d).\n", description, name1, name2, val1, val2);
      status_out = PV_FAILURE;
   }
   return status_out;
}

int testDataPatchEqual(pvdata_t * w1, pvdata_t * w2, int patchSize, const char * name1, const char * name2, int status_in) {
   int status_out = status_in;
   for (int w=0; w<patchSize; w++) {
      if (w1[w] != w2[w]) {
         fprintf(stderr, "TransposeConnTest: value %d of \"%s\" and \"%s\" are not equal (%f versus %f).\n", w, name1, name2, w1[w], w2[w]);
         status_out = PV_FAILURE;
         if (status_out != PV_SUCCESS) break;
      }
   }
   return status_out;
}

int dumpWeights(KernelConn * kconn, FILE * stream) {
   fprintf(stream, "Dumping weights for connection %s\n", kconn->getName() );
   int nxp = kconn->xPatchSize();
   int nyp = kconn->yPatchSize();
   int nfp = kconn->fPatchSize();
   int numArbors = kconn->numberOfAxonalArborLists();
   fprintf(stream, "    nxp = %d, nyp = %d, nfp = %d, numAxonalArbors = %d\n",
           nxp, nyp, nfp, numArbors);
   int numPatches = kconn->getNumWeightPatches();
   for (int arbor=0; arbor<numArbors; arbor++) {
      for(int kn = 0; kn < numPatches; kn++) {
         PVPatch * kp = kconn->getWeights(kn, 0);
         int nx = kp->nx;
         int ny = kp->ny;
         int offset = kp->offset;
         fprintf(stream, "    Weight Patch %d: nx=%d, ny=%d, offset=%d\n",
               kn, nx, ny, offset);
      }
   }
   int numDataPatches = kconn->getNumDataPatches();
   for (int arbor=0; arbor<numArbors; arbor++) {
      for(int n=0; n<numDataPatches; n++) {
         for(int k=0; k<nxp*nyp*nfp; k++) {
            fprintf(stream, "    Arbor %d, Data Patch %d, Index %4d, (x=%3d, y=%3d, f=%3d): Value %g\n",
                    arbor, n, k, kxPos(k, nxp, nyp, nfp), kyPos(k, nxp, nyp, nfp),
                    featureIndex(k, nxp, nyp, nfp), kconn->get_wData(arbor, n)[k]);
         }
      }
   }
   return PV_SUCCESS;
}
<commit_msg>Fix memory leak in TransposeConnTest<commit_after>/*
 * TransposeConnTest.cpp
 *
 *  Created on: Jul 31, 2013
 *      Author: Pete Schultz
 */

/*
 * test_transpose_transpose.cpp
 *
 * Tests whether TransposeConn transposes the weights correctly by taking
 * the transpose twice and checking whether the result is identical to the
 * original.  Based on an old unit test that stopped getting maintained.
 */

#include <float.h>
#include <columns/buildandrun.hpp>

using namespace PV;

int testTransposeOfTransposeWeights(KernelConn * originalMap, TransposeConn * transpose, TransposeConn * transposeOfTranspose, const char * message);
int testWeightsEqual(HyPerConn * conn1, HyPerConn * conn2);
int testPatchesEqual(PVPatch * patch1, PVPatch * patch2, int index, const char * conn1name, const char * conn2name);
int verifyEqual(int val1, int val2, const char * description, const char * name1, const char * name2, int status_in);
int testDataPatchEqual(pvdata_t * w1, pvdata_t * w2, int patchSize, const char * name1, const char * name2, int status_in);
int dumpWeights(KernelConn * kconn, FILE * stream);

int main(int argc, char * argv[]) {
   InterColComm * icComm = new InterColComm(&argc, &argv);
   PVParams * params = new PVParams("input/TransposeConnTest.params", 2*(INITIAL_LAYER_ARRAY_SIZE+INITIAL_CONNECTION_ARRAY_SIZE), icComm);

   // Don't call buildandrun because it will delete hc before returning. (I could use the customexit hook)
   HyPerCol * hc = build(argc, argv, NULL, params);
   hc->run(0); // Weight values are initialized when run calls allocateDataStructures

   int status = PV_SUCCESS;

   KernelConn * originalMap = NULL;
   TransposeConn * transpose = NULL;
   TransposeConn * transposeOfTranspose = NULL;

   originalMap = dynamic_cast<KernelConn *>(hc->getConnFromName("Original Map for One to One Test"));
   transpose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose for One to One Test of TransposeConn"));
   transposeOfTranspose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose of Transpose for One to One Test of TransposeConn"));
   status = testTransposeOfTransposeWeights(originalMap, transpose, transposeOfTranspose, "One-to-one case, TransposeConn");

   originalMap = dynamic_cast<KernelConn *>(hc->getConnFromName("Original Map for Many to One Test"));
   transpose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose for Many to One Test of TransposeConn"));
   transposeOfTranspose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose of Transpose for Many to One Test of TransposeConn"));
   status = testTransposeOfTransposeWeights(originalMap, transpose, transposeOfTranspose, "Many-to-one case, TransposeConn");

   originalMap = dynamic_cast<KernelConn *>(hc->getConnFromName("Original Map for One to Many Test"));
   transpose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose for One to Many Test of TransposeConn"));
   transposeOfTranspose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose of Transpose for One to Many Test of TransposeConn"));
   status = testTransposeOfTransposeWeights(originalMap, transpose, transposeOfTranspose, "One-to-many case, TransposeConn");

   originalMap = dynamic_cast<KernelConn *>(hc->getConnFromName("Original Map for One to One Test"));
   transpose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose for One to One Test of FeedbackConn"));
   transposeOfTranspose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose of Transpose for One to One Test of FeedbackConn"));
   status = testTransposeOfTransposeWeights(originalMap, transpose, transposeOfTranspose, "One-to-one case, FeedbackConn");

   originalMap = dynamic_cast<KernelConn *>(hc->getConnFromName("Original Map for Many to One Test"));
   transpose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose for Many to One Test of FeedbackConn"));
   transposeOfTranspose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose of Transpose for Many to One Test of FeedbackConn"));
   status = testTransposeOfTransposeWeights(originalMap, transpose, transposeOfTranspose, "Many-to-one case, FeedbackConn");

   originalMap = dynamic_cast<KernelConn *>(hc->getConnFromName("Original Map for One to Many Test"));
   transpose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose for One to Many Test of FeedbackConn"));
   transposeOfTranspose = dynamic_cast<TransposeConn *>(hc->getConnFromName("Transpose of Transpose for One to Many Test of FeedbackConn"));
   status = testTransposeOfTransposeWeights(originalMap, transpose, transposeOfTranspose, "One-to-many case, FeedbackConn");

   delete hc;
   delete icComm;
   return status;
}

int manyToOneForTransposeConn(int argc, char * argv[]) {
   HyPerCol * hc = new HyPerCol("column", argc, argv);
   // Layers
   const char * layerAname = "Layer A";
   const char * layerB1to1name = "Layer B One to one";
   const char * layerB_ManyTo1Name = "Layer B Many to one";
   const char * layerB1toManyName = "Layer B One to many";
   const char * originalConnName = "Many to one original map";
   const char * transposeConnName = "Many to one transpose";
   const char * transposeOfTransposeConnName = "Many to one double transpose";

   ANNLayer * layerA = new ANNLayer(layerAname, hc);
   assert(layerA);
   ANNLayer * layerB_ManyTo1 = new ANNLayer(layerB_ManyTo1Name, hc);
   assert(layerB_ManyTo1);
   new ANNLayer(layerB1to1name, hc); // This layer and the next are unused in this test, but get created anyway
   new ANNLayer(layerB1toManyName, hc); // to cause the params to be read, so we don't get unused-parameter warnings.

   // Connections
   InitWeights * initwgt = new InitUniformRandomWeights();
   KernelConn * originalMapManyto1 = new KernelConn(originalConnName, hc, layerAname, layerB_ManyTo1Name, NULL, initwgt);
   assert(originalMapManyto1);
   TransposeConn * transposeManyto1 = new TransposeConn(transposeConnName, hc, layerB_ManyTo1Name, layerAname, originalConnName);
   assert(transposeManyto1);
   TransposeConn * transposeOfTransposeManyto1 = new TransposeConn(transposeOfTransposeConnName, hc, layerAname, layerB_ManyTo1Name, transposeConnName);
   assert(transposeOfTransposeManyto1);

   hc->run(0); // Weight values are initialized when run calls allocateDataStructures

   int status = testTransposeOfTransposeWeights(originalMapManyto1, transposeManyto1, transposeOfTransposeManyto1, "Many-to-one case, TransposeConn");
   delete hc;
   return status;
}

int testTransposeOfTransposeWeights(KernelConn * originalMap, TransposeConn * transpose, TransposeConn * transposeOfTranspose, const char * message) {
   int status = testWeightsEqual(originalMap, transposeOfTranspose);
   if( status == PV_SUCCESS ) {
      printf("%s: TestTransposeConn passed.\n", message);
   }
   else {
      fprintf(stderr, "%s: TestTransposeConn failed.\n", message);
      dumpWeights(originalMap, stdout);
      dumpWeights(transpose, stdout);
      dumpWeights(transposeOfTranspose, stdout);
   }
   return status;
}

int testWeightsEqual(HyPerConn * conn1, HyPerConn * conn2) {
   int status = PV_SUCCESS;

   status = verifyEqual(conn1->xPatchSize(), conn2->xPatchSize(), "nxp", conn1->getName(), conn2->getName(), status);
   status = verifyEqual(conn1->yPatchSize(), conn2->yPatchSize(), "nyp", conn1->getName(), conn2->getName(), status);
   status = verifyEqual(conn1->fPatchSize(), conn2->fPatchSize(), "nfp", conn1->getName(), conn2->getName(), status);
   status = verifyEqual(conn1->numberOfAxonalArborLists(), conn2->numberOfAxonalArborLists(), "numAxonalArbors", conn1->getName(), conn2->getName(), status);
   status = verifyEqual(conn1->getNumWeightPatches(), conn2->getNumWeightPatches(), "numWeightPatches", conn1->getName(), conn2->getName(), status);
   status = verifyEqual(conn1->getNumDataPatches(), conn2->getNumDataPatches(), "numDataPatches", conn1->getName(), conn2->getName(), status);

   if (status != PV_SUCCESS) return status;

   int numWeightPatches = conn1->getNumWeightPatches();
   assert(numWeightPatches == conn2->getNumWeightPatches());
   for( int patchindex = 0; patchindex < numWeightPatches; patchindex++ ) {
      int status1 = testPatchesEqual( conn1->getWeights(patchindex, LOCAL), conn2->getWeights(patchindex, LOCAL), patchindex, conn1->getName(), conn2->getName());
      if( status1 != PV_SUCCESS ) {
         status = status1;
         break;
      }
   }

   if (status != PV_SUCCESS) return status;

   int numArbors = conn1->numberOfAxonalArborLists();
   assert(numArbors == conn2->numberOfAxonalArborLists());
   int numDataPatches = conn1->getNumDataPatches();
   assert(numDataPatches == conn2->getNumDataPatches());
   int patchSize = conn1->xPatchSize()*conn1->yPatchSize()*conn1->fPatchSize();
   assert(patchSize == conn2->xPatchSize()*conn2->yPatchSize()*conn2->fPatchSize());
   for (int arbor=0; arbor<numArbors; arbor++) {
      for (int dataindex = 0; dataindex < numDataPatches; dataindex++) {
         pvdata_t * w1 = conn1->get_wDataStart(arbor)+patchSize*dataindex;
         pvdata_t * w2 = conn2->get_wDataStart(arbor)+patchSize*dataindex;
         status = testDataPatchEqual(w1, w2, patchSize, conn1->getName(), conn2->getName(), status);
         if (status != PV_SUCCESS) break;
      }
   }
   return status;
}

int testPatchesEqual(PVPatch * patch1, PVPatch * patch2, int index, const char * conn1name, const char * conn2name) {
   int status = PV_SUCCESS;
   status = verifyEqual(patch1->nx, patch2->nx, "nx", conn1name, conn2name, status);
   status = verifyEqual(patch1->ny, patch2->ny, "ny", conn1name, conn2name, status);
   status = verifyEqual(patch1->offset, patch2->offset, "offset", conn1name, conn2name, status);

   return status;
}

int verifyEqual(int val1, int val2, const char * description, const char * name1, const char * name2, int status_in) {
   int status_out = status_in;
   if (val1 != val2) {
      fprintf(stderr, "TransposeConnTest: %s of \"%s\" and \"%s\" are not equal (%d versus %d).\n", description, name1, name2, val1, val2);
      status_out = PV_FAILURE;
   }
   return status_out;
}

int testDataPatchEqual(pvdata_t * w1, pvdata_t * w2, int patchSize, const char * name1, const char * name2, int status_in) {
   int status_out = status_in;
   for (int w=0; w<patchSize; w++) {
      if (w1[w] != w2[w]) {
         fprintf(stderr, "TransposeConnTest: value %d of \"%s\" and \"%s\" are not equal (%f versus %f).\n", w, name1, name2, w1[w], w2[w]);
         status_out = PV_FAILURE;
         if (status_out != PV_SUCCESS) break;
      }
   }
   return status_out;
}

int dumpWeights(KernelConn * kconn, FILE * stream) {
   fprintf(stream, "Dumping weights for connection %s\n", kconn->getName() );
   int nxp = kconn->xPatchSize();
   int nyp = kconn->yPatchSize();
   int nfp = kconn->fPatchSize();
   int numArbors = kconn->numberOfAxonalArborLists();
   fprintf(stream, "    nxp = %d, nyp = %d, nfp = %d, numAxonalArbors = %d\n",
           nxp, nyp, nfp, numArbors);
   int numPatches = kconn->getNumWeightPatches();
   for (int arbor=0; arbor<numArbors; arbor++) {
      for(int kn = 0; kn < numPatches; kn++) {
         PVPatch * kp = kconn->getWeights(kn, 0);
         int nx = kp->nx;
         int ny = kp->ny;
         int offset = kp->offset;
         fprintf(stream, "    Weight Patch %d: nx=%d, ny=%d, offset=%d\n",
               kn, nx, ny, offset);
      }
   }
   int numDataPatches = kconn->getNumDataPatches();
   for (int arbor=0; arbor<numArbors; arbor++) {
      for(int n=0; n<numDataPatches; n++) {
         for(int k=0; k<nxp*nyp*nfp; k++) {
            fprintf(stream, "    Arbor %d, Data Patch %d, Index %4d, (x=%3d, y=%3d, f=%3d): Value %g\n",
                    arbor, n, k, kxPos(k, nxp, nyp, nfp), kyPos(k, nxp, nyp, nfp),
                    featureIndex(k, nxp, nyp, nfp), kconn->get_wData(arbor, n)[k]);
         }
      }
   }
   return PV_SUCCESS;
}
<|endoftext|>


<commit_before> //
 // This file is part of Easylogging++ samples
 // Post log dispatch handler
 //
 // Revision 1.0
 // @author mkhan3189
 //

#define _ELPP_HANDLE_POST_LOG_DISPATCH
#include "easylogging++.h"

_INITIALIZE_EASYLOGGINGPP

void handler(const el::LogMessage*) {
    // NOTE:
    // SHOULD NOT LOG ANYTHING HERE! WE DON'T LIKE RECURSIVE LOG-DISPATCHES!

    // BUT WE CAN USE std::cout :)
    std::cout << "Log dispatch has been handled";
}

int main(void) {

    el::Helpers::installPostLogDispatchHandler(handler);

    LOG(INFO) << "My log message";

    return 0;
}
<commit_msg>post-log-dispatch sample improved<commit_after> //
 // This file is part of Easylogging++ samples
 // Post log dispatch handler
 //
 // Revision 1.0
 // @author mkhan3189
 //

#define _ELPP_HANDLE_POST_LOG_DISPATCH
#include "easylogging++.h"

_INITIALIZE_EASYLOGGINGPP

static std::vector<std::string> log_messages_dispatched;

void handler(const el::LogMessage* msg) {
    // NOTE:
    // SHOULD NOT LOG ANYTHING HERE! WE DON'T LIKE RECURSIVE LOG-DISPATCHES!

    // BUT WE CAN USE std::cout :)
    log_messages_dispatched.push_back(msg->message());

    // Also note, this msg pointer will become unavailable as soon as this handler is done.
    // so there will be no point of having a vector like std::vector<el::LogMessage*> and store these pointers
}

int main(void) {

    el::Helpers::installPostLogDispatchHandler(handler);

    LOG(INFO) << "This is my first message";
    LOG(INFO) << "I am second in the line";

    std::cout << std::endl; // Just enter an empty line to make it more readable

    LOG(INFO) << "Following log messages have been dispatched so far! \n\t" << log_messages_dispatched;
    return 0;
}
<|endoftext|>