<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include "ICUXalanNumberFormatProxy.hpp"

#include <vector>

#include <unicode/dcfmtsym.h>
#include <unicode/decimfmt.h>

#include <PlatformSupport/DOMStringHelper.hpp>

inline UnicodeString
XalanDOMStringToUnicodeString(const XalanDOMString&		theString)
{
	const XalanDOMChar* const	theBuffer = c_wstr(theString);

	if (theBuffer == 0)
	{
		return UnicodeString();
	}
	else
	{
		return UnicodeString(theBuffer, length(theBuffer));
	}
}

inline XalanDOMString
UnicodeStringToXalanDOMString(const UnicodeString&	theString)
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::vector;
#endif

	vector<XalanDOMChar>	theBuffer;

	const int32_t			theLength = theString.length();

	theBuffer.reserve(theLength);

	for (int32_t i = 0; i < theLength; ++i)
	{
		theBuffer.push_back(theString[i]);
	}

	return XalanDOMString(&theBuffer[0], theBuffer.size());
}

ICUXalanNumberFormatProxy::ICUXalanNumberFormatProxy() :
	XalanNumberFormat(),
	m_decimalFormat(0)
{
	UErrorCode	theResult = U_ZERO_ERROR;

	m_decimalFormat = new DecimalFormat(theResult);
}

ICUXalanNumberFormatProxy::~ICUXalanNumberFormatProxy()
{
	delete m_decimalFormat;
}

XalanDOMString
ICUXalanNumberFormatProxy::format(double	theValue)
{
	UnicodeString	theResult;

	m_decimalFormat->format(theValue, theResult);

	return UnicodeStringToXalanDOMString(theResult);
}

XalanDOMString
ICUXalanNumberFormatProxy::format(int	theValue)
{
	UnicodeString	theResult;

	m_decimalFormat->format(static_cast<long int>(theValue), theResult);

	return UnicodeStringToXalanDOMString(theResult);
}

XalanDOMString
ICUXalanNumberFormatProxy::format(unsigned int	theValue)
{
	UnicodeString	theResult;

	m_decimalFormat->format(static_cast<long int>(theValue), theResult);

	return UnicodeStringToXalanDOMString(theResult);
}

XalanDOMString
ICUXalanNumberFormatProxy::format(long	theValue)
{
	UnicodeString	theResult;

	m_decimalFormat->format(theValue, theResult);

	return UnicodeStringToXalanDOMString(theResult);
}

XalanDOMString
ICUXalanNumberFormatProxy::format(unsigned long	theValue)
{
	UnicodeString	theResult;

	m_decimalFormat->format(static_cast<long int>(theValue), theResult);

	return UnicodeStringToXalanDOMString(theResult);
}

bool
ICUXalanNumberFormatProxy::isGroupingUsed() const
{
	return m_decimalFormat->isGroupingUsed() ? true : false;
}

void
ICUXalanNumberFormatProxy::setGroupingUsed(bool bUsed)
{
	m_decimalFormat->setGroupingUsed(bUsed);
}

void
ICUXalanNumberFormatProxy::setGroupingSize(unsigned long	size)
{
	assert(size > 0);

	m_decimalFormat->setGroupingSize(size);
}

void
ICUXalanNumberFormatProxy::setGroupingSeparator(const XalanDOMString&	s)
{
	const DecimalFormatSymbols* const	theCurrentSymbols =
				m_decimalFormat->getDecimalFormatSymbols();
	assert(theCurrentSymbols != 0);

	DecimalFormatSymbols* const		theNewSymbols =
		new DecimalFormatSymbols(*theCurrentSymbols);

	theNewSymbols->setGroupingSeparator(charAt(s, 0));

	m_decimalFormat->adoptDecimalFormatSymbols(theNewSymbols);
}
<commit_msg>Linux fixes.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include "ICUXalanNumberFormatProxy.hpp"

#include <vector>

#include <unicode/dcfmtsym.h>
#include <unicode/decimfmt.h>

#include <PlatformSupport/DOMStringHelper.hpp>

#include "ICUBridge.hpp"

ICUXalanNumberFormatProxy::ICUXalanNumberFormatProxy() :
	XalanNumberFormat(),
	m_decimalFormat(0)
{
	UErrorCode	theResult = U_ZERO_ERROR;

	m_decimalFormat = new DecimalFormat(theResult);
}

ICUXalanNumberFormatProxy::~ICUXalanNumberFormatProxy()
{
	delete m_decimalFormat;
}

XalanDOMString
ICUXalanNumberFormatProxy::format(double	theValue)
{
	UnicodeString	theResult;

	m_decimalFormat->format(theValue, theResult);

	return ICUBridge::UnicodeStringToXalanDOMString(theResult);
}

XalanDOMString
ICUXalanNumberFormatProxy::format(int	theValue)
{
	UnicodeString	theResult;

	m_decimalFormat->format(int32_t(theValue), theResult);

	return ICUBridge::UnicodeStringToXalanDOMString(theResult);
}

XalanDOMString
ICUXalanNumberFormatProxy::format(unsigned int	theValue)
{
	UnicodeString	theResult;

	m_decimalFormat->format(int32_t(theValue), theResult);

	return ICUBridge::UnicodeStringToXalanDOMString(theResult);
}

XalanDOMString
ICUXalanNumberFormatProxy::format(long	theValue)
{
	UnicodeString	theResult;

	m_decimalFormat->format(int32_t(theValue), theResult);

	return ICUBridge::UnicodeStringToXalanDOMString(theResult);
}

XalanDOMString
ICUXalanNumberFormatProxy::format(unsigned long	theValue)
{
	UnicodeString	theResult;

	m_decimalFormat->format(int32_t(theValue), theResult);

	return ICUBridge::UnicodeStringToXalanDOMString(theResult);
}

bool
ICUXalanNumberFormatProxy::isGroupingUsed() const
{
	return m_decimalFormat->isGroupingUsed() ? true : false;
}

void
ICUXalanNumberFormatProxy::setGroupingUsed(bool bUsed)
{
	m_decimalFormat->setGroupingUsed(bUsed);
}

void
ICUXalanNumberFormatProxy::setGroupingSize(unsigned long	size)
{
	assert(size > 0);

	m_decimalFormat->setGroupingSize(size);
}

void
ICUXalanNumberFormatProxy::setGroupingSeparator(const XalanDOMString&	s)
{
	const DecimalFormatSymbols* const	theCurrentSymbols =
				m_decimalFormat->getDecimalFormatSymbols();
	assert(theCurrentSymbols != 0);

	DecimalFormatSymbols* const		theNewSymbols =
		new DecimalFormatSymbols(*theCurrentSymbols);

	theNewSymbols->setGroupingSeparator(charAt(s, 0));

	m_decimalFormat->adoptDecimalFormatSymbols(theNewSymbols);
}
<|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include <TestSuite/Tester.h>
#include <limits>

#include "Math/Geometry/Intersection.h"

namespace Magnum { namespace Math { namespace Geometry { namespace Test {

class IntersectionTest: public Corrade::TestSuite::Tester {
    public:
        IntersectionTest();

        void planeLine();
};

typedef Math::Vector3<Float> Vector3;

IntersectionTest::IntersectionTest() {
    addTests({&IntersectionTest::planeLine});
}

void IntersectionTest::planeLine() {
    Vector3 planePosition(-1.0f, 1.0f, 0.5f);
    Vector3 planeNormal(0.0f, 0.0f, 1.0f);

    /* Inside line segment */
    CORRADE_COMPARE((Intersection::planeLine(planePosition, planeNormal,
        Vector3(0.0f, 0.0f, -1.0f), Vector3(0.0f, 0.0f, 2.0f))), 0.75f);

    /* Outside line segment */
    CORRADE_COMPARE((Intersection::planeLine(planePosition, planeNormal,
        Vector3(0.0f, 0.0f, 1.0f), Vector3(0.0f, 0.0f, 1.0f))), -0.5f);

    /* Line lies on the plane */
    CORRADE_COMPARE(Intersection::planeLine(planePosition, planeNormal,
        Vector3(1.0f, 0.5f, 0.5f), Vector3(-1.0f, 0.5f, 0.0f)), std::numeric_limits<Float>::quiet_NaN());

    /* Line is parallell to the plane */
    CORRADE_COMPARE((Intersection::planeLine(planePosition, planeNormal,
        Vector3(1.0f, 0.0f, 1.0f), Vector3(-1.0f, 0.0f, 0.0f))), -std::numeric_limits<Float>::infinity());
}

}}}}

CORRADE_TEST_MAIN(Magnum::Math::Geometry::Test::IntersectionTest)
<commit_msg>Math: more Intersection test cleanup.<commit_after>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include <limits>
#include <TestSuite/Tester.h>

#include "Math/Geometry/Intersection.h"

namespace Magnum { namespace Math { namespace Geometry { namespace Test {

class IntersectionTest: public Corrade::TestSuite::Tester {
    public:
        IntersectionTest();

        void planeLine();
};

typedef Math::Vector3<Float> Vector3;

IntersectionTest::IntersectionTest() {
    addTests({&IntersectionTest::planeLine});
}

void IntersectionTest::planeLine() {
    const Vector3 planePosition(-1.0f, 1.0f, 0.5f);
    const Vector3 planeNormal(0.0f, 0.0f, 1.0f);

    /* Inside line segment */
    CORRADE_COMPARE(Intersection::planeLine(planePosition, planeNormal,
        {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, 2.0f}), 0.75f);

    /* Outside line segment */
    CORRADE_COMPARE(Intersection::planeLine(planePosition, planeNormal,
        {0.0f, 0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}), -0.5f);

    /* Line lies on the plane */
    CORRADE_COMPARE(Intersection::planeLine(planePosition, planeNormal,
        {1.0f, 0.5f, 0.5f}, {-1.0f, 0.5f, 0.0f}), std::numeric_limits<Float>::quiet_NaN());

    /* Line is parallel to the plane */
    CORRADE_COMPARE(Intersection::planeLine(planePosition, planeNormal,
        {1.0f, 0.0f, 1.0f}, {-1.0f, 0.0f, 0.0f}), -std::numeric_limits<Float>::infinity());
}

}}}}

CORRADE_TEST_MAIN(Magnum::Math::Geometry::Test::IntersectionTest)
<|endoftext|>


<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparamsbase.h"

#include "assert.h"
#include "util.h"

#include <boost/assign/list_of.hpp>

using namespace boost::assign;

//
// Main network
//

class CBaseMainParams : public CBaseChainParams {
public:
    CBaseMainParams() {
        networkID = CBaseChainParams::MAIN;
        nRPCPort = 8332;
    }
};
static CBaseMainParams mainParams;

//
// Testnet (v3)
//
class CBaseTestNetParams : public CBaseMainParams {
public:
    CBaseTestNetParams() {
        networkID = CBaseChainParams::TESTNET;
        nRPCPort = 18332;
        strDataDir = "testnet3";
    }
};
static CBaseTestNetParams testNetParams;

//
// Regression test
//
class CBaseRegTestParams : public CBaseTestNetParams {
public:
    CBaseRegTestParams() {
        networkID = CBaseChainParams::REGTEST;
        strDataDir = "regtest";
    }
};
static CBaseRegTestParams regTestParams;

static CBaseChainParams *pCurrentBaseParams = 0;

const CBaseChainParams &BaseParams() {
    assert(pCurrentBaseParams);
    return *pCurrentBaseParams;
}

void SelectBaseParams(CBaseChainParams::Network network) {
    switch (network) {
        case CBaseChainParams::MAIN:
            pCurrentBaseParams = &mainParams;
            break;
        case CBaseChainParams::TESTNET:
            pCurrentBaseParams = &testNetParams;
            break;
        case CBaseChainParams::REGTEST:
            pCurrentBaseParams = &regTestParams;
            break;
        default:
            assert(false && "Unimplemented network");
            return;
    }
}

bool SelectBaseParamsFromCommandLine() {
    bool fRegTest = GetBoolArg("-regtest", false);
    bool fTestNet = GetBoolArg("-testnet", false);

    if (fTestNet && fRegTest) {
        return false;
    }

    if (fRegTest) {
        SelectBaseParams(CBaseChainParams::REGTEST);
    } else if (fTestNet) {
        SelectBaseParams(CBaseChainParams::TESTNET);
    } else {
        SelectBaseParams(CBaseChainParams::MAIN);
    }
    return true;
}

bool AreBaseParamsConfigured() {
    return pCurrentBaseParams != NULL;
}
<commit_msg>rpc port set to 49044.<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparamsbase.h"

#include "assert.h"
#include "util.h"

#include <boost/assign/list_of.hpp>

using namespace boost::assign;

//
// Main network
//

class CBaseMainParams : public CBaseChainParams {
public:
    CBaseMainParams() {
        networkID = CBaseChainParams::MAIN;
        nRPCPort = 49044;
    }
};
static CBaseMainParams mainParams;

//
// Testnet (v3)
//
class CBaseTestNetParams : public CBaseMainParams {
public:
    CBaseTestNetParams() {
        networkID = CBaseChainParams::TESTNET;
        nRPCPort = 18332;
        strDataDir = "testnet3";
    }
};
static CBaseTestNetParams testNetParams;

//
// Regression test
//
class CBaseRegTestParams : public CBaseTestNetParams {
public:
    CBaseRegTestParams() {
        networkID = CBaseChainParams::REGTEST;
        strDataDir = "regtest";
    }
};
static CBaseRegTestParams regTestParams;

static CBaseChainParams *pCurrentBaseParams = 0;

const CBaseChainParams &BaseParams() {
    assert(pCurrentBaseParams);
    return *pCurrentBaseParams;
}

void SelectBaseParams(CBaseChainParams::Network network) {
    switch (network) {
        case CBaseChainParams::MAIN:
            pCurrentBaseParams = &mainParams;
            break;
        case CBaseChainParams::TESTNET:
            pCurrentBaseParams = &testNetParams;
            break;
        case CBaseChainParams::REGTEST:
            pCurrentBaseParams = &regTestParams;
            break;
        default:
            assert(false && "Unimplemented network");
            return;
    }
}

bool SelectBaseParamsFromCommandLine() {
    bool fRegTest = GetBoolArg("-regtest", false);
    bool fTestNet = GetBoolArg("-testnet", false);

    if (fTestNet && fRegTest) {
        return false;
    }

    if (fRegTest) {
        SelectBaseParams(CBaseChainParams::REGTEST);
    } else if (fTestNet) {
        SelectBaseParams(CBaseChainParams::TESTNET);
    } else {
        SelectBaseParams(CBaseChainParams::MAIN);
    }
    return true;
}

bool AreBaseParamsConfigured() {
    return pCurrentBaseParams != NULL;
}
<|endoftext|>


<commit_before>#include "pjobrunnersessionwrapper.h"
#include <QtCore/QRegExp>
#include <iostream>
#include <QtCore/QThread>
#include <QtCore/QWaitCondition>
#include <QtCore/QMutex>

unsigned int s_standard_timeout = 20000;

PJobRunnerSessionWrapper::PJobRunnerSessionWrapper(QHostAddress hostname, long timeout)
    : m_peer(hostname)
{
    m_valid = false;
    m_socket.connectToHost(hostname, 23023);
    if(!m_socket.waitForConnected(timeout)) return;
    send("hello\n");
    if(!m_socket.waitForBytesWritten(s_standard_timeout)) return;
    if(!m_socket.waitForReadyRead(s_standard_timeout)) return;
    QString hello_string;
    do{
        hello_string.append(m_socket.readAll());
    }while(m_socket.waitForReadyRead(1000) && hello_string.size() < 1024);
    received(hello_string);

    if(hello_string.isEmpty()) return;

    QRegExp reg_exp("This is ([^\\s]*) \\(.*\\) version ([^\\s]*) running on ([^\\s]*) \\(([^\\s]*)\\)");

    if(reg_exp.indexIn(hello_string) == -1) return;
    m_version = reg_exp.cap(2);
    m_platform = reg_exp.cap(4);
    m_hostname = reg_exp.cap(3);
    m_valid = true;
}

PJobRunnerSessionWrapper::~PJobRunnerSessionWrapper(){
    if(m_socket.state() == QAbstractSocket::ConnectedState){
        send("exit()\n");
        m_socket.waitForBytesWritten(100);
        m_socket.close();
        m_socket.waitForDisconnected(1000);
    }
}

bool PJobRunnerSessionWrapper::is_valid(){
    return m_valid;
}

QString PJobRunnerSessionWrapper::platform(){
    return m_platform;
}

QString PJobRunnerSessionWrapper::version(){
    return m_version;
}

QString PJobRunnerSessionWrapper::hostname(){
    return m_hostname;
}

bool PJobRunnerSessionWrapper::upload_pjobfile(const QByteArray& content){
    send("prepare_push_connection()\n");
    if(!m_socket.waitForReadyRead(s_standard_timeout))throw LostConnectionException(m_socket.peerName().toStdString(), "waiting for prepare_push_connection() reply.");
    QString line = m_socket.readLine();
    received(line);
    bool ok;
    quint32 port = line.toInt(&ok);
    if(! ok) return false;

    emit debug_out(QString("Opening data connection to port %1... ").arg(port));
    QTcpSocket push_connection;
    push_connection.connectToHost(m_socket.peerAddress(), port);
    if(!push_connection.waitForConnected(s_standard_timeout))throw LostConnectionException(push_connection.peerName().toStdString(), QString("Could not connect to port %1 for uploading.").arg(port).toStdString());

    qint64 bytes_send = 0;
    qint64 all_bytes = content.size();
    const char* data = content.data();
    qint64 transfer_unit_size = 1024*1024;

    while((bytes_send != all_bytes) && (push_connection.state() == QTcpSocket::ConnectedState)){
        push_connection.flush();
        qint64 bytes_written = push_connection.write(data, std::min(transfer_unit_size,all_bytes-bytes_send));
        data += bytes_written;
        bytes_send += bytes_written;
        push_connection.waitForBytesWritten(500);
        emit upload_progress(bytes_send * 100 / all_bytes);
    }
    if(bytes_send != all_bytes){
        emit debug_out(QString("Uploading pjobfile failed! Only %1 bytes out of %1 uploaded.").arg(bytes_send).arg(all_bytes));
        return false;
    }
    push_connection.close();
    push_connection.waitForDisconnected(s_standard_timeout);
    emit debug_out(QString("%1 bytes uploaded!").arg(content.size()));
    return true;
}

bool PJobRunnerSessionWrapper::download_results(QByteArray& data){
    send("prepare_pull_connection_for_results()\n");
    if(!m_socket.waitForReadyRead(s_standard_timeout))throw LostConnectionException(m_socket.peerName().toStdString(), "waiting for prepare_pull_connection_for_results() reply.");
    QString line = m_socket.readLine();
    received(line);
    QString all = m_socket.readAll();
    received(all);
    bool ok;
    quint32 port = line.toInt(&ok);
    if(! ok) return false;
    emit debug_out(QString("Pulling from port %1...").arg(port));
    QTcpSocket pull_connection;
    pull_connection.connectToHost(m_socket.peerAddress(), port);
    if(!pull_connection.waitForConnected(s_standard_timeout)) throw LostConnectionException(pull_connection.peerName().toStdString(), QString("Could not connect to port %1 for downloading.").arg(port).toStdString());;
    if(!pull_connection.waitForReadyRead(s_standard_timeout)) throw LostConnectionException(pull_connection.peerName().toStdString(), QString("Got nothing when waiting for data to download from port %1.").arg(port).toStdString());;

    while(true){
        if(pull_connection.state() == QTcpSocket::UnconnectedState){
            while(pull_connection.bytesAvailable())
                data.append(pull_connection.readAll());
            break;
        }
        if(pull_connection.waitForReadyRead(100)){
            data.append(pull_connection.readAll());
        }
    }
    return true;
}

bool PJobRunnerSessionWrapper::set_parameter(const QString& name, const double& value){
    send(QString("set_parameter(\"%1\",%2);\n").arg(name).arg(value));
    if(!m_socket.waitForReadyRead(s_standard_timeout))throw LostConnectionException(m_socket.peerName().toStdString(), QString("waiting for set_parameter() reply.").toStdString());
    return true;
}

bool PJobRunnerSessionWrapper::open_pjob_from_uploaded_data(){
    QString line;
    unsigned int i=0;
    do{
        if(i>=10){
            emit debug_out("Failed to open PJob file after 10 retries. Giving up...");
            return false;
        }
        if(i>0){
            QWaitCondition sleep;
            QMutex mutex;
            sleep.wait(&mutex, 500*(rand()%10));
        }
        if(line.isEmpty() || line.contains("Can't open pjob file!")){
            send("open_pjob_from_received_data()\n");
        }
        line = m_socket.readLine();
        if(line.isEmpty()){
            m_socket.waitForReadyRead(s_standard_timeout);
        }else{
            received(line);
        }
        i++;
    }while(!line.contains("pjob file opened from received data.") && m_socket.state() == QTcpSocket::ConnectedState);
    return true;
}

bool PJobRunnerSessionWrapper::run_job(){
    send("run_job()\n");
    if(!m_socket.waitForReadyRead(s_standard_timeout)) LostConnectionException(m_socket.peerName().toStdString(), "waiting for run_job() reply.");

    QByteArray buffer;
    do{
        buffer.append(m_socket.readAll());
        foreach(QByteArray line, buffer.split('\n')){
            received(line);
            if(line.contains("Starting process:"))
                return true;
            if(line.contains("Starting process:"))
                return true;
            if(line.contains("Can't"))
                return false;
            if(line.contains("ERROR!"))
                return false;
            if(line.contains("Process could not be started!"))
                return false;
        }
    }while(m_socket.waitForReadyRead(s_standard_timeout*5) && m_socket.state() == QTcpSocket::ConnectedState);
    return false;
}

bool PJobRunnerSessionWrapper::wait_for_job_finished(){
    bool ok=false;
    bool want_exit=false;
    while(!want_exit && m_socket.state() == QTcpSocket::ConnectedState){
        QString line = m_socket.readAll();
        if(line.isEmpty()){
            m_socket.waitForReadyRead(200);
            continue;
        }

        while(line.endsWith('\n') || line.endsWith('\r')) line.chop(1);
        received(line);
        emit job_std_out(line);
        if(line.contains("Process exited normally.")){ ok = true; want_exit = true; }
        if(line.contains("Process crashed!")) want_exit = true;
        if(line.contains("ERROR!")) want_exit = true;
        if(line.contains("Process could not be started!")) want_exit = true;
    }
    while(m_socket.waitForReadyRead(s_standard_timeout/60)){
        received(m_socket.readAll());
    }
    return ok;
}

QHostAddress PJobRunnerSessionWrapper::peer(){
    return m_peer;
}

bool PJobRunnerSessionWrapper::enqueue(){
    send("enqueue();\n");
    if(!m_socket.waitForReadyRead(s_standard_timeout)) return false;
    QString line = m_socket.readAll();
    received(line);
    if(line.contains("Successfully added to queue.")) return true;
    else return false;
}

bool PJobRunnerSessionWrapper::wait_till_its_your_turn(){
    QString buffer;
    while(m_socket.isReadable() && m_socket.state() == QAbstractSocket::ConnectedState){
        if(m_socket.waitForReadyRead(5000)){
            QByteArray read = m_socket.readAll();
            buffer.append(read);
            received(read);
            if(buffer.contains("It's your turn now! Go!")) return true;
        }
    }
    return false;
}

int PJobRunnerSessionWrapper::max_process_count(){
    send("max_process_count();\n");
    if(!m_socket.waitForReadyRead(s_standard_timeout)) throw LostConnectionException(m_socket.peerName().toStdString(), "waiting for max_process_count() reply.");
    bool ok;
    QString line = m_socket.readAll();
    received(line);
    int value = line.toInt(&ok);
    if(ok) return value;
    else throw QString("connection problem");
}

int PJobRunnerSessionWrapper::process_count(){
    send("process_count();\n");
    if(!m_socket.waitForReadyRead(s_standard_timeout)) throw LostConnectionException(m_socket.peerName().toStdString(), "waiting for process_count() reply.");
    bool ok;
    QString line = m_socket.readAll();
    received(line);
    int value = line.toInt(&ok);
    if(ok) return value;
    else throw QString("connection problem");
}

void PJobRunnerSessionWrapper::set_debug(bool b){
    m_debug_mode = b;
}

void PJobRunnerSessionWrapper::send(QString data){
    m_socket.write(data.toUtf8());
    if(!data.endsWith("\n")) data.append("\n");
    if(m_debug_mode) emit debug_out(QString(">>> %1").arg(data).arg(m_peer.toString()));
}

void PJobRunnerSessionWrapper::received(QString data){
    if(!data.endsWith("\n")) data.append("\n");
    if(m_debug_mode) emit debug_out(QString("%1").arg(data).arg(m_peer.toString()));
}

bool PJobRunnerSessionWrapper::open_pjob_from_user_file(QString name){
    send(QString("open_pjob_from_saved_file(\"%1\");\n").arg(name));
    if(!m_socket.waitForReadyRead(s_standard_timeout)) throw LostConnectionException(m_socket.peerName().toStdString(), "waiting for open_pjob_from_saved_file() reply.");
    QString line = m_socket.readAll();
    received(line);
    return line.contains("File found. Opening PJob");
}

bool PJobRunnerSessionWrapper::save_user_file(QString name){
    send(QString("save_received_data(\"%1\")\n").arg(name));
    if(!m_socket.waitForReadyRead(s_standard_timeout)) throw LostConnectionException(m_socket.peerName().toStdString(), "waiting for save_received_data() reply.");
    QString line = m_socket.readAll();
    received(line);
    return line.contains("Received data successfully saved");
}
<commit_msg>PJobRunnerSessionWrapper::save_user_file() timeout decreased.<commit_after>#include "pjobrunnersessionwrapper.h"
#include <QtCore/QRegExp>
#include <iostream>
#include <QtCore/QThread>
#include <QtCore/QWaitCondition>
#include <QtCore/QMutex>

unsigned int s_standard_timeout = 20000;

PJobRunnerSessionWrapper::PJobRunnerSessionWrapper(QHostAddress hostname, long timeout)
    : m_peer(hostname)
{
    m_valid = false;
    m_socket.connectToHost(hostname, 23023);
    if(!m_socket.waitForConnected(timeout)) return;
    send("hello\n");
    if(!m_socket.waitForBytesWritten(s_standard_timeout)) return;
    if(!m_socket.waitForReadyRead(s_standard_timeout)) return;
    QString hello_string;
    do{
        hello_string.append(m_socket.readAll());
    }while(m_socket.waitForReadyRead(1000) && hello_string.size() < 1024);
    received(hello_string);

    if(hello_string.isEmpty()) return;

    QRegExp reg_exp("This is ([^\\s]*) \\(.*\\) version ([^\\s]*) running on ([^\\s]*) \\(([^\\s]*)\\)");

    if(reg_exp.indexIn(hello_string) == -1) return;
    m_version = reg_exp.cap(2);
    m_platform = reg_exp.cap(4);
    m_hostname = reg_exp.cap(3);
    m_valid = true;
}

PJobRunnerSessionWrapper::~PJobRunnerSessionWrapper(){
    if(m_socket.state() == QAbstractSocket::ConnectedState){
        send("exit()\n");
        m_socket.waitForBytesWritten(100);
        m_socket.close();
        m_socket.waitForDisconnected(1000);
    }
}

bool PJobRunnerSessionWrapper::is_valid(){
    return m_valid;
}

QString PJobRunnerSessionWrapper::platform(){
    return m_platform;
}

QString PJobRunnerSessionWrapper::version(){
    return m_version;
}

QString PJobRunnerSessionWrapper::hostname(){
    return m_hostname;
}

bool PJobRunnerSessionWrapper::upload_pjobfile(const QByteArray& content){
    send("prepare_push_connection()\n");
    if(!m_socket.waitForReadyRead(s_standard_timeout))throw LostConnectionException(m_socket.peerName().toStdString(), "waiting for prepare_push_connection() reply.");
    QString line = m_socket.readLine();
    received(line);
    bool ok;
    quint32 port = line.toInt(&ok);
    if(! ok) return false;

    emit debug_out(QString("Opening data connection to port %1... ").arg(port));
    QTcpSocket push_connection;
    push_connection.connectToHost(m_socket.peerAddress(), port);
    if(!push_connection.waitForConnected(s_standard_timeout))throw LostConnectionException(push_connection.peerName().toStdString(), QString("Could not connect to port %1 for uploading.").arg(port).toStdString());

    qint64 bytes_send = 0;
    qint64 all_bytes = content.size();
    const char* data = content.data();
    qint64 transfer_unit_size = 1024*1024;

    while((bytes_send != all_bytes) && (push_connection.state() == QTcpSocket::ConnectedState)){
        push_connection.flush();
        qint64 bytes_written = push_connection.write(data, std::min(transfer_unit_size,all_bytes-bytes_send));
        data += bytes_written;
        bytes_send += bytes_written;
        push_connection.waitForBytesWritten(500);
        emit upload_progress(bytes_send * 100 / all_bytes);
    }
    if(bytes_send != all_bytes){
        emit debug_out(QString("Uploading pjobfile failed! Only %1 bytes out of %1 uploaded.").arg(bytes_send).arg(all_bytes));
        return false;
    }
    push_connection.close();
    push_connection.waitForDisconnected(s_standard_timeout);
    emit debug_out(QString("%1 bytes uploaded!").arg(content.size()));
    return true;
}

bool PJobRunnerSessionWrapper::download_results(QByteArray& data){
    send("prepare_pull_connection_for_results()\n");
    if(!m_socket.waitForReadyRead(s_standard_timeout))throw LostConnectionException(m_socket.peerName().toStdString(), "waiting for prepare_pull_connection_for_results() reply.");
    QString line = m_socket.readLine();
    received(line);
    QString all = m_socket.readAll();
    received(all);
    bool ok;
    quint32 port = line.toInt(&ok);
    if(! ok) return false;
    emit debug_out(QString("Pulling from port %1...").arg(port));
    QTcpSocket pull_connection;
    pull_connection.connectToHost(m_socket.peerAddress(), port);
    if(!pull_connection.waitForConnected(s_standard_timeout)) throw LostConnectionException(pull_connection.peerName().toStdString(), QString("Could not connect to port %1 for downloading.").arg(port).toStdString());;
    if(!pull_connection.waitForReadyRead(s_standard_timeout)) throw LostConnectionException(pull_connection.peerName().toStdString(), QString("Got nothing when waiting for data to download from port %1.").arg(port).toStdString());;

    while(true){
        if(pull_connection.state() == QTcpSocket::UnconnectedState){
            while(pull_connection.bytesAvailable())
                data.append(pull_connection.readAll());
            break;
        }
        if(pull_connection.waitForReadyRead(100)){
            data.append(pull_connection.readAll());
        }
    }
    return true;
}

bool PJobRunnerSessionWrapper::set_parameter(const QString& name, const double& value){
    send(QString("set_parameter(\"%1\",%2);\n").arg(name).arg(value));
    if(!m_socket.waitForReadyRead(s_standard_timeout))throw LostConnectionException(m_socket.peerName().toStdString(), QString("waiting for set_parameter() reply.").toStdString());
    return true;
}

bool PJobRunnerSessionWrapper::open_pjob_from_uploaded_data(){
    QString line;
    unsigned int i=0;
    do{
        if(i>=10){
            emit debug_out("Failed to open PJob file after 10 retries. Giving up...");
            return false;
        }
        if(i>0){
            QWaitCondition sleep;
            QMutex mutex;
            sleep.wait(&mutex, 500*(rand()%10));
        }
        if(line.isEmpty() || line.contains("Can't open pjob file!")){
            send("open_pjob_from_received_data()\n");
        }
        line = m_socket.readLine();
        if(line.isEmpty()){
            m_socket.waitForReadyRead(s_standard_timeout);
        }else{
            received(line);
        }
        i++;
    }while(!line.contains("pjob file opened from received data.") && m_socket.state() == QTcpSocket::ConnectedState);
    return true;
}

bool PJobRunnerSessionWrapper::run_job(){
    send("run_job()\n");
    if(!m_socket.waitForReadyRead(s_standard_timeout)) LostConnectionException(m_socket.peerName().toStdString(), "waiting for run_job() reply.");

    QByteArray buffer;
    do{
        buffer.append(m_socket.readAll());
        foreach(QByteArray line, buffer.split('\n')){
            received(line);
            if(line.contains("Starting process:"))
                return true;
            if(line.contains("Starting process:"))
                return true;
            if(line.contains("Can't"))
                return false;
            if(line.contains("ERROR!"))
                return false;
            if(line.contains("Process could not be started!"))
                return false;
        }
    }while(m_socket.waitForReadyRead(s_standard_timeout*5) && m_socket.state() == QTcpSocket::ConnectedState);
    return false;
}

bool PJobRunnerSessionWrapper::wait_for_job_finished(){
    bool ok=false;
    bool want_exit=false;
    while(!want_exit && m_socket.state() == QTcpSocket::ConnectedState){
        QString line = m_socket.readAll();
        if(line.isEmpty()){
            m_socket.waitForReadyRead(200);
            continue;
        }

        while(line.endsWith('\n') || line.endsWith('\r')) line.chop(1);
        received(line);
        emit job_std_out(line);
        if(line.contains("Process exited normally.")){ ok = true; want_exit = true; }
        if(line.contains("Process crashed!")) want_exit = true;
        if(line.contains("ERROR!")) want_exit = true;
        if(line.contains("Process could not be started!")) want_exit = true;
    }
    while(m_socket.waitForReadyRead(s_standard_timeout/60)){
        received(m_socket.readAll());
    }
    return ok;
}

QHostAddress PJobRunnerSessionWrapper::peer(){
    return m_peer;
}

bool PJobRunnerSessionWrapper::enqueue(){
    send("enqueue();\n");
    if(!m_socket.waitForReadyRead(s_standard_timeout)) return false;
    QString line = m_socket.readAll();
    received(line);
    if(line.contains("Successfully added to queue.")) return true;
    else return false;
}

bool PJobRunnerSessionWrapper::wait_till_its_your_turn(){
    QString buffer;
    while(m_socket.isReadable() && m_socket.state() == QAbstractSocket::ConnectedState){
        if(m_socket.waitForReadyRead(5000)){
            QByteArray read = m_socket.readAll();
            buffer.append(read);
            received(read);
            if(buffer.contains("It's your turn now! Go!")) return true;
        }
    }
    return false;
}

int PJobRunnerSessionWrapper::max_process_count(){
    send("max_process_count();\n");
    if(!m_socket.waitForReadyRead(s_standard_timeout)) throw LostConnectionException(m_socket.peerName().toStdString(), "waiting for max_process_count() reply.");
    bool ok;
    QString line = m_socket.readAll();
    received(line);
    int value = line.toInt(&ok);
    if(ok) return value;
    else throw QString("connection problem");
}

int PJobRunnerSessionWrapper::process_count(){
    send("process_count();\n");
    if(!m_socket.waitForReadyRead(s_standard_timeout)) throw LostConnectionException(m_socket.peerName().toStdString(), "waiting for process_count() reply.");
    bool ok;
    QString line = m_socket.readAll();
    received(line);
    int value = line.toInt(&ok);
    if(ok) return value;
    else throw QString("connection problem");
}

void PJobRunnerSessionWrapper::set_debug(bool b){
    m_debug_mode = b;
}

void PJobRunnerSessionWrapper::send(QString data){
    m_socket.write(data.toUtf8());
    if(!data.endsWith("\n")) data.append("\n");
    if(m_debug_mode) emit debug_out(QString(">>> %1").arg(data).arg(m_peer.toString()));
}

void PJobRunnerSessionWrapper::received(QString data){
    if(!data.endsWith("\n")) data.append("\n");
    if(m_debug_mode) emit debug_out(QString("%1").arg(data).arg(m_peer.toString()));
}

bool PJobRunnerSessionWrapper::open_pjob_from_user_file(QString name){
    send(QString("open_pjob_from_saved_file(\"%1\");\n").arg(name));
    if(!m_socket.waitForReadyRead(s_standard_timeout)) throw LostConnectionException(m_socket.peerName().toStdString(), "waiting for open_pjob_from_saved_file() reply.");
    QString line = m_socket.readAll();
    received(line);
    return line.contains("File found. Opening PJob");
}

bool PJobRunnerSessionWrapper::save_user_file(QString name){
    send(QString("save_received_data(\"%1\")\n").arg(name));
    if(!m_socket.waitForReadyRead(500)) throw LostConnectionException(m_socket.peerName().toStdString(), "waiting for save_received_data() reply.");
    QString line = m_socket.readAll();
    received(line);
    return line.contains("Received data successfully saved");
}
<|endoftext|>


<commit_before>#include <common.hpp>
#include <chat/chat.hpp>
#include <mod.hpp>
#include <server.hpp>

using namespace MCPP;

static const String name("Chat Login/Logout Broadcast");
static const Word priority=1;
static const String online(" has come online");
static const String offline(" has gone offline");
static const String start_reason(" (");
static const String end_reason(")");

class LoginLogout : public Module {

	public:

		virtual const String & Name () const noexcept override {

			return name;

		}

		virtual Word Priority () const noexcept override {

			return priority;

		}

		virtual void Install () override {

			auto & server=Server::Get();

			//	Subscribe to the on login event
			server.OnLogin.Add([] (SmartPointer<Client> client) {

				ChatMessage message;
				message	<<	ChatStyle::BrightGreen
						<<	ChatStyle::Bold
						<<	client->GetUsername()
						<<	ChatFormat::Pop
						<<	online;

				Chat::Get().Send(message);

			});

			//	Subscribe to the on disconnect event
			server.OnDisconnect.Add([] (SmartPointer<Client> client, const String & reason) {

				//	Only proceed if the user was authenticated
				if (client->GetState()!=ProtocolState::Play) return;

				ChatMessage message;
				message	<<	ChatStyle::Red
						<<	ChatStyle::Bold
						<<	client->GetUsername()
						<<	ChatFormat::Pop
						<<	offline;

				//	If there was a reason associated with the disconnect,
				//	append that
				if (reason.Size()!=0) message	<<	start_reason
												<<	ChatStyle::Bold
												<<	reason
												<<	ChatFormat::Pop
												<<	end_reason;

				Chat::Get().Send(message);

			});

		}

};

INSTALL_MODULE(LoginLogout)
<commit_msg>Remove Reference to common.hpp<commit_after>#include <rleahylib/rleahylib.hpp>
#include <chat/chat.hpp>
#include <mod.hpp>
#include <server.hpp>

using namespace MCPP;

static const String name("Chat Login/Logout Broadcast");
static const Word priority=1;
static const String online(" has come online");
static const String offline(" has gone offline");
static const String start_reason(" (");
static const String end_reason(")");

class LoginLogout : public Module {

	public:

		virtual const String & Name () const noexcept override {

			return name;

		}

		virtual Word Priority () const noexcept override {

			return priority;

		}

		virtual void Install () override {

			auto & server=Server::Get();

			//	Subscribe to the on login event
			server.OnLogin.Add([] (SmartPointer<Client> client) {

				ChatMessage message;
				message	<<	ChatStyle::BrightGreen
						<<	ChatStyle::Bold
						<<	client->GetUsername()
						<<	ChatFormat::Pop
						<<	online;

				Chat::Get().Send(message);

			});

			//	Subscribe to the on disconnect event
			server.OnDisconnect.Add([] (SmartPointer<Client> client, const String & reason) {

				//	Only proceed if the user was authenticated
				if (client->GetState()!=ProtocolState::Play) return;

				ChatMessage message;
				message	<<	ChatStyle::Red
						<<	ChatStyle::Bold
						<<	client->GetUsername()
						<<	ChatFormat::Pop
						<<	offline;

				//	If there was a reason associated with the disconnect,
				//	append that
				if (reason.Size()!=0) message	<<	start_reason
												<<	ChatStyle::Bold
												<<	reason
												<<	ChatFormat::Pop
												<<	end_reason;

				Chat::Get().Send(message);

			});

		}

};

INSTALL_MODULE(LoginLogout)
<|endoftext|>


<commit_before>// (c) 2015, dividiti
// BSD license

#include "cl_dataset.hpp"
#include "cl_state.hpp"

#include <algorithm>

#include <cassert>
#include <cmath>

#include "xopenme.h"

namespace gemmbench
{

// Initialize the data in a random way.
template<typename T>
void dataset<T>::init_random(unsigned int seed, bool zero_matrix_C)
{
    srand(seed);

    // Initialize the scalars.
    alpha = symmetric_rand();
    beta = symmetric_rand();

    // Initialize the matrices.
    for (cl_ulong i = 0, k = static_cast<cl_ulong>(n) * static_cast<cl_ulong>(n); i < k; ++i)
    {
        matrix_A[i] = symmetric_rand();
        matrix_B[i] = symmetric_rand();
        matrix_C[i] = zero_matrix_C ? static_cast<T>(0) : symmetric_rand();
    }

} // END OF init_random()

// Compare the results against a reference implementation.
template<typename T>
void dataset<T>::verify_results(state & s, T eps)
{
    // Read results from buffer_C.
    {
        assert(s.args.matrix_order == n && "Mismatching matrix orders.");

        cl_command_queue queue = s.queue;
        cl_mem buffer = s.buffer_C;
        cl_bool blocking_read = true;
        size_t offset = 0;
        size_t cb = sizeof(T) * n * n;
        void *ptr = matrix_C;
        cl_uint num_events_in_wait_list = 1;
        const cl_event event_wait_list[1] = { s.enqueue };
        cl_event *event = NULL;

        cl_int err = CL_SUCCESS;
        err = clEnqueueReadBuffer(queue, buffer, blocking_read,
            offset, cb, ptr, num_events_in_wait_list, event_wait_list, event);
        assert(CL_SUCCESS == err && "clEnqueueReadBuffer() failed.");
    }

    // Compute reference and compare the results against it.
    {
        T * matrix_C_ref = new T[n * n];
        const bool transA = s.meta.transA;
        const bool transB = s.meta.transB;
        const bool transC = false;

        // Compute reference.
        for (cl_uint i = 0; i < n; ++i)
        {
            for (cl_uint j = 0; j < n; ++j)
            {
                T ab = static_cast<T>(0);
                for (cl_uint k = 0; k < n; ++k)
                {
                    ab += matrix_A[index(i, k, transA)] * matrix_B[index(k, j, transB)];
                }
                matrix_C_ref[index(i, j, transC)] *= beta;
                matrix_C_ref[index(i, j, transC)] += alpha * ab;
            }
        }

        // Compare the results against reference.
        std::cout << "Comparing the OpenCL and reference results... ";
        T max_abs_diff = static_cast<T>(0);
        for (cl_uint i = 0; i < n; ++i)
        {
            for (cl_uint j = 0; j < n; ++j)
            {
                T abs_diff = abs(matrix_C[index(i, j, transC)] - matrix_C_ref[index(i, j, transC)]);
                max_abs_diff = std::max<T>(max_abs_diff, abs_diff);
                if (abs_diff > eps)
                {
                    std::cerr << "MISMATCH! (first at C[" << i << "][" << j << "])" << std::endl;
 #if (1 == XOPENME)
                    xopenme_add_var_i(s.openme.var_count++, (char*) "  \"RESULTS#match\":%u", 0);
                    assert(s.openme.var_count_below_max() && "xOpenME max var count reached.");
 #endif
                    exit(EXIT_FAILURE);
                }
            }
        }
        std::cout << "MATCH!" << std::endl;
#if (1 == XOPENME)
        xopenme_add_var_i(s.openme.var_count++, (char*) "  \"RESULTS#match\":%u", 1);
        assert(s.openme.var_count_below_max() && "xOpenME max var count reached.");

        xopenme_add_var_d(s.openme.var_count++, (char*) "  \"RESULTS#eps\":%.8lf", eps);
        assert(s.openme.var_count_below_max() && "xOpenME max var count reached.");

        xopenme_add_var_d(s.openme.var_count++, (char*) "  \"RESULTS#max_abs_diff\":%.8lf", max_abs_diff);
        assert(s.openme.var_count_below_max() && "xOpenME max var count reached.");
#endif

        delete [] matrix_C_ref;
    }

} // END OF dataset::verify_results()

// Instantiate templates to GEMM types.
template void dataset<cl_float>::init_random(unsigned int seed, bool zero_matrix_C);
template void dataset<cl_float>::verify_results(state& s, cl_float eps);

template void dataset<cl_double>::init_random(unsigned int seed, bool zero_matrix_C);
template void dataset<cl_double>::verify_results(state& s, cl_double eps);

} // END OF gemmbench namespace
<commit_msg>Print mismatched values ...<commit_after>// (c) 2015, dividiti
// BSD license

#include "cl_dataset.hpp"
#include "cl_state.hpp"

#include <algorithm>

#include <cassert>
#include <cmath>

#include "xopenme.h"

namespace gemmbench
{

// Initialize the data in a random way.
template<typename T>
void dataset<T>::init_random(unsigned int seed, bool zero_matrix_C)
{
    srand(seed);

    // Initialize the scalars.
    alpha = symmetric_rand();
    beta = symmetric_rand();

    // Initialize the matrices.
    for (cl_ulong i = 0, k = static_cast<cl_ulong>(n) * static_cast<cl_ulong>(n); i < k; ++i)
    {
        matrix_A[i] = symmetric_rand();
        matrix_B[i] = symmetric_rand();
        matrix_C[i] = zero_matrix_C ? static_cast<T>(0) : symmetric_rand();
    }

} // END OF init_random()

// Compare the results against a reference implementation.
template<typename T>
void dataset<T>::verify_results(state & s, T eps)
{
    // Read results from buffer_C.
    {
        assert(s.args.matrix_order == n && "Mismatching matrix orders.");

        cl_command_queue queue = s.queue;
        cl_mem buffer = s.buffer_C;
        cl_bool blocking_read = true;
        size_t offset = 0;
        size_t cb = sizeof(T) * n * n;
        void *ptr = matrix_C;
        cl_uint num_events_in_wait_list = 1;
        const cl_event event_wait_list[1] = { s.enqueue };
        cl_event *event = NULL;

        cl_int err = CL_SUCCESS;
        err = clEnqueueReadBuffer(queue, buffer, blocking_read,
            offset, cb, ptr, num_events_in_wait_list, event_wait_list, event);
        assert(CL_SUCCESS == err && "clEnqueueReadBuffer() failed.");
    }

    // Compute reference and compare the results against it.
    {
        T * matrix_C_ref = new T[n * n];
        const bool transA = s.meta.transA;
        const bool transB = s.meta.transB;
        const bool transC = false;

        // Compute reference.
        for (cl_uint i = 0; i < n; ++i)
        {
            for (cl_uint j = 0; j < n; ++j)
            {
                T ab = static_cast<T>(0);
                for (cl_uint k = 0; k < n; ++k)
                {
                    ab += matrix_A[index(i, k, transA)] * matrix_B[index(k, j, transB)];
                }
                matrix_C_ref[index(i, j, transC)] *= beta;
                matrix_C_ref[index(i, j, transC)] += alpha * ab;
            }
        }

        // Compare the results against reference.
        std::cout << "Comparing the OpenCL and reference results... ";
        T max_abs_diff = static_cast<T>(0);
        for (cl_uint i = 0; i < n; ++i)
        {
            for (cl_uint j = 0; j < n; ++j)
            {
                T abs_diff = abs(matrix_C[index(i, j, transC)] - matrix_C_ref[index(i, j, transC)]);
                max_abs_diff = std::max<T>(max_abs_diff, abs_diff);
                if (abs_diff > eps)
                {
                    std::cerr << "MISMATCH! (first at C[" << i << "][" << j << "])";
                    std::cerr << " : " << matrix_C[index(i, j, transC)] << " vs " << matrix_C_ref[index(i, j, transC)] << std::endl;
 #if (1 == XOPENME)
                    xopenme_add_var_i(s.openme.var_count++, (char*) "  \"RESULTS#match\":%u", 0);
                    assert(s.openme.var_count_below_max() && "xOpenME max var count reached.");
 #endif
                    exit(EXIT_FAILURE);
                }
            }
        }
        std::cout << "MATCH!" << std::endl;
#if (1 == XOPENME)
        xopenme_add_var_i(s.openme.var_count++, (char*) "  \"RESULTS#match\":%u", 1);
        assert(s.openme.var_count_below_max() && "xOpenME max var count reached.");

        xopenme_add_var_d(s.openme.var_count++, (char*) "  \"RESULTS#eps\":%.8lf", eps);
        assert(s.openme.var_count_below_max() && "xOpenME max var count reached.");

        xopenme_add_var_d(s.openme.var_count++, (char*) "  \"RESULTS#max_abs_diff\":%.8lf", max_abs_diff);
        assert(s.openme.var_count_below_max() && "xOpenME max var count reached.");
#endif

        delete [] matrix_C_ref;
    }

} // END OF dataset::verify_results()

// Instantiate templates to GEMM types.
template void dataset<cl_float>::init_random(unsigned int seed, bool zero_matrix_C);
template void dataset<cl_float>::verify_results(state& s, cl_float eps);

template void dataset<cl_double>::init_random(unsigned int seed, bool zero_matrix_C);
template void dataset<cl_double>::verify_results(state& s, cl_double eps);

} // END OF gemmbench namespace
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/**
 * GameTime:
 *	Manages the network time.
 *      Time is stored as microseconds since the epoch.
 */

// the top dog
#include "common.h"

// interface header
#include "GameTime.h"

// system headers
#include <time.h>
#ifndef _WIN32
#  include <sys/time.h>
#endif
#include <list>

// common headers
#include "Pack.h"
#include "bzfio.h"

// type definitions
typedef uint16_t u16;
typedef uint32_t u32;
#ifndef WIN32
typedef int64_t s64;
#else
typedef __int64 s64;
#endif
typedef struct {
  s64 netTime;
  s64 localTime;
} TimeRecord;

// local constants
static const double filterTime = 10.0;
static const unsigned int maxRecords = 1024; // safety
static const unsigned int maxRecordAge = 120 * 1000000;
static const s64 maxTime = 2345678;
static const double minRate = 0.50;
static const double maxRate = 2.00;

// local variables
static std::list<TimeRecord> timeRecs;
static double stepSecs = 0.0;
static s64 stepTime = 0;
static double avgRate = 1.0;
static TimeRecord avgPoint = {0, 0};

/******************************************************************************/

static s64 getRawTime()
{
#ifndef _WIN32

  struct timeval tv;
  gettimeofday(&tv, NULL);
  return ((s64)tv.tv_sec * (s64)1000000) + (s64)tv.tv_usec;

#else //_WIN32

  // FIXME - use QPC if available? (10ms[pat] good enough?)
  //       - during rollovers, check time() against the
  //	 current value to see if a rollover was missed?

  static s64 offset = ((s64)time(NULL) * (s64)1000000) -
                      ((s64)timeGetTime() * (s64)1000);
  static u32 lasttime = (u32)timeGetTime();

  u32 nowtime = (u32)timeGetTime();

  // we've got 49.71 days to catch the rollovers
  if (nowtime < lasttime) {
    // add the rollover value
    offset += ((s64)(1 << 32));
  }
  lasttime = nowtime;
  return offset + ((s64)nowtime * (s64)1000);

#endif //_WIN32
}

/******************************************************************************/

static void calcAvgRate()
{
  // FIXME - this is weak
  const int count = timeRecs.size();
  if (count <= 0) {
    avgRate = 1.0;
    avgPoint.netTime = 0;
    avgPoint.localTime = 0;
    return;
  }
  else if (timeRecs.size() == 1) {
    const TimeRecord& tr = *timeRecs.begin();
    avgRate = 1.0;
    avgPoint = tr;
    return;
  }
  else {
    const TimeRecord& last = *timeRecs.begin();
    const TimeRecord& first = *timeRecs.rbegin();
    const s64 netDiff = last.netTime - first.netTime;
    const s64 locDiff = last.localTime - first.localTime;
    if (locDiff != 0.0) {
      avgRate = ((double)netDiff / (double)locDiff);
      avgPoint = last;
    } else {
      // don't update
    }
  }
  return;
}

/******************************************************************************/

void GameTime::reset()
{
  stepSecs = 0.0;
  stepTime = 0;
  avgRate = 1.0;
  avgPoint.netTime = 0;
  avgPoint.localTime = 0;
  timeRecs.clear();
  return;
}

static void resetToRecord(const TimeRecord& record)
{
  avgRate = 1.0;
  avgPoint = record;
  stepTime = record.netTime;
  TimeRecord copy = record;
  timeRecs.clear();
  timeRecs.push_front(copy);
  return;
}

void GameTime::update()
{
  std::list<TimeRecord>::iterator it;
  unsigned int count = timeRecs.size();
  if (count <= 0) {
    const TimeRecord tr = {0,0};
    resetToRecord(tr);
  }
  else if (count == 1) {
    const TimeRecord& tr = *timeRecs.begin();
    resetToRecord(tr);
  }
  else {
    calcAvgRate();
    const TimeRecord& tr = *timeRecs.begin();
    const s64 diffTime = stepTime - tr.netTime;
    if ((diffTime < -maxTime) || (diffTime > +maxTime) ||
        (avgRate < minRate) || (avgRate > maxRate)) {
      DEBUG4("GameTime: discontinuity: usecs = %lli, rate = %f\n",
             diffTime, avgRate);
      resetToRecord(tr);
    }
  }

  DEBUG4("GameTime: count = %i, rate = %f\n", timeRecs.size(), avgRate);

  return;
}

/******************************************************************************/

void GameTime::setStepTime()
{
  static s64 lastStep = 0;
  const s64 thisStep = getRawTime();
  if (timeRecs.size() <= 0) {
    stepTime = thisStep;
  } else {
    // long term prediction
    const double diffLocal = (double)(thisStep - avgPoint.localTime);
    const double longPred = (double)avgPoint.netTime + (diffLocal * avgRate);
    // short term prediction
    const double skipTime = (double)(thisStep - lastStep);
    const double shortPred = (double)stepTime + (skipTime * avgRate);
    // filtering
    const double c = (skipTime * 1.0e-6) / filterTime;
    const double a = (c > 0.0) && (c < 1.0) ? c : 0.5;
    const double b = 1.0 - a;
    stepTime = (s64)((a * longPred) + (b * (double)shortPred));
  }
  stepSecs = (double)stepTime * 1.0e-6;
  lastStep = thisStep;

  return;
}

double GameTime::getStepTime()
{
  return stepSecs;
}

/******************************************************************************/

int GameTime::packSize()
{
  return (2 * sizeof(u32));
}

void* GameTime::pack(void *buf)
{
  const s64 nowTime = getRawTime();
//  const s64 nowTime = getRawTime() + (s64)((bzfrand() - 0.5) * 2.0e6);
  buf = nboPackUInt(buf, (u32)(nowTime >> 32));		// msb's
  buf = nboPackUInt(buf, (u32)(nowTime & 0xFFFFFFFF));	// lsb's
  return buf;
}

void* GameTime::unpack(void *buf)
{
  u32 msb, lsb;
  buf = nboUnpackUInt(buf, msb);
  buf = nboUnpackUInt(buf, lsb);
  const s64 netTime = ((s64)msb << 32) + (s64)lsb;

  // store the value
  const TimeRecord tr = { netTime, getRawTime() };
  timeRecs.push_front(tr);

  // clear oversize entries
  while (timeRecs.size() > maxRecords) {
    timeRecs.pop_back();
  }

  // clear the aged entries
  if (timeRecs.size() > 0) {
    s64 nowTime = getRawTime();
    while (timeRecs.size() > 0) {
      TimeRecord back = *timeRecs.rbegin();
      if ((nowTime - back.localTime) < maxRecordAge) {
        break;
      }
      timeRecs.pop_back();
    }
  }

  return buf;
}

/******************************************************************************/

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>simpler windows time code<commit_after>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/**
 * GameTime:
 *	Manages the network time.
 *      Time is stored as microseconds since the epoch.
 */

// the top dog
#include "common.h"

// interface header
#include "GameTime.h"

// system headers
#include <time.h>
#ifndef _WIN32
#  include <sys/time.h>
#endif
#include <list>

// common headers
#include "Pack.h"
#include "bzfio.h"

// type definitions
typedef uint16_t u16;
typedef uint32_t u32;
#ifndef WIN32
typedef int64_t s64;
#else
typedef __int64 s64;
#endif
typedef struct {
  s64 netTime;
  s64 localTime;
} TimeRecord;

// local constants
static const double filterTime = 10.0;
static const unsigned int maxRecords = 1024; // safety
static const unsigned int maxRecordAge = 120 * 1000000;
static const s64 maxTime = 2345678;
static const double minRate = 0.50;
static const double maxRate = 2.00;

// local variables
static std::list<TimeRecord> timeRecs;
static double stepSecs = 0.0;
static s64 stepTime = 0;
static double avgRate = 1.0;
static TimeRecord avgPoint = {0, 0};

/******************************************************************************/

static s64 getRawTime()
{
#ifndef _WIN32

  struct timeval tv;
  gettimeofday(&tv, NULL);
  return ((s64)tv.tv_sec * (s64)1000000) + (s64)tv.tv_usec;

#else //_WIN32

  FILETIME ft;
  LARGE_INTEGER li;

  GetSystemTimeAsFileTime(&ft);
  li.LowPart  = ft.dwLowDateTime;
  li.HighPart = ft.dwHighDateTime;

  /* QuadPart is in 100-nanosecond intervals */
  return (li.QuadPart / 10);

#endif //_WIN32
}

/******************************************************************************/

static void calcAvgRate()
{
  // FIXME - this is weak
  const int count = timeRecs.size();
  if (count <= 0) {
    avgRate = 1.0;
    avgPoint.netTime = 0;
    avgPoint.localTime = 0;
    return;
  }
  else if (timeRecs.size() == 1) {
    const TimeRecord& tr = *timeRecs.begin();
    avgRate = 1.0;
    avgPoint = tr;
    return;
  }
  else {
    const TimeRecord& last = *timeRecs.begin();
    const TimeRecord& first = *timeRecs.rbegin();
    const s64 netDiff = last.netTime - first.netTime;
    const s64 locDiff = last.localTime - first.localTime;
    if (locDiff != 0.0) {
      avgRate = ((double)netDiff / (double)locDiff);
      avgPoint = last;
    } else {
      // don't update
    }
  }
  return;
}

/******************************************************************************/

void GameTime::reset()
{
  stepSecs = 0.0;
  stepTime = 0;
  avgRate = 1.0;
  avgPoint.netTime = 0;
  avgPoint.localTime = 0;
  timeRecs.clear();
  return;
}

static void resetToRecord(const TimeRecord& record)
{
  avgRate = 1.0;
  avgPoint = record;
  stepTime = record.netTime;
  TimeRecord copy = record;
  timeRecs.clear();
  timeRecs.push_front(copy);
  return;
}

void GameTime::update()
{
  std::list<TimeRecord>::iterator it;
  unsigned int count = timeRecs.size();
  if (count <= 0) {
    const TimeRecord tr = {0,0};
    resetToRecord(tr);
  }
  else if (count == 1) {
    const TimeRecord& tr = *timeRecs.begin();
    resetToRecord(tr);
  }
  else {
    calcAvgRate();
    const TimeRecord& tr = *timeRecs.begin();
    const s64 diffTime = stepTime - tr.netTime;
    if ((diffTime < -maxTime) || (diffTime > +maxTime) ||
        (avgRate < minRate) || (avgRate > maxRate)) {
      DEBUG4("GameTime: discontinuity: usecs = %lli, rate = %f\n",
             diffTime, avgRate);
      resetToRecord(tr);
    }
  }

  DEBUG4("GameTime: count = %i, rate = %f\n", timeRecs.size(), avgRate);

  return;
}

/******************************************************************************/

void GameTime::setStepTime()
{
  static s64 lastStep = 0;
  const s64 thisStep = getRawTime();
  if (timeRecs.size() <= 0) {
    stepTime = thisStep;
  } else {
    // long term prediction
    const double diffLocal = (double)(thisStep - avgPoint.localTime);
    const double longPred = (double)avgPoint.netTime + (diffLocal * avgRate);
    // short term prediction
    const double skipTime = (double)(thisStep - lastStep);
    const double shortPred = (double)stepTime + (skipTime * avgRate);
    // filtering
    const double c = (skipTime * 1.0e-6) / filterTime;
    const double a = (c > 0.0) && (c < 1.0) ? c : 0.5;
    const double b = 1.0 - a;
    stepTime = (s64)((a * longPred) + (b * (double)shortPred));
  }
  stepSecs = (double)stepTime * 1.0e-6;
  lastStep = thisStep;

  return;
}

double GameTime::getStepTime()
{
  return stepSecs;
}

/******************************************************************************/

int GameTime::packSize()
{
  return (2 * sizeof(u32));
}

void* GameTime::pack(void *buf)
{
  const s64 nowTime = getRawTime();
//  const s64 nowTime = getRawTime() + (s64)((bzfrand() - 0.5) * 2.0e6);
  buf = nboPackUInt(buf, (u32)(nowTime >> 32));		// msb's
  buf = nboPackUInt(buf, (u32)(nowTime & 0xFFFFFFFF));	// lsb's
  return buf;
}

void* GameTime::unpack(void *buf)
{
  u32 msb, lsb;
  buf = nboUnpackUInt(buf, msb);
  buf = nboUnpackUInt(buf, lsb);
  const s64 netTime = ((s64)msb << 32) + (s64)lsb;

  // store the value
  const TimeRecord tr = { netTime, getRawTime() };
  timeRecs.push_front(tr);

  // clear oversize entries
  while (timeRecs.size() > maxRecords) {
    timeRecs.pop_back();
  }

  // clear the aged entries
  if (timeRecs.size() > 0) {
    s64 nowTime = getRawTime();
    while (timeRecs.size() > 0) {
      TimeRecord back = *timeRecs.rbegin();
      if ((nowTime - back.localTime) < maxRecordAge) {
        break;
      }
      timeRecs.pop_back();
    }
  }

  return buf;
}

/******************************************************************************/

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>
#include <stdio.h>
#include <math.h>
#include "drawstuff/drawstuff.h"

#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif

void start()
{
  // adjust the starting viewpoint a bit
  float xyz[3],hpr[3];
  dsGetViewpoint (xyz,hpr);
  hpr[0] += 7;
  dsSetViewpoint (xyz,hpr);
}

void simLoop (int pause)
{
  float pos[3];
  float R[9];
  static float a = 0;

  if (!pause) a += 0.02f;
  if (a > (2*M_PI)) a -= (float) (2*M_PI);
  float ca = (float) cos(a);
  float sa = (float) sin(a);

  dsSetTexture (DS_WOOD);

  float b = (a > M_PI) ? (2*(a-(float)M_PI)) : a*2;
  pos[0] = -0.3f;
  pos[1] = 0;
  pos[2] = (float) (0.1f*(2*M_PI*b - b*b) + 0.65f);
  R[0] = ca; R[1] = 0; R[2] = -sa;
  R[3] = 0;  R[4] = 1; R[5] = 0;
  R[6] = sa; R[7] = 0; R[8] = ca;
  dsSetColor (1,0.8f,0.6f);
  dsDrawSphere (pos,R,0.3f);

  dsSetTexture (DS_NONE);

  pos[0] = -0.2f;
  pos[1] = 0.8f;
  pos[2] = 0.4f;
  R[0] = ca; R[1] = -sa; R[2] = 0;
  R[3] = sa; R[4] = ca;  R[5] = 0;
  R[6] = 0;  R[7] = 0;	 R[8] = 1;
  float sides[3] = {0.1f,0.4f,0.8f};
  dsSetColor (0.6f,0.6f,1);
  dsDrawBox (pos,R,sides);

  dsSetTexture (DS_WOOD);

  float r = 0.3f;		      // cylinder radius
  float d = (float)cos(a*2) * 0.4f;
  float cd = (float)cos(-d/r);
  float sd = (float)sin(-d/r);
  pos[0] = -0.2f;
  pos[1] = -1 + d;
  pos[2] = 0.3f;
  R[0] = 0;  R[1] = -sd; R[2] = cd;
  R[3] = 0;  R[4] = cd;  R[5] = sd;
  R[6] = -1; R[7] = 0;	 R[8] = 0;
  dsSetColor (0.4f,1,1);
  dsDrawCylinder (pos,R,0.8f,r);

  pos[0] = 0;
  pos[1] = 0;
  pos[2] = 0.2f;
  R[0] = 0;   R[1] = 0;  R[2] = 1;
  R[3] = sa;  R[4] = ca; R[5] = 0;
  R[6] = -ca; R[7] = sa; R[8] = 0;
  dsSetColor (1,0.9f,0.2f);
  dsDrawCappedCylinder (pos,R,0.8f,0.2f);
}

void command (int cmd)
{
  dsPrint ("received command %d (`%c')\n",cmd,cmd);
}

int main (int argc, char **argv)
{
  // setup pointers to callback functions
  dsFunctions fn;
  fn.version = DS_VERSION;
  fn.start = &start;
  fn.step = &simLoop;
  fn.command = command;
  fn.stop = 0;
  fn.path_to_textures = 0;	// uses default

  // run simulation
  dsSimulationLoop (argc,argv,600,600,&fn);

  return 0;
}
<commit_msg>interface change for R.<commit_after>
#include <stdio.h>
#include <math.h>
#include "drawstuff/drawstuff.h"

#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif

void start()
{
  // adjust the starting viewpoint a bit
  float xyz[3],hpr[3];
  dsGetViewpoint (xyz,hpr);
  hpr[0] += 7;
  dsSetViewpoint (xyz,hpr);
}

void simLoop (int pause)
{
  float pos[3];
  float R[12];
  static float a = 0;

  if (!pause) a += 0.02f;
  if (a > (2*M_PI)) a -= (float) (2*M_PI);
  float ca = (float) cos(a);
  float sa = (float) sin(a);

  dsSetTexture (DS_WOOD);

  float b = (a > M_PI) ? (2*(a-(float)M_PI)) : a*2;
  pos[0] = -0.3f;
  pos[1] = 0;
  pos[2] = (float) (0.1f*(2*M_PI*b - b*b) + 0.65f);
  R[0] = ca; R[1] = 0; R[2] = -sa;
  R[4] = 0;  R[5] = 1; R[6] = 0;
  R[8] = sa; R[9] = 0; R[10] = ca;
  dsSetColor (1,0.8f,0.6f);
  dsDrawSphere (pos,R,0.3f);

  dsSetTexture (DS_NONE);

  pos[0] = -0.2f;
  pos[1] = 0.8f;
  pos[2] = 0.4f;
  R[0] = ca; R[1] = -sa; R[2] = 0;
  R[4] = sa; R[5] = ca;  R[6] = 0;
  R[8] = 0;  R[9] = 0;	 R[10] = 1;
  float sides[3] = {0.1f,0.4f,0.8f};
  dsSetColor (0.6f,0.6f,1);
  dsDrawBox (pos,R,sides);

  dsSetTexture (DS_WOOD);

  float r = 0.3f;		      // cylinder radius
  float d = (float)cos(a*2) * 0.4f;
  float cd = (float)cos(-d/r);
  float sd = (float)sin(-d/r);
  pos[0] = -0.2f;
  pos[1] = -1 + d;
  pos[2] = 0.3f;
  R[0] = 0;   R[1] = 0;  R[2] = -1;
  R[4] = -sd; R[5] = cd; R[6] =  0;
  R[8] =  cd; R[9] = sd; R[10] = 0;
  dsSetColor (0.4f,1,1);
  dsDrawCylinder (pos,R,0.8f,r);

  pos[0] = 0;
  pos[1] = 0;
  pos[2] = 0.2f;
  R[0] = 0; R[1] = sa; R[2] = -ca;
  R[4] = 0; R[5] = ca; R[6] = sa;
  R[8] = 1; R[9] = 0;  R[10] = 0;
  dsSetColor (1,0.9f,0.2f);
  dsDrawCappedCylinder (pos,R,0.8f,0.2f);
}

void command (int cmd)
{
  dsPrint ("received command %d (`%c')\n",cmd,cmd);
}

int main (int argc, char **argv)
{
  // setup pointers to callback functions
  dsFunctions fn;
  fn.version = DS_VERSION;
  fn.start = &start;
  fn.step = &simLoop;
  fn.command = command;
  fn.stop = 0;
  fn.path_to_textures = 0;	// uses default

  // run simulation
  dsSimulationLoop (argc,argv,400,400,&fn);

  return 0;
}
<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Sven Kaulmann

#ifndef DUNE_STUFF_COMMON_MATRIX_HH
#define DUNE_STUFF_COMMON_MATRIX_HH

// dune-common
#include <dune/stuff/common/disable_warnings.hh>
# include <dune/common/densematrix.hh>
#include <dune/stuff/common/reenable_warnings.hh>

#include <dune/stuff/common/debug.hh>
#include <dune/stuff/common/math.hh>

#if HAVE_DUNE_ISTL && HAVE_DUNE_FEM
  // for dune-istl
# if defined(HAVE_BOOST)
#   undef HAVE_BOOST
#   define HAVE_BOOST 1
# endif
# include <dune/stuff/common/disable_warnings.hh>
#   include <dune/fem/operator/matrix/spmatrix.hh>
#   include <dune/istl/operators.hh>
#   include <dune/fem/operator/matrix/istlmatrix.hh>
#   include <dune/fem/operator/matrix/preconditionerwrapper.hh>
# include <dune/stuff/common/reenable_warnings.hh>
#endif // if HAVE_DUNE_ISTL && HAVE_DUNE_FEM

namespace Dune {
namespace Stuff {
namespace Common {

// \todo doc
template< class MatrixImp >
inline void
  DUNE_DEPRECATED_MSG("Use *= 0 instead!")
            clear(Dune::DenseMatrix< MatrixImp >& matrix)
{
  matrix *= typename Dune::DenseMatrix< MatrixImp >::value_type(0);
}

//! TODO
template< class MatrixImp >
struct DUNE_DEPRECATED_MSG("deprecated dune-fem util, use stuff/la instead")
  PrecondionWrapperDummy
{
  typedef typename MatrixImp::RowDiscreteFunctionType::DofStorageType X;
  typedef typename MatrixImp::ColDiscreteFunctionType::DofStorageType Y;
  void pre(X&, Y&) {}
  void apply(X&, const Y&) {}
  void post(X&) {}
}; // struct PrecondionWrapperDummy

/** \brief get the diagonal of a fieldMatrix into a fieldvector
   * \note While in principle this might do for SparseRowMatrix as well, don't do it! SparseRowMatrix has specialised
   *functions for this (putting the diagonal into DiscreteFunctions tho
   **/
template< class FieldMatrixType >
class MatrixDiagonal
  : public FieldVector< typename FieldMatrixType::field_type,
                        FieldMatrixType::rows >
{
public:
  MatrixDiagonal(const FieldMatrixType& matrix) {
    static_assert(FieldMatrixType::rows == FieldMatrixType::cols, "Matrix must be square!");
    // CompileTimeChecker< FieldMatrixType::rows == FieldMatrixType::cols > matrix_must_be_square;

    for (size_t i = 0; i < FieldMatrixType::rows; i++)
      (*this)[i] = matrix[i][i];
  }
}; // class MatrixDiagonal

//! returns Sum of matrix' diagonal entries
template< class FieldMatrixType >
typename FieldMatrixType::field_type matrixTrace(const FieldMatrixType& matrix) {
  MatrixDiagonal< FieldMatrixType > diag(matrix);
  typename FieldMatrixType::field_type trace = typename FieldMatrixType::field_type(0);
  for (size_t i = 0; i < FieldMatrixType::rows; i++)
    trace += diag[i];
  return trace;
} // typename FieldMatrixType::field_type matrixTrace(const FieldMatrixType& matrix)

//! produces a NxN Identity matrix compatible with parent type
template< class MatrixType >
class IdentityMatrix
  : public MatrixType
{
public:
  IdentityMatrix(size_t N)
    : MatrixType(N, N, 1) {
    for (size_t i = 1; i < N; ++i)
      MatrixType::set(i, i, 1.0);
  }

  const MatrixType& matrix() const { return *this; }
}; // class IdentityMatrix

//! produces a NxN Identity matrix object compatible with parent type
template< class MatrixObjectType >
class DUNE_DEPRECATED_MSG("deprecated dune-fem util, use stuff/la instead")
IdentityMatrixObject
  : public MatrixObjectType
{
public:
  IdentityMatrixObject(const typename MatrixObjectType::DomainSpaceType& domain_space,
                       const typename MatrixObjectType::RangeSpaceType& range_space)
    : MatrixObjectType(domain_space, range_space) {
    MatrixObjectType::reserve();
    for (int i = 0; i < MatrixObjectType::matrix().rows(); ++i)
      MatrixObjectType::matrix().set(i, i, 1.0);
  }
};

//! adds the missing setDiag function to SparseRowMatrix
template< class DiscFuncType, class MatrixType >
void setMatrixDiag(MatrixType& matrix, DiscFuncType& diag) {
  typedef typename DiscFuncType::DofIteratorType DofIteratorType;

  //! we assume that the dimension of the functionspace of f is the same as
  //! the size of the matrix
  DofIteratorType it = diag.dbegin();

  for (int row = 0; row < matrix.rows(); row++)
  {
    if (*it != 0.0)
      matrix.set(row, row, *it);
    ++it;
  }
  return;
} // setMatrixDiag

//! return false if
abs( a(row,col) - b(col,row) ) > tolerance
 for any col,row
template< class MatrixType >
bool areTransposed(const MatrixType& a, const MatrixType& b, const double tolerance = 1e-8) {
  if ( ( a.rows() != b.cols() ) || ( b.rows() != a.cols() ) )
    return false;

  for (int row = 0; row < a.rows(); ++row)
  {
    for (int col = 0; col  tolerance)
        return false;
    }
  }
  return true;
} // areTransposed

//! extern matrix addition that ignore 0 entries
template< class MatrixType >
void addMatrix(MatrixType& dest, const MatrixType& arg, const double eps = 1e-14) {
  for (int i = 0; i < arg.rows(); ++i)
    for (int j = 0; j < arg.cols(); ++j)
    {
      const double value = arg(i, j);
      if (std::fabs(value) > eps)
        dest.add(i, j, value);
    }

} // addMatrix

/** @brief Write sparse matrix to given output stream
   *
   *  @param[in]  matrix The matrix to be written
   *  @param[in] out    The outgoing stream
   */
template< class SparseMatrixImpl, class Output >
void writeSparseMatrix(const SparseMatrixImpl& matrix,
                       Output& out) {
  const unsigned int nRows = matrix.rows();
  const unsigned int nCols = matrix.cols();

  for (int i = 0; i != nRows; ++i)
  {
    for (int j = 0; j != nCols; ++j)
    {
      if ( matrix.find(i, j) )
      {
        out << i << "," << j << ",";
        out.precision(12);
        out.setf(std::ios::scientific);
        out << matrix(i, j) << std::endl;
      }
    }
  }
  return;
} // writeSparseMatrix

/** @brief Read sparse matrix from given inputstream
   *
   *  @param[out] matrix The matrix to be read
   *  @param[in]  in     The ingoing stream
   */
template< class SparseMatrixImpl, class Input >
void readSparseMatrix(SparseMatrixImpl& matrix,
                      Input& in) {
  matrix.clear();
  std::string row;
  while ( std::getline(in, row) )
  {
    size_t last_found = 0;
    size_t found = row.find_first_of(",");
    double temp;
    std::vector< double > entryLine;
    do {
      if (found == std::string::npos)
        found = row.size();
      std::string subs = row.substr(last_found, found - last_found);
      last_found = found + 1;
      std::istringstream in_str(subs);
      if (entryLine.size() == 2)
      {
        in_str.precision(12);
        in_str.setf(std::ios::scientific);
      } else {
        in_str.precision(10);
        in_str.setf(std::ios::fixed);
      }
      in_str >> temp;
      entryLine.push_back(temp);
      found = row.find_first_of(",", last_found);
    } while (last_found != row.size() + 1);
    assert(entryLine.size() == 3);
    matrix.add(entryLine[0], entryLine[1], entryLine[2]);
  }
} // readSparseMatrix

/**
   *  \brief  multiplies rows of arg2 with arg1
   *  \todo   doc
   **/
template< class FieldMatrixImp >
FieldMatrixImp rowWiseMatrixMultiplication(const FieldMatrixImp& arg1,
                                           const FieldMatrixImp& arg2) {
  typedef FieldMatrixImp
  FieldMatrixType;
  typedef typename FieldMatrixType::row_type
  RowType;
  typedef typename FieldMatrixType::ConstRowIterator
  ConstRowIteratorType;
  typedef typename FieldMatrixType::RowIterator
  RowIteratorType;

  assert( arg2.rowdim() == arg1.coldim() );

  FieldMatrixType ret(0.0);

  ConstRowIteratorType arg2RowItEnd = arg2.end();
  RowIteratorType retRowItEnd = ret.end();
  RowIteratorType retRowIt = ret.begin();
  for (ConstRowIteratorType arg2RowIt = arg2.begin();
       arg2RowIt != arg2RowItEnd, retRowIt != retRowItEnd;
       ++arg2RowIt, ++retRowIt)
  {
    RowType row(0.0);
    arg1.mv(*arg2RowIt, row);
    *retRowIt = row;
  }
  return ret;
} // rowWiseMatrixMultiplication

//! prints actual memusage of matrix in kB
template< class MatrixType >
void printMemUsage(const MatrixType& matrix, std::ostream& stream, std::string name = "") {
  long size = matrix.numberOfValues() * sizeof(typename MatrixType::Ttype) / 1024.f;

  stream << "matrix size " << name << "\t\t" << size << std::endl;
}

//! prints actual memusage of matrixobject in kB
template< class MatrixObjectType>
void printMemUsageObject(const MatrixObjectType& matrix_object, std::ostream& stream, std::string name = "") {
  printMemUsage(matrix_object.matrix(), stream, name);
}

template< class M >
void forceTranspose(const M& arg, M& dest) {
  assert( arg.cols() == dest.rows() );
  assert( dest.cols() == arg.rows() );
// dest.clear();
  for (int i = 0; i < arg.cols(); ++i)
    for (int j = 0; j < arg.rows(); ++j)
      dest.set( j, i, arg(i, j) );
} // forceTranspose

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_MATRIX_HH
<commit_msg>[common] remove deprecated stuff from matrix.hh<commit_after>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Sven Kaulmann

#ifndef DUNE_STUFF_COMMON_MATRIX_HH
#define DUNE_STUFF_COMMON_MATRIX_HH

// dune-common
#include <dune/stuff/common/disable_warnings.hh>
# include <dune/common/densematrix.hh>
#include <dune/stuff/common/reenable_warnings.hh>

#include <dune/stuff/common/debug.hh>
#include <dune/stuff/common/math.hh>

#if HAVE_DUNE_ISTL && HAVE_DUNE_FEM
  // for dune-istl
# if defined(HAVE_BOOST)
#   undef HAVE_BOOST
#   define HAVE_BOOST 1
# endif
# include <dune/stuff/common/disable_warnings.hh>
#   include <dune/fem/operator/matrix/spmatrix.hh>
#   include <dune/istl/operators.hh>
#   include <dune/fem/operator/matrix/istlmatrix.hh>
#   include <dune/fem/operator/matrix/preconditionerwrapper.hh>
# include <dune/stuff/common/reenable_warnings.hh>
#endif // if HAVE_DUNE_ISTL && HAVE_DUNE_FEM

namespace Dune {
namespace Stuff {
namespace Common {

/** \brief get the diagonal of a fieldMatrix into a fieldvector
   * \note While in principle this might do for SparseRowMatrix as well, don't do it! SparseRowMatrix has specialised
   *functions for this (putting the diagonal into DiscreteFunctions tho
   **/
template< class FieldMatrixType >
class MatrixDiagonal
  : public FieldVector< typename FieldMatrixType::field_type,
                        FieldMatrixType::rows >
{
public:
  MatrixDiagonal(const FieldMatrixType& matrix) {
    static_assert(FieldMatrixType::rows == FieldMatrixType::cols, "Matrix must be square!");
    // CompileTimeChecker< FieldMatrixType::rows == FieldMatrixType::cols > matrix_must_be_square;

    for (size_t i = 0; i < FieldMatrixType::rows; i++)
      (*this)[i] = matrix[i][i];
  }
}; // class MatrixDiagonal

//! returns Sum of matrix' diagonal entries
template< class FieldMatrixType >
typename FieldMatrixType::field_type matrixTrace(const FieldMatrixType& matrix) {
  MatrixDiagonal< FieldMatrixType > diag(matrix);
  typename FieldMatrixType::field_type trace = typename FieldMatrixType::field_type(0);
  for (size_t i = 0; i < FieldMatrixType::rows; i++)
    trace += diag[i];
  return trace;
} // typename FieldMatrixType::field_type matrixTrace(const FieldMatrixType& matrix)

//! produces a NxN Identity matrix compatible with parent type
template< class MatrixType >
class IdentityMatrix
  : public MatrixType
{
public:
  IdentityMatrix(size_t N)
    : MatrixType(N, N, 1) {
    for (size_t i = 1; i < N; ++i)
      MatrixType::set(i, i, 1.0);
  }

  const MatrixType& matrix() const { return *this; }
}; // class IdentityMatrix

//! produces a NxN Identity matrix object compatible with parent type
template< class MatrixObjectType >
class DUNE_DEPRECATED_MSG("deprecated dune-fem util, use stuff/la instead")
IdentityMatrixObject
  : public MatrixObjectType
{
public:
  IdentityMatrixObject(const typename MatrixObjectType::DomainSpaceType& domain_space,
                       const typename MatrixObjectType::RangeSpaceType& range_space)
    : MatrixObjectType(domain_space, range_space) {
    MatrixObjectType::reserve();
    for (int i = 0; i < MatrixObjectType::matrix().rows(); ++i)
      MatrixObjectType::matrix().set(i, i, 1.0);
  }
};

//! adds the missing setDiag function to SparseRowMatrix
template< class DiscFuncType, class MatrixType >
void setMatrixDiag(MatrixType& matrix, DiscFuncType& diag) {
  typedef typename DiscFuncType::DofIteratorType DofIteratorType;

  //! we assume that the dimension of the functionspace of f is the same as
  //! the size of the matrix
  DofIteratorType it = diag.dbegin();

  for (int row = 0; row < matrix.rows(); row++)
  {
    if (*it != 0.0)
      matrix.set(row, row, *it);
    ++it;
  }
  return;
} // setMatrixDiag

//! return false if
abs( a(row,col) - b(col,row) ) > tolerance
 for any col,row
template< class MatrixType >
bool areTransposed(const MatrixType& a, const MatrixType& b, const double tolerance = 1e-8) {
  if ( ( a.rows() != b.cols() ) || ( b.rows() != a.cols() ) )
    return false;

  for (int row = 0; row < a.rows(); ++row)
  {
    for (int col = 0; col  tolerance)
        return false;
    }
  }
  return true;
} // areTransposed

//! extern matrix addition that ignore 0 entries
template< class MatrixType >
void addMatrix(MatrixType& dest, const MatrixType& arg, const double eps = 1e-14) {
  for (int i = 0; i < arg.rows(); ++i)
    for (int j = 0; j < arg.cols(); ++j)
    {
      const double value = arg(i, j);
      if (std::fabs(value) > eps)
        dest.add(i, j, value);
    }

} // addMatrix

/** @brief Write sparse matrix to given output stream
   *
   *  @param[in]  matrix The matrix to be written
   *  @param[in] out    The outgoing stream
   */
template< class SparseMatrixImpl, class Output >
void writeSparseMatrix(const SparseMatrixImpl& matrix,
                       Output& out) {
  const unsigned int nRows = matrix.rows();
  const unsigned int nCols = matrix.cols();

  for (int i = 0; i != nRows; ++i)
  {
    for (int j = 0; j != nCols; ++j)
    {
      if ( matrix.find(i, j) )
      {
        out << i << "," << j << ",";
        out.precision(12);
        out.setf(std::ios::scientific);
        out << matrix(i, j) << std::endl;
      }
    }
  }
  return;
} // writeSparseMatrix

/** @brief Read sparse matrix from given inputstream
   *
   *  @param[out] matrix The matrix to be read
   *  @param[in]  in     The ingoing stream
   */
template< class SparseMatrixImpl, class Input >
void readSparseMatrix(SparseMatrixImpl& matrix,
                      Input& in) {
  matrix.clear();
  std::string row;
  while ( std::getline(in, row) )
  {
    size_t last_found = 0;
    size_t found = row.find_first_of(",");
    double temp;
    std::vector< double > entryLine;
    do {
      if (found == std::string::npos)
        found = row.size();
      std::string subs = row.substr(last_found, found - last_found);
      last_found = found + 1;
      std::istringstream in_str(subs);
      if (entryLine.size() == 2)
      {
        in_str.precision(12);
        in_str.setf(std::ios::scientific);
      } else {
        in_str.precision(10);
        in_str.setf(std::ios::fixed);
      }
      in_str >> temp;
      entryLine.push_back(temp);
      found = row.find_first_of(",", last_found);
    } while (last_found != row.size() + 1);
    assert(entryLine.size() == 3);
    matrix.add(entryLine[0], entryLine[1], entryLine[2]);
  }
} // readSparseMatrix

/**
   *  \brief  multiplies rows of arg2 with arg1
   *  \todo   doc
   **/
template< class FieldMatrixImp >
FieldMatrixImp rowWiseMatrixMultiplication(const FieldMatrixImp& arg1,
                                           const FieldMatrixImp& arg2) {
  typedef FieldMatrixImp
  FieldMatrixType;
  typedef typename FieldMatrixType::row_type
  RowType;
  typedef typename FieldMatrixType::ConstRowIterator
  ConstRowIteratorType;
  typedef typename FieldMatrixType::RowIterator
  RowIteratorType;

  assert( arg2.rowdim() == arg1.coldim() );

  FieldMatrixType ret(0.0);

  ConstRowIteratorType arg2RowItEnd = arg2.end();
  RowIteratorType retRowItEnd = ret.end();
  RowIteratorType retRowIt = ret.begin();
  for (ConstRowIteratorType arg2RowIt = arg2.begin();
       arg2RowIt != arg2RowItEnd, retRowIt != retRowItEnd;
       ++arg2RowIt, ++retRowIt)
  {
    RowType row(0.0);
    arg1.mv(*arg2RowIt, row);
    *retRowIt = row;
  }
  return ret;
} // rowWiseMatrixMultiplication

//! prints actual memusage of matrix in kB
template< class MatrixType >
void printMemUsage(const MatrixType& matrix, std::ostream& stream, std::string name = "") {
  long size = matrix.numberOfValues() * sizeof(typename MatrixType::Ttype) / 1024.f;

  stream << "matrix size " << name << "\t\t" << size << std::endl;
}

//! prints actual memusage of matrixobject in kB
template< class MatrixObjectType>
void printMemUsageObject(const MatrixObjectType& matrix_object, std::ostream& stream, std::string name = "") {
  printMemUsage(matrix_object.matrix(), stream, name);
}

template< class M >
void forceTranspose(const M& arg, M& dest) {
  assert( arg.cols() == dest.rows() );
  assert( dest.cols() == arg.rows() );
// dest.clear();
  for (int i = 0; i < arg.cols(); ++i)
    for (int j = 0; j < arg.rows(); ++j)
      dest.set( j, i, arg(i, j) );
} // forceTranspose

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_MATRIX_HH
<|endoftext|>