<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: documentdefinition.hxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: ihi $ $Date: 2007-04-16 16:24:46 $
 *
 *  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 _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_
#define _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_

#ifndef _CPPUHELPER_PROPSHLP_HXX
#include <cppuhelper/propshlp.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _DBA_REGHELPER_HXX_
#include "dba_reghelper.hxx"
#endif
#ifndef DBA_CONTENTHELPER_HXX
#include "ContentHelper.hxx"
#endif
#ifndef COMPHELPER_PROPERTYSTATECONTAINER_HXX
#include <comphelper/propertystatecontainer.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCOMPONENTLOADER_HPP_
#include <com/sun/star/frame/XComponentLoader.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XSTATECHANGELISTENER_HPP_
#include <com/sun/star/embed/XStateChangeListener.hpp>
#endif

//........................................................................
namespace dbaccess
{
//........................................................................

    class OInterceptor;
    class OEmbeddedClientHelper;
//==========================================================================
//= ODocumentDefinition - a database "document" which is simply a link to a real
//=                   document
//==========================================================================

    typedef ::cppu::ImplHelper1<        ::com::sun::star::embed::XComponentSupplier
                                >   ODocumentDefinition_Base;

class ODocumentDefinition
        :public OContentHelper
        ,public ::comphelper::OPropertyStateContainer
        ,public ::comphelper::OPropertyArrayUsageHelper< ODocumentDefinition >
        ,public ODocumentDefinition_Base
{
    ::com::sun::star::uno::Reference< ::com::sun::star::embed::XEmbeddedObject>         m_xEmbeddedObject;
    ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStateChangeListener >   m_xListener;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFramesSupplier >        m_xDesktop;
    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >             m_xLastKnownConnection;

    OInterceptor*                                                                       m_pInterceptor;
    sal_Bool                                                                            m_bForm; // <TRUE/> if it is a form
    sal_Bool                                                                            m_bOpenInDesign;
    sal_Bool                                                                            m_bInExecute;
    OEmbeddedClientHelper*                                                              m_pClientHelper;

private:
    // Command "insert"
    void insert( const ::rtl::OUString& _sURL, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& Environment ) throw( ::com::sun::star::uno::Exception );

    /** fills the load arguments
    *
    * \param _rArgs
    * \param _rEmbeddedObjectDescriptor
    */
    void fillLoadArgs(::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rArgs
                    , ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rEmbeddedObjectDescriptor
                    ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection
                    ,sal_Bool _bReadOnly);
    /** loads the EmbeddedObject if not already loaded
        @param  _aClassID
            If set, it will be used to create the embedded object.
    */
    void loadEmbeddedObject(const ::com::sun::star::uno::Sequence< sal_Int8 >& _aClassID = ::com::sun::star::uno::Sequence< sal_Int8 >()
                            ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection = ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>()
                            ,sal_Bool _bReadOnly = sal_False);

    void generateNewImage(::com::sun::star::uno::Any& _rImage);
    void fillDocumentInfo(::com::sun::star::uno::Any& _rInfo);
    /** searches for read-only flag in the args of the model and sets it to the given value,
        if the value was not found, it will be appended.
        @param  _bReadOnly
            If <TRUE/> the document will be switched to readonly mode
    */
    void setModelReadOnly(sal_Bool _bReadOnly);
    void updateDocumentTitle();
protected:
    virtual ~ODocumentDefinition();

public:

    ODocumentDefinition(
             const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContainer
            ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&
            ,const TContentPtr& _pImpl
            ,sal_Bool _bForm
            ,const ::com::sun::star::uno::Sequence< sal_Int8 >& _aClassID = ::com::sun::star::uno::Sequence< sal_Int8 >()
            ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection = ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>()
        );

// com::sun::star::lang::XTypeProvider
    DECLARE_TYPEPROVIDER( );

// ::com::sun::star::uno::XInterface
    DECLARE_XINTERFACE( )

// ::com::sun::star::lang::XServiceInfo
    DECLARE_SERVICE_INFO_STATIC();

// ::com::sun::star::beans::XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);

    // XComponentSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloseable > SAL_CALL getComponent(  ) throw (::com::sun::star::uno::RuntimeException);

// OPropertySetHelper
    virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

    // XCommandProcessor
    virtual ::com::sun::star::uno::Any SAL_CALL execute( const ::com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& Environment ) throw (::com::sun::star::uno::Exception, ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException) ;

    // XRename
    virtual void SAL_CALL rename( const ::rtl::OUString& newName ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage> getStorage() const;

    sal_Bool save(sal_Bool _bApprove);
    void closeObject();
    sal_Bool isModified();
    void fillReportData(sal_Bool _bFill = sal_True);

    /** prepares closing the document component

        The method suspends the controller associated with the document, and saves the document
        if necessary.

        @return
            <TRUE/> if and only if the document component can be closed
    */
    bool prepareClose();

    static ::com::sun::star::uno::Sequence< sal_Int8 > getDefaultDocumentTypeClassId();

    /** does necessary initializations after our embedded object has been switched to ACTIVE
        @param _bOpenedInDesignMode
            determines whether the embedded object has been opened for designing it or for data display
    */
    void impl_onActivateEmbeddedObject( bool _bOpenedInDesignMode );

    /** initializes a newly created view/controller which is displaying our embedded object

        Has only to be called if the respective embedded object has been loaded for design (and
        not for data entry)

        @param  _rxController
            the controller which belongs to the XModel of our (active) embedded object
    */
    void impl_initObjectEditView( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController >& _rxController );

    /** appends the given frame to the frames collection of our database document's current controller
    */
    void impl_appendFrameToDocumentFrames_throw( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxFrame );

    /** removes the given frame from the desktop's frame collection
        @raises ::com::sun::star::uno::RuntimeException
    */
    void impl_removeFrameFromDesktop_throw( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxFrame );

protected:
    // OPropertyArrayUsageHelper
    virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;

    virtual void getPropertyDefaultByHandle( sal_Int32 _nHandle, ::com::sun::star::uno::Any& _rDefault ) const;
    // helper
    virtual void SAL_CALL disposing();

private:
    void registerProperties();

};

//........................................................................
}   // namespace dbaccess
//........................................................................

#endif // _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_

<commit_msg>INTEGRATION: CWS dba23a (1.18.84); FILE MERGED 2007/02/26 11:48:07 fs 1.18.84.1: remove unused code Issue number:  #i74804# Submitted by:  jnavrati@openoffice.org Reviewed by:   frank.schoenheit@sun.com<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: documentdefinition.hxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 10:12:58 $
 *
 *  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 _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_
#define _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_

#ifndef _CPPUHELPER_PROPSHLP_HXX
#include <cppuhelper/propshlp.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _DBA_REGHELPER_HXX_
#include "dba_reghelper.hxx"
#endif
#ifndef DBA_CONTENTHELPER_HXX
#include "ContentHelper.hxx"
#endif
#ifndef COMPHELPER_PROPERTYSTATECONTAINER_HXX
#include <comphelper/propertystatecontainer.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCOMPONENTLOADER_HPP_
#include <com/sun/star/frame/XComponentLoader.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XSTATECHANGELISTENER_HPP_
#include <com/sun/star/embed/XStateChangeListener.hpp>
#endif

//........................................................................
namespace dbaccess
{
//........................................................................

    class OInterceptor;
    class OEmbeddedClientHelper;
//==========================================================================
//= ODocumentDefinition - a database "document" which is simply a link to a real
//=                   document
//==========================================================================

    typedef ::cppu::ImplHelper1<        ::com::sun::star::embed::XComponentSupplier
                                >   ODocumentDefinition_Base;

class ODocumentDefinition
        :public OContentHelper
        ,public ::comphelper::OPropertyStateContainer
        ,public ::comphelper::OPropertyArrayUsageHelper< ODocumentDefinition >
        ,public ODocumentDefinition_Base
{
    ::com::sun::star::uno::Reference< ::com::sun::star::embed::XEmbeddedObject>         m_xEmbeddedObject;
    ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStateChangeListener >   m_xListener;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFramesSupplier >        m_xDesktop;
    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >             m_xLastKnownConnection;

    OInterceptor*                                                                       m_pInterceptor;
    sal_Bool                                                                            m_bForm; // <TRUE/> if it is a form
    sal_Bool                                                                            m_bOpenInDesign;
    sal_Bool                                                                            m_bInExecute;
    OEmbeddedClientHelper*                                                              m_pClientHelper;

private:
    // Command "insert"
    void insert( const ::rtl::OUString& _sURL, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& Environment ) throw( ::com::sun::star::uno::Exception );

    /** fills the load arguments
    *
    * \param _rArgs
    * \param _rEmbeddedObjectDescriptor
    */
    void fillLoadArgs(::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rArgs
                    , ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rEmbeddedObjectDescriptor
                    ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection
                    ,sal_Bool _bReadOnly);
    /** loads the EmbeddedObject if not already loaded
        @param  _aClassID
            If set, it will be used to create the embedded object.
    */
    void loadEmbeddedObject(const ::com::sun::star::uno::Sequence< sal_Int8 >& _aClassID = ::com::sun::star::uno::Sequence< sal_Int8 >()
                            ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection = ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>()
                            ,sal_Bool _bReadOnly = sal_False);

    void generateNewImage(::com::sun::star::uno::Any& _rImage);
    void fillDocumentInfo(::com::sun::star::uno::Any& _rInfo);
    /** searches for read-only flag in the args of the model and sets it to the given value,
        if the value was not found, it will be appended.
        @param  _bReadOnly
            If <TRUE/> the document will be switched to readonly mode
    */
    void updateDocumentTitle();
protected:
    virtual ~ODocumentDefinition();

public:

    ODocumentDefinition(
             const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContainer
            ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&
            ,const TContentPtr& _pImpl
            ,sal_Bool _bForm
            ,const ::com::sun::star::uno::Sequence< sal_Int8 >& _aClassID = ::com::sun::star::uno::Sequence< sal_Int8 >()
            ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection = ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>()
        );

// com::sun::star::lang::XTypeProvider
    DECLARE_TYPEPROVIDER( );

// ::com::sun::star::uno::XInterface
    DECLARE_XINTERFACE( )

// ::com::sun::star::lang::XServiceInfo
    DECLARE_SERVICE_INFO_STATIC();

// ::com::sun::star::beans::XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);

    // XComponentSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloseable > SAL_CALL getComponent(  ) throw (::com::sun::star::uno::RuntimeException);

// OPropertySetHelper
    virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

    // XCommandProcessor
    virtual ::com::sun::star::uno::Any SAL_CALL execute( const ::com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& Environment ) throw (::com::sun::star::uno::Exception, ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException) ;

    // XRename
    virtual void SAL_CALL rename( const ::rtl::OUString& newName ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage> getStorage() const;

    sal_Bool save(sal_Bool _bApprove);
    void closeObject();
    sal_Bool isModified();
    void fillReportData(sal_Bool _bFill = sal_True);

    /** prepares closing the document component

        The method suspends the controller associated with the document, and saves the document
        if necessary.

        @return
            <TRUE/> if and only if the document component can be closed
    */
    bool prepareClose();

    static ::com::sun::star::uno::Sequence< sal_Int8 > getDefaultDocumentTypeClassId();

    /** does necessary initializations after our embedded object has been switched to ACTIVE
        @param _bOpenedInDesignMode
            determines whether the embedded object has been opened for designing it or for data display
    */
    void impl_onActivateEmbeddedObject( bool _bOpenedInDesignMode );

    /** initializes a newly created view/controller which is displaying our embedded object

        Has only to be called if the respective embedded object has been loaded for design (and
        not for data entry)

        @param  _rxController
            the controller which belongs to the XModel of our (active) embedded object
    */
    void impl_initObjectEditView( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController >& _rxController );

    /** appends the given frame to the frames collection of our database document's current controller
    */
    void impl_appendFrameToDocumentFrames_throw( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxFrame );

    /** removes the given frame from the desktop's frame collection
        @raises ::com::sun::star::uno::RuntimeException
    */
    void impl_removeFrameFromDesktop_throw( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxFrame );

protected:
    // OPropertyArrayUsageHelper
    virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;

    virtual void getPropertyDefaultByHandle( sal_Int32 _nHandle, ::com::sun::star::uno::Any& _rDefault ) const;
    // helper
    virtual void SAL_CALL disposing();

private:
    void registerProperties();

};

//........................................................................
}   // namespace dbaccess
//........................................................................

#endif // _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_

<|endoftext|>


<commit_before>// $Id: Socket_test.C,v 1.3 1999/11/24 14:54:25 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/SYSTEM/socket.h>
///////////////////////////

START_TEST(Socket, "$Id: Socket_test.C,v 1.3 1999/11/24 14:54:25 oliver Exp $")
using namespace BALL;

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>added: first test - transparent transmission if one character between   two forked processes<commit_after>// $Id: Socket_test.C,v 1.4 2000/01/14 20:34:48 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/SYSTEM/socket.h>
#include <unistd.h>
///////////////////////////

START_TEST(Socket, "$Id: Socket_test.C,v 1.4 2000/01/14 20:34:48 oliver Exp $")
using namespace BALL;

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

CHECK(simple socket transmission)
SockInetBuf sock_inet_buf(SocketBuf::sock_stream);
sock_inet_buf.bind();
char c;
int port = sock_inet_buf.localport();
STATUS("localport = " << sock_inet_buf.localport())
STATUS("localhost = " << sock_inet_buf.localhost())
if (fork())
{
	STATUS("A:listen...")
  sock_inet_buf.listen();
	STATUS("A:accept...")
  IOStreamSocket  s(sock_inet_buf.accept());
	STATUS("A:get...")
	s.get(c);
	STATUS("S:done")
} else {
	sleep(1);
	IOStreamSocket  sio(SocketBuf::sock_stream);
	int result = sio->connect(sock_inet_buf.localhost(), port);
	STATUS("B:connect = " << result)
	sio.put((char)123);
	STATUS("B:done.")
	return 0;
}
TEST_EQUAL((int)c, (int)123);
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>


<commit_before>/**
 * \file
 * \brief SignalsQueuedOperationsTestCase class implementation
 *
 * \author Copyright (C) 2015-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "SignalsQueuedOperationsTestCase.hpp"

#include "signalsTestSelfOneSignalPending.hpp"

#include "distortos/DynamicThread.hpp"
#include "distortos/ThisThread-Signals.hpp"

#include <cerrno>

namespace distortos
{

namespace test
{

namespace
{

/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/

/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {512};

/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/

/**
 * \brief Phase 1 of test case.
 *
 * The same signal number is queued multiple times for current thread (with increasing signal value) until EAGAIN error
 * code is returned, which means that all space for queuing of signals is used. The same number of calls to
 * ThisThread::Signals::tryWait() must succeed and signal value contained in received SignalInformation object must
 * match expected values.
 *
 * \return true if test succeeded, false otherwise
 */

bool phase1()
{
#if defined(CONFIG_MAIN_THREAD_QUEUED_SIGNALS) && CONFIG_MAIN_THREAD_QUEUED_SIGNALS > 0

	constexpr uint8_t testSignalNumber {30};
	int testValue {};

	{
		int ret;
		while ((ret = ThisThread::Signals::queueSignal(testSignalNumber, sigval{testValue})) == 0)
		{
			++testValue;
			if (signalsTestSelfOneSignalPending(testSignalNumber) == false)
				return false;
		}

		if (ret != EAGAIN)
			return false;
	}

	const SignalSet signalSet {SignalSet::full};
	for (decltype(testValue) expectedValue {}; expectedValue < testValue; ++expectedValue)
	{
		if (signalsTestSelfOneSignalPending(testSignalNumber) == false)	// the queued signal must still be pending
			return false;

		const auto tryWaitResult = ThisThread::Signals::tryWait(signalSet);
		if (tryWaitResult.first != 0)
			return false;

		auto& signalInformation = tryWaitResult.second;
		if (signalInformation.getSignalNumber() != testSignalNumber ||
				signalInformation.getCode() != SignalInformation::Code::queued ||
				signalInformation.getValue().sival_int != expectedValue)
			return false;
	}

	// after the test no signals may be pending
	if (ThisThread::Signals::getPendingSignalSet().getBitset().none() == false)
		return false;

#endif	// defined(CONFIG_MAIN_THREAD_QUEUED_SIGNALS) && CONFIG_MAIN_THREAD_QUEUED_SIGNALS > 0

	return true;
}

/**
 * \brief Phase 2 of test case.
 *
 * Tests error cases specific to queuing of signals:
 * - attempt to queue a signal to thread that has enabled reception of signals but disabled queuing of signals must fail
 * with ENOTSUP;
 *
 * \return true if test succeeded, false otherwise
 */

bool phase2()
{
	{
		auto testThread = makeDynamicThread({testThreadStackSize, true, 0, 0, {}}, [](){});
		if (testThread.queueSignal({}, {}) != ENOTSUP)
			return false;
	}

	return true;
}

}	// namespace

/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/

bool SignalsQueuedOperationsTestCase::run_() const
{
	for (const auto& function : {phase1, phase2})
	{
		// initially no signals may be pending
		if (ThisThread::Signals::getPendingSignalSet().getBitset().none() == false)
			return false;

		if (function() == false)
			return false;
	}

	// after the test no signals may be pending
	if (ThisThread::Signals::getPendingSignalSet().getBitset().none() == false)
		return false;

	return true;
}

}	// namespace test

}	// namespace distortos
<commit_msg>Disable SignalsQueuedOperationsTestCase if signals are disabled<commit_after>/**
 * \file
 * \brief SignalsQueuedOperationsTestCase class implementation
 *
 * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "SignalsQueuedOperationsTestCase.hpp"

#include "distortos/distortosConfiguration.h"

#if CONFIG_SIGNALS_ENABLE == 1

#include "signalsTestSelfOneSignalPending.hpp"

#include "distortos/DynamicThread.hpp"
#include "distortos/ThisThread-Signals.hpp"

#include <cerrno>

#endif	// CONFIG_SIGNALS_ENABLE == 1

namespace distortos
{

namespace test
{

#if CONFIG_SIGNALS_ENABLE == 1

namespace
{

/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/

/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {512};

/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/

/**
 * \brief Phase 1 of test case.
 *
 * The same signal number is queued multiple times for current thread (with increasing signal value) until EAGAIN error
 * code is returned, which means that all space for queuing of signals is used. The same number of calls to
 * ThisThread::Signals::tryWait() must succeed and signal value contained in received SignalInformation object must
 * match expected values.
 *
 * \return true if test succeeded, false otherwise
 */

bool phase1()
{
#if defined(CONFIG_MAIN_THREAD_QUEUED_SIGNALS) && CONFIG_MAIN_THREAD_QUEUED_SIGNALS > 0

	constexpr uint8_t testSignalNumber {30};
	int testValue {};

	{
		int ret;
		while ((ret = ThisThread::Signals::queueSignal(testSignalNumber, sigval{testValue})) == 0)
		{
			++testValue;
			if (signalsTestSelfOneSignalPending(testSignalNumber) == false)
				return false;
		}

		if (ret != EAGAIN)
			return false;
	}

	const SignalSet signalSet {SignalSet::full};
	for (decltype(testValue) expectedValue {}; expectedValue < testValue; ++expectedValue)
	{
		if (signalsTestSelfOneSignalPending(testSignalNumber) == false)	// the queued signal must still be pending
			return false;

		const auto tryWaitResult = ThisThread::Signals::tryWait(signalSet);
		if (tryWaitResult.first != 0)
			return false;

		auto& signalInformation = tryWaitResult.second;
		if (signalInformation.getSignalNumber() != testSignalNumber ||
				signalInformation.getCode() != SignalInformation::Code::queued ||
				signalInformation.getValue().sival_int != expectedValue)
			return false;
	}

	// after the test no signals may be pending
	if (ThisThread::Signals::getPendingSignalSet().getBitset().none() == false)
		return false;

#endif	// defined(CONFIG_MAIN_THREAD_QUEUED_SIGNALS) && CONFIG_MAIN_THREAD_QUEUED_SIGNALS > 0

	return true;
}

/**
 * \brief Phase 2 of test case.
 *
 * Tests error cases specific to queuing of signals:
 * - attempt to queue a signal to thread that has enabled reception of signals but disabled queuing of signals must fail
 * with ENOTSUP;
 *
 * \return true if test succeeded, false otherwise
 */

bool phase2()
{
	{
		auto testThread = makeDynamicThread({testThreadStackSize, true, 0, 0, {}}, [](){});
		if (testThread.queueSignal({}, {}) != ENOTSUP)
			return false;
	}

	return true;
}

}	// namespace

#endif	// CONFIG_SIGNALS_ENABLE == 1

/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/

bool SignalsQueuedOperationsTestCase::run_() const
{
#if CONFIG_SIGNALS_ENABLE == 1

	for (const auto& function : {phase1, phase2})
	{
		// initially no signals may be pending
		if (ThisThread::Signals::getPendingSignalSet().getBitset().none() == false)
			return false;

		if (function() == false)
			return false;
	}

	// after the test no signals may be pending
	if (ThisThread::Signals::getPendingSignalSet().getBitset().none() == false)
		return false;

#endif	// CONFIG_SIGNALS_ENABLE == 1

	return true;
}

}	// namespace test

}	// namespace distortos
<|endoftext|>


<commit_before><commit_msg>Resolving merge on set_relation.cc.  Removed normalizeR.<commit_after><|endoftext|>


<commit_before>/****************************
** Tsunagari Tile Engine   **
** timeout.cpp             **
** Copyright 2012 OmegaSDG **
****************************/

#include <list>

#include "python.h"
#include "timeout.h"
#include "window.h"

static std::list<Timeout*> timeouts;

static Timeout* pythonSetTimeout(boost::python::object callback, int delay)
{
	int now = GameWindow::instance().time();
	int end = now + delay;

	// Insert sorted by resolution time.
	std::list<Timeout*>::iterator it;
	for (it = timeouts.begin(); it != timeouts.end(); it++) {
		Timeout* t = *it;
		if (end < t->readyTime())
			break;
	}

	Timeout* t = new Timeout(callback, delay);
	timeouts.insert(it, t);
	return t;
}

Timeout::Timeout(boost::python::object callback, int delay)
	: callback(callback),
	  start(GameWindow::instance().time()),
	  delay(delay),
	  active(true)
{
}

void Timeout::cancel()
{
	active = false;
}

bool Timeout::isActive()
{
	return active;
}

bool Timeout::ready(int now)
{
	return now > start + delay;
}

int Timeout::readyTime()
{
	return start + delay;
}

void Timeout::execute()
{
	try {
		callback();
	} catch (boost::python::error_already_set) {
		pythonErr();
	}
}

void updateTimeouts()
{
	int now = GameWindow::instance().time();
	bool next = true;

	while (next && timeouts.size()) {
		Timeout* t = timeouts.front();
		if (!t->isActive()) {
			timeouts.pop_front();
			delete t;
		}
		else if (t->ready(now)) {
			t->execute();
			timeouts.pop_front();
			delete t;
		}
		else {
			next = false;
		}
	}
}

void exportTimeout()
{
	using namespace boost::python;

	class_<Timeout> ("Timeout", no_init)
		.def("cancel", &Timeout::cancel)
		;

	pythonAddFunction("timeout", make_function(pythonSetTimeout,
		return_value_policy<reference_existing_object>()));
}

<commit_msg>Py: timeout(): delay is a float<commit_after>/****************************
** Tsunagari Tile Engine   **
** timeout.cpp             **
** Copyright 2012 OmegaSDG **
****************************/

#include <list>

#include "python.h"
#include "timeout.h"
#include "window.h"

static std::list<Timeout*> timeouts;

static Timeout* pythonSetTimeout(boost::python::object callback, float delay)
{
	int now = GameWindow::instance().time();
	int end = now + (int)(1000 * delay);

	// Insert sorted by resolution time.
	std::list<Timeout*>::iterator it;
	for (it = timeouts.begin(); it != timeouts.end(); it++) {
		Timeout* t = *it;
		if (end < t->readyTime())
			break;
	}

	Timeout* t = new Timeout(callback, delay);
	timeouts.insert(it, t);
	return t;
}

Timeout::Timeout(boost::python::object callback, int delay)
	: callback(callback),
	  start(GameWindow::instance().time()),
	  delay(delay),
	  active(true)
{
}

void Timeout::cancel()
{
	active = false;
}

bool Timeout::isActive()
{
	return active;
}

bool Timeout::ready(int now)
{
	return now > start + delay;
}

int Timeout::readyTime()
{
	return start + delay;
}

void Timeout::execute()
{
	try {
		callback();
	} catch (boost::python::error_already_set) {
		pythonErr();
	}
}

void updateTimeouts()
{
	int now = GameWindow::instance().time();
	bool next = true;

	while (next && timeouts.size()) {
		Timeout* t = timeouts.front();
		if (!t->isActive()) {
			timeouts.pop_front();
			delete t;
		}
		else if (t->ready(now)) {
			t->execute();
			timeouts.pop_front();
			delete t;
		}
		else {
			next = false;
		}
	}
}

void exportTimeout()
{
	using namespace boost::python;

	class_<Timeout> ("Timeout", no_init)
		.def("cancel", &Timeout::cancel)
		;

	pythonAddFunction("timeout", make_function(pythonSetTimeout,
		return_value_policy<reference_existing_object>()));
}

<|endoftext|>


<commit_before>#include "YarrarMarkerParser.h"
#include "Util.h"

#include <cassert>
#include <cstdint>

namespace {

using namespace yarrar;

const int FIELD_SIZE = 8;

int getId(const cv::Mat& field)
{
    // TODO: A real parser. This is only for testing.
    // Final id is fourth line as binary converted to integer.
    int id = 0;
    for(int i = 0; i < FIELD_SIZE; ++i)
    {
        if(field.at<uint8_t>(3, i) == 1)
        {
            id = id | (uint8_t) (1 << (7 - i));
        }
    }

    return id;
}

Rotation90 getZRotation(const cv::Mat& field)
{
    // The rectangle in upper left corner is used to
    // indicate the rotation.

    if(field.at<uchar>(1, 1) == 1) return Rotation90::DEG_0;
    else if(field.at<int8_t>(1, 6) == 1) return Rotation90::DEG_90;
    else if(field.at<int8_t>(6, 6) == 1) return Rotation90::DEG_180;
    else if(field.at<int8_t>(6, 1) == 1) return Rotation90::DEG_270;

    return Rotation90::DEG_0;
}

}

namespace yarrar {

MarkerValue YarrarMarkerParser::getData(const cv::Mat& image)
{
    assert(image.cols == image.rows && "Id parser expects square image");

    cv::Mat binary;
    cv::inRange(image, 0, 100, binary);

    // Works by dividing the image to 8x8 matrix (byte per line).
    // Then check if a cell is either black (1) or white (0).
    const int dimension = FIELD_SIZE;
    const int stepSize = image.cols / dimension;
    const int start = stepSize / 2;
    //DataField field;

    cv::Mat field = cv::Mat::zeros(dimension, dimension, CV_8S);

    for(int i = 0; i < dimension; ++i)
    {
        for(int j = 0; j < dimension; ++j)
        {
            const int col = start + i * stepSize;
            const int row = start + j * stepSize;
            const bool isBlack = binary.at<uint8_t>(col, row) > 0;
            field.at<int8_t>(i, j) = isBlack ? 1 : 0;
        }
    }

    // Get current rotation.
    Rotation90 rot = getZRotation(field);

    // Rotate the field, so that it's in default (DEG_0)
    // rotation. This way id parsing doesn't
    // have to care about rotations.
    switch(rot)
    {
        case Rotation90::DEG_90:
            util::rotate(field, field, Rotation90::DEG_270);
            break;
        case Rotation90::DEG_180:
            util::rotate(field, field, Rotation90::DEG_180);
            break;
        case Rotation90::DEG_270:
            util::rotate(field, field, Rotation90::DEG_90);
            break;
        case Rotation90::DEG_0:
            break;
    }

    return {
        true, // TODO: Validation
        getId(field),
        rot
    };
}

}
<commit_msg>Use uint_8 consistently in YarrarMarkerParser.<commit_after>#include "YarrarMarkerParser.h"
#include "Util.h"

#include <cassert>
#include <cstdint>

namespace {

using namespace yarrar;

const int FIELD_SIZE = 8;

int getId(const cv::Mat& field)
{
    // TODO: A real parser. This is only for testing.
    // Final id is fourth line as binary converted to integer.
    int id = 0;
    for(int i = 0; i < FIELD_SIZE; ++i)
    {
        if(field.at<uint8_t>(3, i) == 1)
        {
            id = id | (uint8_t) (1 << (7 - i));
        }
    }

    return id;
}

Rotation90 getZRotation(const cv::Mat& field)
{
    // The rectangle in upper left corner is used to
    // indicate the rotation.

    if(field.at<uint8_t>(1, 1) == 1) return Rotation90::DEG_0;
    else if(field.at<uint8_t>(1, 6) == 1) return Rotation90::DEG_90;
    else if(field.at<uint8_t>(6, 6) == 1) return Rotation90::DEG_180;
    else if(field.at<uint8_t>(6, 1) == 1) return Rotation90::DEG_270;

    return Rotation90::DEG_0;
}

}

namespace yarrar {

MarkerValue YarrarMarkerParser::getData(const cv::Mat& image)
{
    assert(image.cols == image.rows && "Id parser expects square image");

    cv::Mat binary;
    cv::inRange(image, 0, 100, binary);

    // Works by dividing the image to 8x8 matrix (byte per line).
    // Then check if a cell is either black (1) or white (0).
    const int dimension = FIELD_SIZE;
    const int stepSize = image.cols / dimension;
    const int start = stepSize / 2;

    cv::Mat field = cv::Mat::zeros(dimension, dimension, CV_8S);

    for(int i = 0; i < dimension; ++i)
    {
        for(int j = 0; j < dimension; ++j)
        {
            const int col = start + i * stepSize;
            const int row = start + j * stepSize;
            const bool isBlack = binary.at<uint8_t>(col, row) > 0;
            field.at<uint8_t>(i, j) = isBlack ? 1 : 0;
        }
    }

    // Get current rotation.
    Rotation90 rot = getZRotation(field);

    // Rotate the field, so that it's in default (DEG_0)
    // rotation. This way id parsing doesn't
    // have to care about rotations.
    switch(rot)
    {
        case Rotation90::DEG_90:
            util::rotate(field, field, Rotation90::DEG_270);
            break;
        case Rotation90::DEG_180:
            util::rotate(field, field, Rotation90::DEG_180);
            break;
        case Rotation90::DEG_270:
            util::rotate(field, field, Rotation90::DEG_90);
            break;
        case Rotation90::DEG_0:
            break;
    }

    return {
        true, // TODO: Validation
        getId(field),
        rot
    };
}

}
<|endoftext|>


<commit_before><commit_msg>#96071#: try to create URL via LocalFileHelper if URL is not valid<commit_after><|endoftext|>


<commit_before>// rhoruntime.cpp
#include "pch_rhoruntime.h"
#include "rhoruntime.h"

using namespace rhoruntime;
using namespace Platform;

CRhoRuntime::CRhoRuntime():
	m_WaitCallback(nullptr),
	m_UpdateWebViewCallback(nullptr),
	m_ExitCallback(nullptr)
{
}

// this callback is an example of calling the C# API methods from C++
void CRhoRuntime::SetWaitCallback(WaitCallbackPointer^ callback)
{
	m_WaitCallback = callback;
}

// this callback is an example of updating UI controls from C++ non-UI thread
void CRhoRuntime::SetUpdateWebViewCallback(UpdateWebViewCallbackPointer^ callback)
{
	m_UpdateWebViewCallback = callback;
}

// this callback is an example of application exit technique
void CRhoRuntime::SetExitCallback(ExitCallbackPointer^ callback)
{
	m_ExitCallback = callback;
}

// rhodes executed in a separate thread
void CRhoRuntime::Execute()
{
	// sample code just for testing
	for (int i=0; i<10; i++) {
		// wait for 1 second
		if ((i > 0) && m_WaitCallback)
			m_WaitCallback(1000);
		// update HTML code in WebView
		if (m_UpdateWebViewCallback)
			m_UpdateWebViewCallback(i);
	}
	// exit application
	if (m_ExitCallback)
		m_ExitCallback();
}<commit_msg>temp sqlite3 init<commit_after>// rhoruntime.cpp
#include "pch_rhoruntime.h"
#include "rhoruntime.h"

#include "../../shared/sqlite/sqlite3.h"

using namespace rhoruntime;
using namespace Platform;

CRhoRuntime::CRhoRuntime():
	m_WaitCallback(nullptr),
	m_UpdateWebViewCallback(nullptr),
	m_ExitCallback(nullptr)
{
	sqlite3_initialize();
}

// this callback is an example of calling the C# API methods from C++
void CRhoRuntime::SetWaitCallback(WaitCallbackPointer^ callback)
{
	m_WaitCallback = callback;
}

// this callback is an example of updating UI controls from C++ non-UI thread
void CRhoRuntime::SetUpdateWebViewCallback(UpdateWebViewCallbackPointer^ callback)
{
	m_UpdateWebViewCallback = callback;
}

// this callback is an example of application exit technique
void CRhoRuntime::SetExitCallback(ExitCallbackPointer^ callback)
{
	m_ExitCallback = callback;
}

// rhodes executed in a separate thread
void CRhoRuntime::Execute()
{
	// sample code just for testing
	for (int i=0; i<10; i++) {
		// wait for 1 second
		if ((i > 0) && m_WaitCallback)
			m_WaitCallback(1000);
		// update HTML code in WebView
		if (m_UpdateWebViewCallback)
			m_UpdateWebViewCallback(i);
	}
	// exit application
	if (m_ExitCallback)
		m_ExitCallback();
}<|endoftext|>


<commit_before><commit_msg>CID#708514 uninitialized members<commit_after><|endoftext|>


<commit_before>// $Id$

/*
Copyright (c) 2007-2011, Trustees of The Leland Stanford Junior University
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the Stanford University nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <iostream>
#include <sstream>
#include "random_utils.hpp"
#include "traffic.hpp"

TrafficPattern::TrafficPattern(int nodes)
: _nodes(nodes)
{
  if(nodes <= 0) {
    cout << "Error: Traffic patterns require at least one node." << endl;
    exit(-1);
  }
}

TrafficPattern * TrafficPattern::New(string const & pattern, int nodes)
{
  string pattern_name;
  string param_str;
  size_t left = pattern.find_first_of('(');
  if(left == string::npos) {
    pattern_name = pattern;
    param_str = "{}";
  } else {
    pattern_name = pattern.substr(0, left);
    size_t right = pattern.find_last_of(')');
    if(right == string::npos) {
      param_str = pattern.substr(left+1);
    } else {
      param_str = pattern.substr(left+1, right-left-1);
    }
  }
  vector<string> params = tokenize('{' + param_str + '}');

  TrafficPattern * result = NULL;
  if(pattern_name == "bitcomp") {
    result = new BitCompTrafficPattern(nodes);
  } else if(pattern_name == "transpose") {
    result = new TransposeTrafficPattern(nodes);
  } else if(pattern_name == "bitrev") {
    result = new BitRevTrafficPattern(nodes);
  } else if(pattern_name == "shuffle") {
    result = new ShuffleTrafficPattern(nodes);
  } else if(pattern_name == "randperm") {
    int perm_seed = params.empty() ? 0 : atoi(params[0].c_str());
    result = new RandomPermutationTrafficPattern(nodes, perm_seed);
  } else if(pattern_name == "uniform") {
    result = new UniformRandomTrafficPattern(nodes);
  } else if(pattern_name == "background") {
    vector<string> excludes_str = tokenize(params[0]);
    vector<int> excludes(excludes_str.size());
    for(size_t i = 0; i < excludes.size(); ++i) {
      excludes[i] = atoi(excludes_str[i].c_str());
    }
    result = new UniformBackgroundTrafficPattern(nodes, excludes);
  } else if(pattern_name == "diagonal") {
    result = new DiagonalTrafficPattern(nodes);
  } else if(pattern_name == "asymmetric") {
    result = new AsymmetricTrafficPattern(nodes);
  } else if(pattern_name == "taper64") {
    result = new Taper64TrafficPattern(nodes);
  } else if((pattern_name == "tornado") || (pattern_name == "neighbor") ||
	    (pattern_name == "bad_dragon") || (pattern_name == "badperm_yarc")) {
    if(params.size() < 3) {
      cout << "Error: Missing parameters for digit permutation traffic pattern: " << pattern << endl;
      exit(-1);
    }
    int k = atoi(params[0].c_str());
    int n = atoi(params[1].c_str());
    int xr = atoi(params[2].c_str());
    if(pattern_name == "tornado") {
      result = new TornadoTrafficPattern(nodes, k, n, xr);
    } else if(pattern_name == "neighbor") {
      result = new NeighborTrafficPattern(nodes, k, n, xr);
    } else if(pattern_name == "bad_dragon") {
      result = new BadPermDFlyTrafficPattern(nodes, k, n, xr);
    } else if(pattern_name == "badperm_yarc") {
      result = new BadPermYarcTrafficPattern(nodes, k, n, xr);
    }
  } else if(pattern_name == "hotspot") {
    if(params.empty()) {
      cout << "Error: Missing parameter for hotspot traffic pattern: " << pattern << endl;
      exit(-1);
    }
    vector<string> hotspots_str = tokenize(params[0]);
    vector<int> hotspots(hotspots_str.size());
    for(size_t i = 0; i < hotspots.size(); ++i) {
      hotspots[i] = atoi(hotspots_str[i].c_str());
    }
    vector<int> rates(hotspots.size(), 1);
    if(params.size() >= 2) {
      vector<string> rates_str = tokenize(params[1]);
      rates_str.resize(hotspots.size(), rates_str.back());
      for(size_t i = 0; i < rates.size(); ++i) {
	rates[i] = atoi(rates_str[i].c_str());
      }
    }
    result = new HotSpotTrafficPattern(nodes, hotspots, rates);
  } else {
    cout << "Error: Unknown traffic pattern: " << pattern << endl;
    exit(-1);
  }
  return result;
}

TrafficPattern * TrafficPattern::New(string const & pattern, int nodes, Configuration const & config)
{
  TrafficPattern * result = NULL;
  if((pattern == "tornado") || (pattern == "neighbor") ||
     (pattern == "bad_dragon") || (pattern == "badperm_yarc")) {
    int k = config.GetInt("k");
    int n = config.GetInt("n");
    int xr = config.GetInt("xr");
    ostringstream ss;
    ss << pattern << '(' << k << ',' << n << ',' << xr << ')';
    result = New(ss.str(), nodes);
  } else {
    result = New(pattern, nodes);
  }
  return result;
}

PermutationTrafficPattern::PermutationTrafficPattern(int nodes)
  : TrafficPattern(nodes)
{

}

BitPermutationTrafficPattern::BitPermutationTrafficPattern(int nodes)
  : PermutationTrafficPattern(nodes)
{
  if((nodes & -nodes) != nodes) {
    cout << "Error: Bit permutation traffic patterns require the number of "
	 << "nodes to be a power of two." << endl;
    exit(-1);
  }
}

BitCompTrafficPattern::BitCompTrafficPattern(int nodes)
  : BitPermutationTrafficPattern(nodes)
{

}

int BitCompTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  int const mask = _nodes - 1;
  return ~source & mask;
}

TransposeTrafficPattern::TransposeTrafficPattern(int nodes)
  : BitPermutationTrafficPattern(nodes), _shift(0)
{
  while(nodes >>= 1) {
    ++_shift;
  }
  if(_shift % 2) {
    cout << "Error: Transpose traffic pattern requires the number of nodes to "
	 << "be an even power of two." << endl;
    exit(-1);
  }
}

int TransposeTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  int const mask_lo = (1 << _shift) - 1;
  int const mask_hi = mask_lo << _shift;
  return (((source >> _shift) & mask_lo) | ((source << _shift) & mask_hi));
}

BitRevTrafficPattern::BitRevTrafficPattern(int nodes)
  : BitPermutationTrafficPattern(nodes)
{

}

int BitRevTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  int result = 0;
  for(int n = _nodes; n > 1; n >>= 1) {
    result = (result << 1) | (source % 2);
    source >>= 1;
  }
  return result;
}

ShuffleTrafficPattern::ShuffleTrafficPattern(int nodes)
  : BitPermutationTrafficPattern(nodes)
{

}

int ShuffleTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  int const shifted = source << 1;
  return ((shifted & (_nodes - 1)) | bool(shifted & _nodes));
}

DigitPermutationTrafficPattern::DigitPermutationTrafficPattern(int nodes, int k,
							       int n, int xr)
  : PermutationTrafficPattern(nodes), _k(k), _n(n), _xr(xr)
{

}

TornadoTrafficPattern::TornadoTrafficPattern(int nodes, int k, int n, int xr)
  : DigitPermutationTrafficPattern(nodes, k, n, xr)
{

}

int TornadoTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));

  int offset = 1;
  int result = 0;

  for(int n = 0; n < _n; ++n) {
    result += offset *
      (((source / offset) % (_xr * _k) + ((_xr * _k) / 2 - 1)) % (_xr * _k));
    offset *= (_xr * _k);
  }
  return result;
}

NeighborTrafficPattern::NeighborTrafficPattern(int nodes, int k, int n, int xr)
  : DigitPermutationTrafficPattern(nodes, k, n, xr)
{

}

int NeighborTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));

  int offset = 1;
  int result = 0;

  for(int n = 0; n < _n; ++n) {
    result += offset *
      (((source / offset) % (_xr * _k) + 1) % (_xr * _k));
    offset *= (_xr * _k);
  }
  return result;
}

RandomPermutationTrafficPattern::RandomPermutationTrafficPattern(int nodes,
								 int seed)
  : TrafficPattern(nodes)
{
  _dest.resize(nodes);
  randomize(seed);
}

void RandomPermutationTrafficPattern::randomize(int seed)
{
  unsigned long prev_seed = RandomIntLong( );
  RandomSeed(seed);

  _dest.assign(_nodes, -1);

  for(int i = 0; i < _nodes; ++i) {
    int ind = RandomInt(_nodes - 1 - i);

    int j = 0;
    int cnt = 0;
    while((cnt < ind) || (_dest[j] != -1)) {
      if(_dest[j] == -1) {
	++cnt;
      }
      ++j;
      assert(j < _nodes);
    }

    _dest[j] = i;
  }

  RandomSeed(prev_seed);
}

int RandomPermutationTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  assert((_dest[source] >= 0) && (_dest[source] < _nodes));
  return _dest[source];
}

RandomTrafficPattern::RandomTrafficPattern(int nodes)
  : TrafficPattern(nodes)
{

}

UniformRandomTrafficPattern::UniformRandomTrafficPattern(int nodes)
  : RandomTrafficPattern(nodes)
{

}

int UniformRandomTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  return RandomInt(_nodes - 1);
}

UniformBackgroundTrafficPattern::UniformBackgroundTrafficPattern(int nodes, vector<int> excluded_nodes)
  : RandomTrafficPattern(nodes)
{
  for(size_t i = 0; i < excluded_nodes.size(); ++i) {
    int const node = excluded_nodes[i];
    assert((node >= 0) && (node < _nodes));
    _excluded.insert(node);
  }
}

int UniformBackgroundTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));

  int result;

  do {
    result = RandomInt(_nodes - 1);
  } while(_excluded.count(result) > 0);

  return result;
}

DiagonalTrafficPattern::DiagonalTrafficPattern(int nodes)
  : RandomTrafficPattern(nodes)
{

}

int DiagonalTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  return ((RandomInt(2) == 0) ? ((source + 1) % _nodes) : source);
}

AsymmetricTrafficPattern::AsymmetricTrafficPattern(int nodes)
  : RandomTrafficPattern(nodes)
{

}

int AsymmetricTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  int const half = _nodes / 2;
  return (source % half) + (RandomInt(1) ? half : 0);
}

Taper64TrafficPattern::Taper64TrafficPattern(int nodes)
  : RandomTrafficPattern(nodes)
{
  if(nodes != 64) {
    cout << "Error: Tthe Taper64 traffic pattern requires the number of nodes "
	 << "to be exactly 64." << endl;
    exit(-1);
  }
}

int Taper64TrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  if(RandomInt(1)) {
    return ((64 + source + 8 * (RandomInt(2) - 1) + (RandomInt(2) - 1)) % 64);
  } else {
    return RandomInt(_nodes - 1);
  }
}

BadPermDFlyTrafficPattern::BadPermDFlyTrafficPattern(int nodes, int k, int n,
						     int xr)
  : DigitPermutationTrafficPattern(nodes, k, n, xr)
{

}

int BadPermDFlyTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));

  int const grp_size_routers = 2 * (_xr * _k);
  int const grp_size_nodes = grp_size_routers * (_xr * _k);

  return ((RandomInt(grp_size_nodes - 1) + ((source / grp_size_nodes) + 1) * grp_size_nodes) % _nodes);
}

BadPermYarcTrafficPattern::BadPermYarcTrafficPattern(int nodes, int k, int n,
						     int xr)
  : DigitPermutationTrafficPattern(nodes, k, n, xr)
{

}

int BadPermYarcTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  int const row = source / (_xr * _k);
  return RandomInt((_xr * _k) - 1) * (_xr * _k) + row;
}

HotSpotTrafficPattern::HotSpotTrafficPattern(int nodes, vector<int> hotspots,
					     vector<int> rates)
  : TrafficPattern(nodes), _hotspots(hotspots), _rates(rates), _max_val(-1)
{
  assert(!_hotspots.empty());
  size_t const size = _hotspots.size();
  _rates.resize(size, _rates.empty() ? 1 : _rates.back());
  for(size_t i = 0; i < size; ++i) {
    int const hotspot = _hotspots[i];
    assert((hotspot >= 0) && (hotspot < _nodes));
    int const rate = _rates[i];
    assert(rate >= 0);
    _max_val += rate;
  }
}

int HotSpotTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));

  int pct = RandomInt(_max_val);

  for(size_t i = 0; i < (_hotspots.size() - 1); ++i) {
    int const limit = _rates[i];
    if(limit > pct) {
      return _hotspots[i];
    } else {
      pct -= limit;
    }
  }
  assert(_rates.back() > pct);
  return _hotspots.back();
}
<commit_msg>transpose traffic was broken, _shift need to be divided by 2<commit_after>// $Id$

/*
Copyright (c) 2007-2011, Trustees of The Leland Stanford Junior University
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the Stanford University nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <iostream>
#include <sstream>
#include "random_utils.hpp"
#include "traffic.hpp"

TrafficPattern::TrafficPattern(int nodes)
: _nodes(nodes)
{
  if(nodes <= 0) {
    cout << "Error: Traffic patterns require at least one node." << endl;
    exit(-1);
  }
}

TrafficPattern * TrafficPattern::New(string const & pattern, int nodes)
{
  string pattern_name;
  string param_str;
  size_t left = pattern.find_first_of('(');
  if(left == string::npos) {
    pattern_name = pattern;
    param_str = "{}";
  } else {
    pattern_name = pattern.substr(0, left);
    size_t right = pattern.find_last_of(')');
    if(right == string::npos) {
      param_str = pattern.substr(left+1);
    } else {
      param_str = pattern.substr(left+1, right-left-1);
    }
  }
  vector<string> params = tokenize('{' + param_str + '}');

  TrafficPattern * result = NULL;
  if(pattern_name == "bitcomp") {
    result = new BitCompTrafficPattern(nodes);
  } else if(pattern_name == "transpose") {
    result = new TransposeTrafficPattern(nodes);
  } else if(pattern_name == "bitrev") {
    result = new BitRevTrafficPattern(nodes);
  } else if(pattern_name == "shuffle") {
    result = new ShuffleTrafficPattern(nodes);
  } else if(pattern_name == "randperm") {
    int perm_seed = params.empty() ? 0 : atoi(params[0].c_str());
    result = new RandomPermutationTrafficPattern(nodes, perm_seed);
  } else if(pattern_name == "uniform") {
    result = new UniformRandomTrafficPattern(nodes);
  } else if(pattern_name == "background") {
    vector<string> excludes_str = tokenize(params[0]);
    vector<int> excludes(excludes_str.size());
    for(size_t i = 0; i < excludes.size(); ++i) {
      excludes[i] = atoi(excludes_str[i].c_str());
    }
    result = new UniformBackgroundTrafficPattern(nodes, excludes);
  } else if(pattern_name == "diagonal") {
    result = new DiagonalTrafficPattern(nodes);
  } else if(pattern_name == "asymmetric") {
    result = new AsymmetricTrafficPattern(nodes);
  } else if(pattern_name == "taper64") {
    result = new Taper64TrafficPattern(nodes);
  } else if((pattern_name == "tornado") || (pattern_name == "neighbor") ||
	    (pattern_name == "bad_dragon") || (pattern_name == "badperm_yarc")) {
    if(params.size() < 3) {
      cout << "Error: Missing parameters for digit permutation traffic pattern: " << pattern << endl;
      exit(-1);
    }
    int k = atoi(params[0].c_str());
    int n = atoi(params[1].c_str());
    int xr = atoi(params[2].c_str());
    if(pattern_name == "tornado") {
      result = new TornadoTrafficPattern(nodes, k, n, xr);
    } else if(pattern_name == "neighbor") {
      result = new NeighborTrafficPattern(nodes, k, n, xr);
    } else if(pattern_name == "bad_dragon") {
      result = new BadPermDFlyTrafficPattern(nodes, k, n, xr);
    } else if(pattern_name == "badperm_yarc") {
      result = new BadPermYarcTrafficPattern(nodes, k, n, xr);
    }
  } else if(pattern_name == "hotspot") {
    if(params.empty()) {
      cout << "Error: Missing parameter for hotspot traffic pattern: " << pattern << endl;
      exit(-1);
    }
    vector<string> hotspots_str = tokenize(params[0]);
    vector<int> hotspots(hotspots_str.size());
    for(size_t i = 0; i < hotspots.size(); ++i) {
      hotspots[i] = atoi(hotspots_str[i].c_str());
    }
    vector<int> rates(hotspots.size(), 1);
    if(params.size() >= 2) {
      vector<string> rates_str = tokenize(params[1]);
      rates_str.resize(hotspots.size(), rates_str.back());
      for(size_t i = 0; i < rates.size(); ++i) {
	rates[i] = atoi(rates_str[i].c_str());
      }
    }
    result = new HotSpotTrafficPattern(nodes, hotspots, rates);
  } else {
    cout << "Error: Unknown traffic pattern: " << pattern << endl;
    exit(-1);
  }
  return result;
}

TrafficPattern * TrafficPattern::New(string const & pattern, int nodes, Configuration const & config)
{
  TrafficPattern * result = NULL;
  if((pattern == "tornado") || (pattern == "neighbor") ||
     (pattern == "bad_dragon") || (pattern == "badperm_yarc")) {
    int k = config.GetInt("k");
    int n = config.GetInt("n");
    int xr = config.GetInt("xr");
    ostringstream ss;
    ss << pattern << '(' << k << ',' << n << ',' << xr << ')';
    result = New(ss.str(), nodes);
  } else {
    result = New(pattern, nodes);
  }
  return result;
}

PermutationTrafficPattern::PermutationTrafficPattern(int nodes)
  : TrafficPattern(nodes)
{

}

BitPermutationTrafficPattern::BitPermutationTrafficPattern(int nodes)
  : PermutationTrafficPattern(nodes)
{
  if((nodes & -nodes) != nodes) {
    cout << "Error: Bit permutation traffic patterns require the number of "
	 << "nodes to be a power of two." << endl;
    exit(-1);
  }
}

BitCompTrafficPattern::BitCompTrafficPattern(int nodes)
  : BitPermutationTrafficPattern(nodes)
{

}

int BitCompTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  int const mask = _nodes - 1;
  return ~source & mask;
}

TransposeTrafficPattern::TransposeTrafficPattern(int nodes)
  : BitPermutationTrafficPattern(nodes), _shift(0)
{
  while(nodes >>= 1) {
    ++_shift;
  }
  if(_shift % 2) {
    cout << "Error: Transpose traffic pattern requires the number of nodes to "
	 << "be an even power of two." << endl;
    exit(-1);
  }
  _shift/=2;
}

int TransposeTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  int const mask_lo = (1 << _shift) - 1;
  int const mask_hi = mask_lo << _shift;
  return (((source >> _shift) & mask_lo) | ((source << _shift) & mask_hi));
}

BitRevTrafficPattern::BitRevTrafficPattern(int nodes)
  : BitPermutationTrafficPattern(nodes)
{

}

int BitRevTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  int result = 0;
  for(int n = _nodes; n > 1; n >>= 1) {
    result = (result << 1) | (source % 2);
    source >>= 1;
  }
  return result;
}

ShuffleTrafficPattern::ShuffleTrafficPattern(int nodes)
  : BitPermutationTrafficPattern(nodes)
{

}

int ShuffleTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  int const shifted = source << 1;
  return ((shifted & (_nodes - 1)) | bool(shifted & _nodes));
}

DigitPermutationTrafficPattern::DigitPermutationTrafficPattern(int nodes, int k,
							       int n, int xr)
  : PermutationTrafficPattern(nodes), _k(k), _n(n), _xr(xr)
{

}

TornadoTrafficPattern::TornadoTrafficPattern(int nodes, int k, int n, int xr)
  : DigitPermutationTrafficPattern(nodes, k, n, xr)
{

}

int TornadoTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));

  int offset = 1;
  int result = 0;

  for(int n = 0; n < _n; ++n) {
    result += offset *
      (((source / offset) % (_xr * _k) + ((_xr * _k) / 2 - 1)) % (_xr * _k));
    offset *= (_xr * _k);
  }
  return result;
}

NeighborTrafficPattern::NeighborTrafficPattern(int nodes, int k, int n, int xr)
  : DigitPermutationTrafficPattern(nodes, k, n, xr)
{

}

int NeighborTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));

  int offset = 1;
  int result = 0;

  for(int n = 0; n < _n; ++n) {
    result += offset *
      (((source / offset) % (_xr * _k) + 1) % (_xr * _k));
    offset *= (_xr * _k);
  }
  return result;
}

RandomPermutationTrafficPattern::RandomPermutationTrafficPattern(int nodes,
								 int seed)
  : TrafficPattern(nodes)
{
  _dest.resize(nodes);
  randomize(seed);
}

void RandomPermutationTrafficPattern::randomize(int seed)
{
  unsigned long prev_seed = RandomIntLong( );
  RandomSeed(seed);

  _dest.assign(_nodes, -1);

  for(int i = 0; i < _nodes; ++i) {
    int ind = RandomInt(_nodes - 1 - i);

    int j = 0;
    int cnt = 0;
    while((cnt < ind) || (_dest[j] != -1)) {
      if(_dest[j] == -1) {
	++cnt;
      }
      ++j;
      assert(j < _nodes);
    }

    _dest[j] = i;
  }

  RandomSeed(prev_seed);
}

int RandomPermutationTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  assert((_dest[source] >= 0) && (_dest[source] < _nodes));
  return _dest[source];
}

RandomTrafficPattern::RandomTrafficPattern(int nodes)
  : TrafficPattern(nodes)
{

}

UniformRandomTrafficPattern::UniformRandomTrafficPattern(int nodes)
  : RandomTrafficPattern(nodes)
{

}

int UniformRandomTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  return RandomInt(_nodes - 1);
}

UniformBackgroundTrafficPattern::UniformBackgroundTrafficPattern(int nodes, vector<int> excluded_nodes)
  : RandomTrafficPattern(nodes)
{
  for(size_t i = 0; i < excluded_nodes.size(); ++i) {
    int const node = excluded_nodes[i];
    assert((node >= 0) && (node < _nodes));
    _excluded.insert(node);
  }
}

int UniformBackgroundTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));

  int result;

  do {
    result = RandomInt(_nodes - 1);
  } while(_excluded.count(result) > 0);

  return result;
}

DiagonalTrafficPattern::DiagonalTrafficPattern(int nodes)
  : RandomTrafficPattern(nodes)
{

}

int DiagonalTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  return ((RandomInt(2) == 0) ? ((source + 1) % _nodes) : source);
}

AsymmetricTrafficPattern::AsymmetricTrafficPattern(int nodes)
  : RandomTrafficPattern(nodes)
{

}

int AsymmetricTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  int const half = _nodes / 2;
  return (source % half) + (RandomInt(1) ? half : 0);
}

Taper64TrafficPattern::Taper64TrafficPattern(int nodes)
  : RandomTrafficPattern(nodes)
{
  if(nodes != 64) {
    cout << "Error: Tthe Taper64 traffic pattern requires the number of nodes "
	 << "to be exactly 64." << endl;
    exit(-1);
  }
}

int Taper64TrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  if(RandomInt(1)) {
    return ((64 + source + 8 * (RandomInt(2) - 1) + (RandomInt(2) - 1)) % 64);
  } else {
    return RandomInt(_nodes - 1);
  }
}

BadPermDFlyTrafficPattern::BadPermDFlyTrafficPattern(int nodes, int k, int n,
						     int xr)
  : DigitPermutationTrafficPattern(nodes, k, n, xr)
{

}

int BadPermDFlyTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));

  int const grp_size_routers = 2 * (_xr * _k);
  int const grp_size_nodes = grp_size_routers * (_xr * _k);

  return ((RandomInt(grp_size_nodes - 1) + ((source / grp_size_nodes) + 1) * grp_size_nodes) % _nodes);
}

BadPermYarcTrafficPattern::BadPermYarcTrafficPattern(int nodes, int k, int n,
						     int xr)
  : DigitPermutationTrafficPattern(nodes, k, n, xr)
{

}

int BadPermYarcTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));
  int const row = source / (_xr * _k);
  return RandomInt((_xr * _k) - 1) * (_xr * _k) + row;
}

HotSpotTrafficPattern::HotSpotTrafficPattern(int nodes, vector<int> hotspots,
					     vector<int> rates)
  : TrafficPattern(nodes), _hotspots(hotspots), _rates(rates), _max_val(-1)
{
  assert(!_hotspots.empty());
  size_t const size = _hotspots.size();
  _rates.resize(size, _rates.empty() ? 1 : _rates.back());
  for(size_t i = 0; i < size; ++i) {
    int const hotspot = _hotspots[i];
    assert((hotspot >= 0) && (hotspot < _nodes));
    int const rate = _rates[i];
    assert(rate >= 0);
    _max_val += rate;
  }
}

int HotSpotTrafficPattern::dest(int source)
{
  assert((source >= 0) && (source < _nodes));

  int pct = RandomInt(_max_val);

  for(size_t i = 0; i < (_hotspots.size() - 1); ++i) {
    int const limit = _rates[i];
    if(limit > pct) {
      return _hotspots[i];
    } else {
      pct -= limit;
    }
  }
  assert(_rates.back() > pct);
  return _hotspots.back();
}
<|endoftext|>


<commit_before>/*
 * SessionSpelling.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionSpelling.hpp"

#include <boost/shared_ptr.hpp>

#include <core/Error.hpp>
#include <core/Exec.hpp>

#include <core/Algorithm.hpp>
#include <core/spelling/HunspellSpellingEngine.hpp>

#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <r/RUtil.hpp>
#include <r/RExec.hpp>

#include <session/SessionUserSettings.hpp>
#include <session/SessionModuleContext.hpp>

using namespace rstudio::core;

namespace rstudio {
namespace session {
namespace modules {
namespace spelling {

namespace {

// underlying spelling engine
boost::scoped_ptr<core::spelling::SpellingEngine> s_pSpellingEngine;

// R function for testing & debugging
SEXP rs_checkSpelling(SEXP wordSEXP)
{
   bool isCorrect;
   std::string word = r::sexp::asString(wordSEXP);

   Error error = s_pSpellingEngine->checkSpelling(word, &isCorrect);

   // We'll return true here so as not to tie up the front end.
   if (error)
   {
      LOG_ERROR(error);
      isCorrect = true;
   }

   r::sexp::Protect rProtect;
   return r::sexp::create(isCorrect, &rProtect);
}

json::Object dictionaryAsJson(const core::spelling::HunspellDictionary& dict)
{
   json::Object dictJson;
   dictJson["id"] = dict.id();
   dictJson["name"] = dict.name();
   return dictJson;
}

FilePath userDictionariesDir()
{
   return module_context::userScratchPath().childPath("dictionaries");
}

void syncSpellingEngineDictionaries()
{
   s_pSpellingEngine->useDictionary(userSettings().spellingLanguage());
}

core::spelling::HunspellDictionaryManager hunspellDictionaryManager()
{
   core::spelling::HunspellDictionaryManager dictManager(
                                         options().hunspellDictionariesPath(),
                                         userDictionariesDir());
   return dictManager;
}

FilePath allLanguagesDir()
{
   return module_context::userScratchPath().childPath(
                                          "dictionaries/languages-system");
}

// This responds to the request path of /dictionaries/<dict>/<dict>.dic
// and returns the file at <userScratchDir>/dictionaries/<dict>.dic
// Typo.js expects a hardcoded path in this form and we want to avoid forking it
void handleDictionaryRequest(const http::Request& request, http::Response* pResponse)
{
   std::string prefix = "/dictionaries/";
   std::string fileName = http::util::pathAfterPrefix(request, prefix);
   std::vector<std::string> splat = core::algorithm::split(fileName, "/");

   if (splat.size() != 2)
   {
      pResponse->setNotFoundError(request);
      return;
   }

   pResponse->setCacheableFile(allLanguagesDir().complete(splat[1]), request);
}

Error checkSpelling(const json::JsonRpcRequest& request,
                    json::JsonRpcResponse* pResponse)
{
   json::Array words;
   Error error = json::readParams(request.params, &words);
   if (error)
      return error;

   json::Array misspelledIndexes;
   for (std::size_t i=0; i<words.size(); i++)
   {
      if (!json::isType<std::string>(words[i]))
      {
         BOOST_ASSERT(false);
         continue;
      }

      std::string word = words[i].get_str();
      bool isCorrect = true;
      error = s_pSpellingEngine->checkSpelling(word, &isCorrect);
      if (error)
      {
         // if we can't check a word, ignore it; some combinations of platform, non-ASCII
         // characters, and locale are known to fail in iconv, and we don't want to put those
         // failures in front of the user (we just won't be able to spell check those words)
         LOG_ERROR(error);
      }
      else if (!isCorrect)
      {
         misspelledIndexes.push_back(static_cast<int>(i));
      }
   }

   pResponse->setResult(misspelledIndexes);

   return Success();
}

Error suggestionList(const json::JsonRpcRequest& request,
                     json::JsonRpcResponse* pResponse)
{
   std::string word;
   Error error = json::readParams(request.params, &word);
   if (error)
      return error;

   std::vector<std::string> sugs;
   error = s_pSpellingEngine->suggestionList(word, &sugs);
   if (error)
      return error;

   json::Array sugsJson;
   std::transform(sugs.begin(),
                  sugs.end(),
                  std::back_inserter(sugsJson),
                  json::toJsonString);
   pResponse->setResult(sugsJson);

   return Success();
}

Error getWordChars(const json::JsonRpcRequest& request,
                   json::JsonRpcResponse* pResponse)
{
   std::wstring wordChars;
   Error error = s_pSpellingEngine->wordChars(&wordChars);
   if (error)
      return error;

   pResponse->setResult(string_utils::wideToUtf8(wordChars));

   return Success();
}

Error addCustomDictionary(const json::JsonRpcRequest& request,
                          json::JsonRpcResponse* pResponse)
{
   // get the argument
   std::string dict;
   Error error = json::readParams(request.params, &dict);
   if (error)
      return error;
   FilePath dictPath = module_context::resolveAliasedPath(dict);

   // verify .dic extension
   if (!dictPath.hasExtensionLowerCase(".dic"))
   {
      std::string msg = "Dictionary files must have a .dic extension";
      Error error(json::errc::ParamInvalid, ERROR_LOCATION);
      pResponse->setError(error, json::Value(msg));
      return Success();
   }

   // perform the add
   using namespace rstudio::core::spelling;
   HunspellDictionaryManager dictManager = hunspellDictionaryManager();
   error = dictManager.custom().add(dictPath);
   if (error)
      return error;

   // sync spelling engine
   syncSpellingEngineDictionaries();

   // return
   pResponse->setResult(json::toJsonArray(dictManager.custom().dictionaries()));
   return Success();
}

Error removeCustomDictionary(const json::JsonRpcRequest& request,
                             json::JsonRpcResponse* pResponse)
{
   // get the argument
   std::string name;
   Error error = json::readParams(request.params, &name);
   if (error)
      return error;

   // perform the remove
   using namespace rstudio::core::spelling;
   HunspellDictionaryManager dictManager = hunspellDictionaryManager();
   error = dictManager.custom().remove(name);
   if (error)
      return error;

   // sync spelling engine
   syncSpellingEngineDictionaries();

   // return
   pResponse->setResult(json::toJsonArray(dictManager.custom().dictionaries()));
   return Success();
}

Error installAllDictionaries(const json::JsonRpcRequest& request,
                             json::JsonRpcResponse* pResponse)
{
   // form system path to all languages dir
   std::string targetDir = string_utils::utf8ToSystem(
                                    allLanguagesDir().absolutePath());

   // perform the download
   r::exec::RFunction dlFunc(".rs.downloadAllDictionaries",
                                targetDir,
                                module_context::haveSecureDownloadFileMethod());
   Error error = dlFunc.call();
   if (error)
   {
      std::string userMessage = r::endUserErrorMessage(error);
      pResponse->setError(error, json::Value(userMessage));
      return Success();
   }
   else
   {
      pResponse->setResult(spelling::spellingPrefsContextAsJson());
      return Success();
   }
}

// reset dictionary on user settings changed
void onUserSettingsChanged()
{
   syncSpellingEngineDictionaries();
}

SEXP rs_dictionariesPath()
{
   r::sexp::Protect protect;
   return r::sexp::create(
            options().hunspellDictionariesPath().absolutePath(),
            &protect);
}

SEXP rs_userDictionariesPath()
{
   r::sexp::Protect protect;
   return r::sexp::create(
            userDictionariesDir().absolutePath(),
            &protect);
}

} // anonymous namespace

core::json::Object spellingPrefsContextAsJson()
{
   using namespace rstudio::core::spelling;

   core::json::Object contextJson;

   HunspellDictionaryManager dictManager = hunspellDictionaryManager();
   std::vector<HunspellDictionary> dictionaries;
   Error error = dictManager.availableLanguages(&dictionaries);
   if (error)
   {
      LOG_ERROR(error);
      return core::json::Object();
   }

   core::json::Array dictionariesJson;
   std::transform(dictionaries.begin(),
                  dictionaries.end(),
                  std::back_inserter(dictionariesJson),
                  dictionaryAsJson);

   std::vector<std::string> customDicts = dictManager.custom().dictionaries();
   core::json::Array customDictsJson = json::toJsonArray(customDicts);

   // return json
   contextJson["all_languages_installed"] = dictManager.allLanguagesInstalled();
   contextJson["available_languages"] = dictionariesJson;
   contextJson["custom_dictionaries"] = customDictsJson;
   return contextJson;
}

Error initialize()
{
   RS_REGISTER_CALL_METHOD(rs_checkSpelling);
   RS_REGISTER_CALL_METHOD(rs_dictionariesPath);
   RS_REGISTER_CALL_METHOD(rs_userDictionariesPath);

   // initialize spelling engine
   using namespace rstudio::core::spelling;
   HunspellSpellingEngine* pHunspell = new HunspellSpellingEngine(
                                             userSettings().spellingLanguage(),
                                             hunspellDictionaryManager(),
                                             &r::util::iconvstr);
   s_pSpellingEngine.reset(pHunspell);

   // connect to user settings changed
   userSettings().onChanged.connect(onUserSettingsChanged);

   // register rpc methods
   using boost::bind;
   using namespace module_context;
   ExecBlock initBlock ;
   initBlock.addFunctions()
      (bind(registerRpcMethod, "check_spelling", checkSpelling))
      (bind(registerRpcMethod, "suggestion_list", suggestionList))
      (bind(registerRpcMethod, "get_word_chars", getWordChars))
      (bind(registerRpcMethod, "add_custom_dictionary", addCustomDictionary))
      (bind(registerRpcMethod, "remove_custom_dictionary", removeCustomDictionary))
      (bind(registerRpcMethod, "install_all_dictionaries", installAllDictionaries))
      (bind(registerUriHandler, "/dictionaries", handleDictionaryRequest))
      (bind(sourceModuleRFile, "SessionSpelling.R"));
   return initBlock.execute();
}

} // namespace spelling
} // namespace modules
} // namespace session
} // namespace rstudio

<commit_msg>fix realtime spelling working with non bundled dictionaries bug #4408<commit_after>/*
 * SessionSpelling.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionSpelling.hpp"

#include <boost/shared_ptr.hpp>

#include <core/Error.hpp>
#include <core/Exec.hpp>

#include <core/Algorithm.hpp>
#include <core/spelling/HunspellSpellingEngine.hpp>

#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <r/RUtil.hpp>
#include <r/RExec.hpp>

#include <session/SessionUserSettings.hpp>
#include <session/SessionModuleContext.hpp>

using namespace rstudio::core;

namespace rstudio {
namespace session {
namespace modules {
namespace spelling {

namespace {

// underlying spelling engine
boost::scoped_ptr<core::spelling::SpellingEngine> s_pSpellingEngine;

// R function for testing & debugging
SEXP rs_checkSpelling(SEXP wordSEXP)
{
   bool isCorrect;
   std::string word = r::sexp::asString(wordSEXP);

   Error error = s_pSpellingEngine->checkSpelling(word, &isCorrect);

   // We'll return true here so as not to tie up the front end.
   if (error)
   {
      LOG_ERROR(error);
      isCorrect = true;
   }

   r::sexp::Protect rProtect;
   return r::sexp::create(isCorrect, &rProtect);
}

json::Object dictionaryAsJson(const core::spelling::HunspellDictionary& dict)
{
   json::Object dictJson;
   dictJson["id"] = dict.id();
   dictJson["name"] = dict.name();
   return dictJson;
}

FilePath userDictionariesDir()
{
   return module_context::userScratchPath().childPath("dictionaries");
}

void syncSpellingEngineDictionaries()
{
   s_pSpellingEngine->useDictionary(userSettings().spellingLanguage());
}

core::spelling::HunspellDictionaryManager hunspellDictionaryManager()
{
   core::spelling::HunspellDictionaryManager dictManager(
                                         options().hunspellDictionariesPath(),
                                         userDictionariesDir());
   return dictManager;
}

FilePath allLanguagesDir()
{
   return module_context::userScratchPath().childPath(
                                          "dictionaries/languages-system");
}

FilePath customDictionariesDir()
{
   return module_context::userScratchPath().childPath(
                                          "dictionaries/custom");
}

// This responds to the request path of /dictionaries/<dict>/<dict>.dic
// and returns the file at <userScratchDir>/dictionaries/<dict>.dic
// Typo.js expects a hardcoded path in this form and we want to avoid forking it
void handleDictionaryRequest(const http::Request& request, http::Response* pResponse)
{
   std::string prefix = "/dictionaries/";
   std::string fileName = http::util::pathAfterPrefix(request, prefix);
   std::vector<std::string> splat = core::algorithm::split(fileName, "/");

   if (splat.size() != 2)
   {
      pResponse->setNotFoundError(request);
      return;
   }

   // preference order: custom -> user -> system -> pre-installed
   if (customDictionariesDir().complete(splat[1]).exists())
   {
      pResponse->setCacheableFile(customDictionariesDir().complete(splat[1]), request);
   }
   else if (allLanguagesDir().complete(splat[1]).exists())
   {
      pResponse->setCacheableFile(allLanguagesDir().complete(splat[1]), request);
   }
   else if (options().hunspellDictionariesPath().complete(splat[1]).exists())
   {
      pResponse->setCacheableFile(options().hunspellDictionariesPath().complete(splat[1]), request);
   }
   else
   {
      pResponse->setNotFoundError(request);
   }
}

Error checkSpelling(const json::JsonRpcRequest& request,
                    json::JsonRpcResponse* pResponse)
{
   json::Array words;
   Error error = json::readParams(request.params, &words);
   if (error)
      return error;

   json::Array misspelledIndexes;
   for (std::size_t i=0; i<words.size(); i++)
   {
      if (!json::isType<std::string>(words[i]))
      {
         BOOST_ASSERT(false);
         continue;
      }

      std::string word = words[i].get_str();
      bool isCorrect = true;
      error = s_pSpellingEngine->checkSpelling(word, &isCorrect);
      if (error)
      {
         // if we can't check a word, ignore it; some combinations of platform, non-ASCII
         // characters, and locale are known to fail in iconv, and we don't want to put those
         // failures in front of the user (we just won't be able to spell check those words)
         LOG_ERROR(error);
      }
      else if (!isCorrect)
      {
         misspelledIndexes.push_back(static_cast<int>(i));
      }
   }

   pResponse->setResult(misspelledIndexes);

   return Success();
}

Error suggestionList(const json::JsonRpcRequest& request,
                     json::JsonRpcResponse* pResponse)
{
   std::string word;
   Error error = json::readParams(request.params, &word);
   if (error)
      return error;

   std::vector<std::string> sugs;
   error = s_pSpellingEngine->suggestionList(word, &sugs);
   if (error)
      return error;

   json::Array sugsJson;
   std::transform(sugs.begin(),
                  sugs.end(),
                  std::back_inserter(sugsJson),
                  json::toJsonString);
   pResponse->setResult(sugsJson);

   return Success();
}

Error getWordChars(const json::JsonRpcRequest& request,
                   json::JsonRpcResponse* pResponse)
{
   std::wstring wordChars;
   Error error = s_pSpellingEngine->wordChars(&wordChars);
   if (error)
      return error;

   pResponse->setResult(string_utils::wideToUtf8(wordChars));

   return Success();
}

Error addCustomDictionary(const json::JsonRpcRequest& request,
                          json::JsonRpcResponse* pResponse)
{
   // get the argument
   std::string dict;
   Error error = json::readParams(request.params, &dict);
   if (error)
      return error;
   FilePath dictPath = module_context::resolveAliasedPath(dict);

   // verify .dic extension
   if (!dictPath.hasExtensionLowerCase(".dic"))
   {
      std::string msg = "Dictionary files must have a .dic extension";
      Error error(json::errc::ParamInvalid, ERROR_LOCATION);
      pResponse->setError(error, json::Value(msg));
      return Success();
   }

   // perform the add
   using namespace rstudio::core::spelling;
   HunspellDictionaryManager dictManager = hunspellDictionaryManager();
   error = dictManager.custom().add(dictPath);
   if (error)
      return error;

   // sync spelling engine
   syncSpellingEngineDictionaries();

   // return
   pResponse->setResult(json::toJsonArray(dictManager.custom().dictionaries()));
   return Success();
}

Error removeCustomDictionary(const json::JsonRpcRequest& request,
                             json::JsonRpcResponse* pResponse)
{
   // get the argument
   std::string name;
   Error error = json::readParams(request.params, &name);
   if (error)
      return error;

   // perform the remove
   using namespace rstudio::core::spelling;
   HunspellDictionaryManager dictManager = hunspellDictionaryManager();
   error = dictManager.custom().remove(name);
   if (error)
      return error;

   // sync spelling engine
   syncSpellingEngineDictionaries();

   // return
   pResponse->setResult(json::toJsonArray(dictManager.custom().dictionaries()));
   return Success();
}

Error installAllDictionaries(const json::JsonRpcRequest& request,
                             json::JsonRpcResponse* pResponse)
{
   // form system path to all languages dir
   std::string targetDir = string_utils::utf8ToSystem(
                                    allLanguagesDir().absolutePath());

   // perform the download
   r::exec::RFunction dlFunc(".rs.downloadAllDictionaries",
                                targetDir,
                                module_context::haveSecureDownloadFileMethod());
   Error error = dlFunc.call();
   if (error)
   {
      std::string userMessage = r::endUserErrorMessage(error);
      pResponse->setError(error, json::Value(userMessage));
      return Success();
   }
   else
   {
      pResponse->setResult(spelling::spellingPrefsContextAsJson());
      return Success();
   }
}

// reset dictionary on user settings changed
void onUserSettingsChanged()
{
   syncSpellingEngineDictionaries();
}

SEXP rs_dictionariesPath()
{
   r::sexp::Protect protect;
   return r::sexp::create(
            options().hunspellDictionariesPath().absolutePath(),
            &protect);
}

SEXP rs_userDictionariesPath()
{
   r::sexp::Protect protect;
   return r::sexp::create(
            userDictionariesDir().absolutePath(),
            &protect);
}

} // anonymous namespace

core::json::Object spellingPrefsContextAsJson()
{
   using namespace rstudio::core::spelling;

   core::json::Object contextJson;

   HunspellDictionaryManager dictManager = hunspellDictionaryManager();
   std::vector<HunspellDictionary> dictionaries;
   Error error = dictManager.availableLanguages(&dictionaries);
   if (error)
   {
      LOG_ERROR(error);
      return core::json::Object();
   }

   core::json::Array dictionariesJson;
   std::transform(dictionaries.begin(),
                  dictionaries.end(),
                  std::back_inserter(dictionariesJson),
                  dictionaryAsJson);

   std::vector<std::string> customDicts = dictManager.custom().dictionaries();
   core::json::Array customDictsJson = json::toJsonArray(customDicts);

   // return json
   contextJson["all_languages_installed"] = dictManager.allLanguagesInstalled();
   contextJson["available_languages"] = dictionariesJson;
   contextJson["custom_dictionaries"] = customDictsJson;
   return contextJson;
}

Error initialize()
{
   RS_REGISTER_CALL_METHOD(rs_checkSpelling);
   RS_REGISTER_CALL_METHOD(rs_dictionariesPath);
   RS_REGISTER_CALL_METHOD(rs_userDictionariesPath);

   // initialize spelling engine
   using namespace rstudio::core::spelling;
   HunspellSpellingEngine* pHunspell = new HunspellSpellingEngine(
                                             userSettings().spellingLanguage(),
                                             hunspellDictionaryManager(),
                                             &r::util::iconvstr);
   s_pSpellingEngine.reset(pHunspell);

   // connect to user settings changed
   userSettings().onChanged.connect(onUserSettingsChanged);

   // register rpc methods
   using boost::bind;
   using namespace module_context;
   ExecBlock initBlock ;
   initBlock.addFunctions()
      (bind(registerRpcMethod, "check_spelling", checkSpelling))
      (bind(registerRpcMethod, "suggestion_list", suggestionList))
      (bind(registerRpcMethod, "get_word_chars", getWordChars))
      (bind(registerRpcMethod, "add_custom_dictionary", addCustomDictionary))
      (bind(registerRpcMethod, "remove_custom_dictionary", removeCustomDictionary))
      (bind(registerRpcMethod, "install_all_dictionaries", installAllDictionaries))
      (bind(registerUriHandler, "/dictionaries", handleDictionaryRequest))
      (bind(sourceModuleRFile, "SessionSpelling.R"));
   return initBlock.execute();
}

} // namespace spelling
} // namespace modules
} // namespace session
} // namespace rstudio

<|endoftext|>