<commit_before>/** augmentor_stress_test.cc                                 -*- C++ -*-
    Rémi Attab, 10 May 2013
    Copyright (c) 2013 Datacratic.  All rights reserved.

    Stress test to worm out the bottleneck in augmentor base.

*/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include "rtbkit/testing/test_agent.h"
#include "rtbkit/plugins/augmentor/redis_augmentor.h"
#include "rtbkit/core/agent_configuration/agent_configuration_service.h"
#include "jml/db/persistent.h"
#include "jml/utils/exc_assert.h"

#include <boost/test/unit_test.hpp>
#include <thread>
#include <atomic>
#include <set>

using namespace std;
using namespace ML;
using namespace RTBKIT;

static const string sampleBr =
    "{\"id\":\"85885bb0-b91b-11e2-c4cf-7fba90171555\",\"timestamp\":1368153863.008756,\"isTest\":false,\"url\":\"http://myonlinearcade.com/\",\"ipAddress\":\"166.13.20.21\",\"userAgent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/20.0\",\"language\":\"fr\",\"protocolVersion\":\"0.3\",\"exchange\":\"appnexus\",\"provider\":\"appnexus\",\"winSurcharges\":{\"surcharge\":{\"USD/1M\":50}},\"winSurchageMicros\":{\"surcharge\":{\"USD/1M\":50}},\"location\":{\"countryCode\":\"CA\",\"regionCode\":\"QC\",\"cityName\":\"Laval\",\"postalCode\":\"0\",\"dma\":0,\"timezoneOffsetMinutes\":-1},\"segments\":{\"appnexus\":[\"memberId1357\"],\"browser\":[\"Mozilla Firefox\"],\"device_type\":[\"Computer\"],\"os\":[\"Microsoft Windows 7\"]},\"userIds\":{\"an\":\"5273283952213481305\",\"xchg\":\"5273283952213481305\"},\"imp\":[{\"id\":\"156331815539876686\",\"banner\":{\"w\":728,\"h\":90},\"formats\":[\"728x90\"]}],\"spots\":[{\"id\":\"156331815539876686\",\"banner\":{\"w\":728,\"h\":90},\"formats\":[\"728x90\"]}]}";

static std::atomic<size_t> instances(0);
std::string instancedName(const std::string& prefix)
{
    return prefix + to_string(instances.fetch_add(1));
}

struct MockAugmentationLoop : public ServiceBase, public MessageLoop
{
    MockAugmentationLoop(const std::shared_ptr<ServiceProxies>& proxies) :
        ServiceBase(instancedName("mock-aug-loop-"), proxies),
        toAug(proxies->zmqContext),
        sent(0), recv(0)
    {}

    void start()
    {
        registerServiceProvider(serviceName(), { "rtbRouterAugmentation" });

        toAug.init(getServices()->config, serviceName() + "/augmentors");
        toAug.bindTcp(getServices()->ports->getRange("augmentors"));

        toAug.clientMessageHandler = [&] (const vector<string> & message) {
        	ExcAssertEqual (message[0], "redis-augmentation");
        	if (message[1] == "RESPONSE")
        	{
        		ExcAssertEqual (message.size(), 7);
        		ExcAssertEqual (message[5], "redis-augmentation");
        		recordHit("recv");
        		cerr << "REDIS-AUG:" << message[6] << endl ;
        		recv++;
        	}
        };

        toAug.onConnection = [=] (const std::string & client) {
            cerr << "augmentor " << client << " has connected" << endl;
        };
        toAug.onDisconnection = [=] (const std::string & client) {
            cerr << "augmentor " << client << " has disconnected" << endl;
        };

        addSource("MockAugLoop::toAug", toAug);

        {
            // FIXME: should use Agent Config
            set<string> agents {
            	"bob-the-agent_" + to_string(getpid()),
            	"alice-the-agent_" + to_string(getpid())
            };
            std::ostringstream agentStr;
            ML::DB::Store_Writer writer(agentStr);
            writer.save(agents);
            this->agents = agentStr.str();
        }

        addPeriodic("MockAugLoop::send", 0.9, [=] (uint64_t) {
            toAug.sendMessage(
                "redis-augmentation", "AUGMENT", "1.0", "redis-augmentation",
                to_string(random()), "datacratic", sampleBr,
                agents, Date::now());

            sent++;
        });

        MessageLoop::start();
    }

    ZmqNamedClientBus toAug;
    string agents;
    size_t sent, recv;
};

BOOST_AUTO_TEST_CASE( stressTest )
{
    enum {
        FeederThreads = 1,
        TestLength = 20,
        RedisThreads = 5
    };

    auto proxies = make_shared<ServiceProxies>();

    AgentConfigurationService agentConfig(proxies, "config");
    agentConfig.unsafeDisableMonitor();
    agentConfig.init();
    agentConfig.bindTcp();
    agentConfig.start();

    atomic<size_t> processed(0);

    TestAgent agent1(proxies, "bob-the-agent");
    agent1.init();
    agent1.start();
    agent1.configure();
    {
    	AugmentationConfig aug_conf;
    	aug_conf.name = "redis";
    	aug_conf.required = true;
    	auto& v =  aug_conf.config;
    	Json::Value av(Json::arrayValue);
    	av.append("winSurcharges.surcharge.USD/1M");
    	av.append("id");
    	av.append("exchange");
    	av.append("foo.bar"); // not found
    	v["aug-list"] = av;
    	v["aug-prefix"] = "rtbkit:redis";
    	agent1.config.addAugmentation(aug_conf);
    }
    agent1.doConfig (agent1.config);

    TestAgent agent2(proxies, "alice-the-agent");
    agent2.config.account = {"aliceCampaign", "aliceStrategy"};
    agent2.init();
    agent2.start();
    agent2.doConfig(agent2.config);
    {
    	AugmentationConfig aug_conf;
    	aug_conf.name = "redis";
    	aug_conf.required = true;
    	auto& v =  aug_conf.config;
    	Json::Value av(Json::arrayValue);
    	av.append("id");
    	av.append("url"); // not found
    	v["aug-list"] = av;
    	v["aug-prefix"] = "rtbkit:redis";
    	agent2.config.addAugmentation(aug_conf);
    }
    agent2.doConfig (agent2.config);

    cerr << "init feeders\n";

    vector< std::shared_ptr<MockAugmentationLoop> > feederThreads;
    for (size_t i = 0; i < FeederThreads; ++i) {
        feederThreads.emplace_back(new MockAugmentationLoop(proxies));
        feederThreads.back()->start();
    }

    cerr << "init aug\n";

    RedisAugmentor aug("redis-augmentation", "redis-augmentation", proxies, "localhost:6379");
    aug.init(2);
    aug.start();

    this_thread::sleep_for(chrono::milliseconds(100));

    cerr << "sleeping..." << endl;

    for (size_t i = 0; i < TestLength; ++i) {
        this_thread::sleep_for(chrono::seconds(1));
        cerr << "[ " << i << " / " << TestLength << " ]: "
             << "load=" << aug.sampleLoad()
             << ", prob=" << aug.shedProbability()
             << endl;
    }

    cerr << "WOKE UP!" << endl;

    size_t sent = 0, recv = 0;
    for (auto& th : feederThreads) {
        th->shutdown();
        sent += th->sent;
        recv += th->recv;
    }
    aug.shutdown();

    cerr << "sent: " << sent << endl
         << "proc: " << processed << endl
         << "recv: " << recv << endl;

    proxies->events->dump(cerr);
}
<commit_msg>fixed unit tests<commit_after>/** augmentor_stress_test.cc                                 -*- C++ -*-
    Rémi Attab, 10 May 2013
    Copyright (c) 2013 Datacratic.  All rights reserved.

    Stress test to worm out the bottleneck in augmentor base.

*/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include "rtbkit/testing/test_agent.h"
#include "rtbkit/plugins/augmentor/redis_augmentor.h"
#include "rtbkit/core/agent_configuration/agent_configuration_service.h"
#include "jml/db/persistent.h"
#include "jml/utils/exc_assert.h"
#include "soa/service/redis.h"

#include <boost/test/unit_test.hpp>
#include <mutex>
#include <atomic>
#include <set>

using namespace std;
using namespace ML;
using namespace RTBKIT;

static const string sampleBr =
    "{\"id\":\"85885bb0-b91b-11e2-c4cf-7fba90171555\",\"timestamp\":1368153863.008756,\"isTest\":false,\"url\":\"http://myonlinearcade.com/\",\"ipAddress\":\"166.13.20.21\",\"userAgent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/20.0\",\"language\":\"fr\",\"protocolVersion\":\"0.3\",\"exchange\":\"appnexus\",\"provider\":\"appnexus\",\"winSurcharges\":{\"surcharge\":{\"USD/1M\":50}},\"winSurchageMicros\":{\"surcharge\":{\"USD/1M\":50}},\"location\":{\"countryCode\":\"CA\",\"regionCode\":\"QC\",\"cityName\":\"Laval\",\"postalCode\":\"0\",\"dma\":0,\"timezoneOffsetMinutes\":-1},\"segments\":{\"appnexus\":[\"memberId1357\"],\"browser\":[\"Mozilla Firefox\"],\"device_type\":[\"Computer\"],\"os\":[\"Microsoft Windows 7\"]},\"userIds\":{\"an\":\"5273283952213481305\",\"xchg\":\"5273283952213481305\"},\"imp\":[{\"id\":\"156331815539876686\",\"banner\":{\"w\":728,\"h\":90},\"formats\":[\"728x90\"]}],\"spots\":[{\"id\":\"156331815539876686\",\"banner\":{\"w\":728,\"h\":90},\"formats\":[\"728x90\"]}]}";

static std::atomic<size_t> instances(0);
std::string instancedName(const std::string& prefix)
{
    return prefix + to_string(instances.fetch_add(1));
}

static mutex aug_mtx ;
static const string aug_str =
		"[{\"account\":[\"aliceCampaign\",\"aliceStrategy\"],\"augmentation\":{\"data\":{\"rtbkit:redis:id:85885bb0-b91b-11e2-c4cf-7fba90171555\":\"9876\",\"rtbkit:redis:url:http://myonlinearcade.com/\":\"JSCRIPT\"}}},{\"account\":[\"testCampaign\",\"testStrategy\"],\"augmentation\":{\"data\":{\"rtbkit:redis:id:85885bb0-b91b-11e2-c4cf-7fba90171555\":\"9876\",\"rtbkit:redis:winSurcharges.surcharge.USD/1M:50\":\"123\"}}}]";
static vector<string> aug_vec ;
struct MockAugmentationLoop : public ServiceBase, public MessageLoop
{
    MockAugmentationLoop(const std::shared_ptr<ServiceProxies>& proxies) :
        ServiceBase(instancedName("mock-aug-loop-"), proxies),
        toAug(proxies->zmqContext),
        sent(0), recv(0)
    {}

    void start()
    {
        registerServiceProvider(serviceName(), { "rtbRouterAugmentation" });

        toAug.init(getServices()->config, serviceName() + "/augmentors");
        toAug.bindTcp(getServices()->ports->getRange("augmentors"));

        toAug.clientMessageHandler = [&] (const vector<string> & message) {
        	ExcAssertEqual (message[0], "redis-augmentation");
        	if (message[1] == "RESPONSE")
        	{
        		ExcAssertEqual (message.size(), 7);
        		ExcAssertEqual (message[5], "redis-augmentation");
        		recordHit("recv");
        		// cerr << "REDIS-AUG:" << message[6] << endl ;
        		lock_guard<mutex> l(aug_mtx);
        		aug_vec.emplace_back (message[6]);
        		recv++;
        	}
        };

        toAug.onConnection = [=] (const std::string & client) {
            cerr << "augmentor " << client << " has connected" << endl;
        };
        toAug.onDisconnection = [=] (const std::string & client) {
            cerr << "augmentor " << client << " has disconnected" << endl;
        };

        addSource("MockAugLoop::toAug", toAug);

        {
            // FIXME: should use Agent Config
            set<string> agents {
            	"bob-the-agent_" + to_string(getpid()),
            	"alice-the-agent_" + to_string(getpid())
            };
            std::ostringstream agentStr;
            ML::DB::Store_Writer writer(agentStr);
            writer.save(agents);
            this->agents = agentStr.str();
        }

        addPeriodic("MockAugLoop::send", 0.9, [=] (uint64_t) {
            toAug.sendMessage(
                "redis-augmentation", "AUGMENT", "1.0", "redis-augmentation",
                to_string(random()), "datacratic", sampleBr,
                agents, Date::now());

            sent++;
        });

        MessageLoop::start();
    }

    ZmqNamedClientBus toAug;
    string agents;
    size_t sent, recv;
};

BOOST_AUTO_TEST_CASE( redisAugmentorTest )
{
    enum {
        FeederThreads = 1,
        TestLength = 20,
        RedisThreads = 2
    };

    // Setup Redis -- assuming an instance runs locally
    // on default port.
    {
    	using namespace Redis;
    	AsyncConnection redis(Address("localhost:6379"));
    	// set a few keys
        Command mset(MSET);
        mset.addArg("rtbkit:redis:winSurcharges.surcharge.USD/1M:50"); mset.addArg(123.45);
        mset.addArg("rtbkit:redis:id:85885bb0-b91b-11e2-c4cf-7fba90171555"); mset.addArg(9876);
        mset.addArg("rtbkit:redis:url:http://myonlinearcade.com/"); mset.addArg("JSCRIPT");

        Result result = redis.exec(mset);
        BOOST_CHECK_EQUAL(result.ok(), true);
    }

    auto proxies = make_shared<ServiceProxies>();

    AgentConfigurationService agentConfig(proxies, "config");
    agentConfig.unsafeDisableMonitor();
    agentConfig.init();
    agentConfig.bindTcp();
    agentConfig.start();

    atomic<size_t> processed(0);

    TestAgent agent1(proxies, "bob-the-agent");
    agent1.init();
    agent1.start();
    agent1.configure();
    {
    	AugmentationConfig aug_conf;
    	aug_conf.name = "redis";
    	aug_conf.required = true;
    	auto& v =  aug_conf.config;
    	Json::Value av(Json::arrayValue);
    	av.append("winSurcharges.surcharge.USD/1M");
    	av.append("id");
    	av.append("exchange");
    	av.append("foo.bar"); // not found
    	v["aug-list"] = av;
    	v["aug-prefix"] = "rtbkit:redis";
    	agent1.config.addAugmentation(aug_conf);
    }
    agent1.doConfig (agent1.config);

    TestAgent agent2(proxies, "alice-the-agent");
    agent2.config.account = {"aliceCampaign", "aliceStrategy"};
    agent2.init();
    agent2.start();
    agent2.doConfig(agent2.config);
    {
    	AugmentationConfig aug_conf;
    	aug_conf.name = "redis";
    	aug_conf.required = true;
    	auto& v =  aug_conf.config;
    	Json::Value av(Json::arrayValue);
    	av.append("id");
    	av.append("url"); // not found
    	v["aug-list"] = av;
    	v["aug-prefix"] = "rtbkit:redis";
    	agent2.config.addAugmentation(aug_conf);
    }
    agent2.doConfig (agent2.config);

    cerr << "init feeders\n";

    vector< std::shared_ptr<MockAugmentationLoop> > feederThreads;
    for (size_t i = 0; i < FeederThreads; ++i) {
        feederThreads.emplace_back(new MockAugmentationLoop(proxies));
        feederThreads.back()->start();
    }

    cerr << "init aug\n";

    RedisAugmentor aug("redis-augmentation", "redis-augmentation", proxies, "localhost:6379");
    aug.init(RedisThreads);
    aug.start();

    this_thread::sleep_for(chrono::milliseconds(100));

    cerr << "sleeping..." << endl;

    for (size_t i = 0; i < TestLength; ++i) {
        this_thread::sleep_for(chrono::seconds(1));
        cerr << "[ " << i << " / " << TestLength << " ]: "
             << "load=" << aug.sampleLoad()
             << ", prob=" << aug.shedProbability()
             << endl;
    }

    cerr << "WOKE UP!" << endl;

    size_t sent = 0, recv = 0;
    for (auto& th : feederThreads) {
        th->shutdown();
        sent += th->sent;
        recv += th->recv;
    }
    aug.shutdown();

    BOOST_CHECK_EQUAL(aug_vec.size(),sent);
    BOOST_CHECK_EQUAL(sent,recv);
    for (const auto& str: aug_vec)
    	BOOST_CHECK_EQUAL(str, aug_str);

    cerr << "sent: " << sent << endl
         << "proc: " << processed << endl
         << "recv: " << recv << endl;

    proxies->events->dump(cerr);
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "transformcontact.h"

#include "transformname.h"
#include "transformnickname.h"
#include "transformphonenumber.h"
#include "transformemail.h"

#include <qtcontacts.h>
#include <cntfldst.h>
#include <cntdb.h>
#include <cntdbobs.h>
#include <cntitem.h>

#include <QDebug>

TransformContact::TransformContact()
{
	initializeTransformContactData();
}

TransformContact::~TransformContact()
{
}

void TransformContact::initializeTransformContactData()
{
	//These can be added to normal list, if we loop through it.
	m_transformContactData.insert(Name, new TransformName);
	m_transformContactData.insert(Nickname, new TransformNickname);
	m_transformContactData.insert(PhoneNumber, new TransformPhoneNumber);
	m_transformContactData.insert(EmailAddress, new TransformEmail);
}

QContact TransformContact::transformContact(CContactItem &contact) const
{
		// Create a new QContact
		QContact newQtContact;
		newQtContact.setId(contact.Id());

		// Iterate through the CContactItemFieldSet, creating
		// new fields for the QContact
		CContactItemFieldSet& fields(contact.CardFields());

		const int numFields(fields.Count());

		for(int i(0); i < numFields; ++i)
		{
			QContactDetail *detail = transformItemField( fields[i], newQtContact );

			if(detail)
			{
				newQtContact.saveDetail(detail);
			}
		}

		return newQtContact;
}

/*! Transform a QContact into a Symbian CContactItem.
 *  This will convert all supported fields to the CContactItem format.
 *
 * \param contact A reference to a QContact to be converted.
 * \param contactItem A reference to the CContactItem to add the fields to.
*/
void TransformContact::transformContactL(
        QContact &contact,
        CContactItem &contactItem) const
{
	// Copy all fields to the Symbian contact.
	QList<QContactDetail> detailList(contact.details());

	// Iterate through the contact details in the QContact
	const int detailCount(detailList.count());

	for(int i(0); i < detailCount; ++i)
	{
		QList<CContactItemField *> fieldList = transformDetailL( detailList.at(i) );
		int fieldCount = fieldList.count();

		for (int i = 0; i < fieldCount; i++)
        {
			//transform ownership of field
		    contactItem.AddFieldL(*fieldList.at(i));
		}
	}
}

QList<CContactItemField *> TransformContact::transformDetailL(const QContactDetail &detail) const
{
	QList<CContactItemField *> itemFieldList;
	QString detailName(detail.definitionName());

	QMap<ContactData, TransformContactData*>::const_iterator i = m_transformContactData.constBegin();
	while (i != m_transformContactData.constEnd()) {
        if (i.value()->supportsDetail(detailName)) {
            itemFieldList = i.value()->transformDetailL(detail);
            break;
	    }
        ++i;
    }

	return itemFieldList;
}

QContactDetail *TransformContact::transformItemField(const CContactItemField& field, const QContact &contact) const
{
	QContactDetail *detail(0);
	TUint32 fieldType(field.ContentType().FieldType(0).iUid);

	QMap<ContactData, TransformContactData*>::const_iterator i = m_transformContactData.constBegin();
	while (i != m_transformContactData.constEnd()) {
        if (i.value()->supportsField(fieldType)) {
            detail = i.value()->transformItemField(field, contact);
            break;
        }
        ++i;
	 }

	return detail;
}

<commit_msg>Fixed a regression error with saving contact details<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "transformcontact.h"

#include "transformname.h"
#include "transformnickname.h"
#include "transformphonenumber.h"
#include "transformemail.h"

#include <qtcontacts.h>
#include <cntfldst.h>
#include <cntdb.h>
#include <cntdbobs.h>
#include <cntitem.h>

#include <QDebug>

TransformContact::TransformContact()
{
	initializeTransformContactData();
}

TransformContact::~TransformContact()
{
}

void TransformContact::initializeTransformContactData()
{
	//These can be added to normal list, if we loop through it.
	m_transformContactData.insert(Name, new TransformName);
	m_transformContactData.insert(Nickname, new TransformNickname);
	m_transformContactData.insert(PhoneNumber, new TransformPhoneNumber);
	m_transformContactData.insert(EmailAddress, new TransformEmail);
}

QContact TransformContact::transformContact(CContactItem &contact) const
{
		// Create a new QContact
		QContact newQtContact;
		newQtContact.setId(contact.Id());

		// Iterate through the CContactItemFieldSet, creating
		// new fields for the QContact
		CContactItemFieldSet& fields(contact.CardFields());

		const int numFields(fields.Count());

		for(int i(0); i < numFields; ++i)
		{
			QContactDetail *detail = transformItemField( fields[i], newQtContact );

			if(detail)
			{
				newQtContact.saveDetail(detail);
			}
		}

		return newQtContact;
}

/*! Transform a QContact into a Symbian CContactItem.
 *  This will convert all supported fields to the CContactItem format.
 *
 * \param contact A reference to a QContact to be converted.
 * \param contactItem A reference to the CContactItem to add the fields to.
*/
void TransformContact::transformContactL(
        QContact &contact,
        CContactItem &contactItem) const
{
	//Create a new fieldSet
	CContactItemFieldSet *fieldSet = CContactItemFieldSet::NewLC();

	// Copy all fields to the Symbian contact.
	QList<QContactDetail> detailList(contact.details());

	// Iterate through the contact details in the QContact
	const int detailCount(detailList.count());

	for(int i(0); i < detailCount; ++i)
	{
		QList<CContactItemField *> fieldList = transformDetailL( detailList.at(i) );
		int fieldCount = fieldList.count();

		for (int i = 0; i < fieldCount; i++)
        {
			//Add field to fieldSet
			fieldSet->AddL(*fieldList.at(i));
		}
	}

	contactItem.UpdateFieldSet(fieldSet);
	CleanupStack::Pop(fieldSet);
}

QList<CContactItemField *> TransformContact::transformDetailL(const QContactDetail &detail) const
{
	QList<CContactItemField *> itemFieldList;
	QString detailName(detail.definitionName());

	QMap<ContactData, TransformContactData*>::const_iterator i = m_transformContactData.constBegin();
	while (i != m_transformContactData.constEnd()) {
        if (i.value()->supportsDetail(detailName)) {
            itemFieldList = i.value()->transformDetailL(detail);
            break;
	    }
        ++i;
    }

	return itemFieldList;
}

QContactDetail *TransformContact::transformItemField(const CContactItemField& field, const QContact &contact) const
{
	QContactDetail *detail(0);
	TUint32 fieldType(field.ContentType().FieldType(0).iUid);

	QMap<ContactData, TransformContactData*>::const_iterator i = m_transformContactData.constBegin();
	while (i != m_transformContactData.constEnd()) {
        if (i.value()->supportsField(fieldType)) {
            detail = i.value()->transformItemField(field, contact);
            break;
        }
        ++i;
	 }

	return detail;
}

<|endoftext|>


<commit_before>/* net6 - Library providing IPv4/IPv6 network access
 * Copyright (C) 2005 Armin Burgmeier / 0x539 dev group
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "error.hpp"
#include "select.hpp"

net6::selector::selector()
{
/*	FD_ZERO(&read_set);
	FD_ZERO(&write_set);
	FD_ZERO(&error_set);*/
}

net6::selector::~selector()
{
}

void net6::selector::add(const socket& sock, socket::condition condition)
{
	if(condition & socket::INCOMING)
	{
//		FD_SET(sock.cobj(), &read_set);
		read_list.push_back(sock);
	}

	if(condition & socket::OUTGOING)
	{
//		FD_SET(sock.cobj(), &write_set);
		write_list.push_back(sock);
	}

	if(condition & socket::IOERROR)
	{
//		FD_SET(sock.cobj(), &error_set);
		error_list.push_back(sock);
	}
}

void net6::selector::remove(const socket& sock, socket::condition condition)
{
	if(condition & socket::INCOMING)
	{
//		FD_CLR(sock.cobj(), &read_set);
		read_list.erase(std::remove(read_list.begin(), read_list.end(),
		                sock), read_list.end() );
	}

	if(condition & socket::OUTGOING)
	{
//		FD_CLR(sock.cobj(), &write_set);
		write_list.erase(std::remove(write_list.begin(),
		                 write_list.end(), sock), write_list.end() );
	}

	if(condition & socket::IOERROR)
	{
//		FD_CLR(sock.cobj(), &error_set);
		error_list.erase(std::remove(error_list.begin(),
		                 error_list.end(), sock), error_list.end() );
	}
}

bool
net6::selector::check(const socket& sock, socket::condition condition) const
{
	if(condition & socket::INCOMING)
		if(std::find(read_list.begin(), read_list.end(), sock) !=
		   read_list.end() )
			return true;

	if(condition & socket::OUTGOING)
		if(std::find(write_list.begin(), write_list.end(), sock) !=
		   write_list.end() )
			return true;

	if(condition & socket::IOERROR)
		if(std::find(error_list.begin(), error_list.end(), sock) !=
		   error_list.end() )
			return true;

	return false;
}

void net6::selector::select()
{
	select_impl(NULL);
}

void net6::selector::select(unsigned long timeout)
{
	timeval tv;
	tv.tv_sec = timeout / 1000;
	tv.tv_usec = timeout % 1000;
	select_impl(&tv);
}

net6::selector::signal_socket_event_type net6::selector::socket_event() const
{
	return signal_socket_event;
}

void net6::selector::select_impl(timeval* tv)
{
	// Determinate the highest file descriptor number for select()
	socket::socket_type max_fd = 0;
	fd_set readfs, writefs, errorfs;
	std::list<socket>::iterator i;

	FD_ZERO(&readfs);
	FD_ZERO(&writefs);
	FD_ZERO(&errorfs);

	for(i = read_list.begin(); i != read_list.end(); ++ i)
	{
		if(i->cobj() > max_fd)
			max_fd = i->cobj();
		FD_SET(i->cobj(), &readfs);
	}

	for(i = write_list.begin(); i != write_list.end(); ++ i)
	{
		if(i->cobj() > max_fd)
			max_fd = i->cobj();
		FD_SET(i->cobj(), &writefs);
	}

	for(i = error_list.begin(); i != error_list.end(); ++ i)
	{
		if(i->cobj() > max_fd)
			max_fd = i->cobj();
		FD_SET(i->cobj(), &errorfs);
	}

	int retval = ::select(max_fd + 1, &readfs, &writefs,
	                      &errorfs, tv);

	if(retval == -1)
		throw error(net6::error::SYSTEM);

	// Check for selected sockets
	std::list<socket> read_event, write_event, error_event;
	for(i = read_list.begin(); i != read_list.end(); ++ i)
		if(FD_ISSET(i->cobj(), &readfs) )
			read_event.push_back(*i);

	for(i = write_list.begin(); i != write_list.end(); ++ i)
		if(FD_ISSET(i->cobj(), &writefs) )
			write_event.push_back(*i);

	for(i = error_list.begin(); i != error_list.end(); ++ i)
		if(FD_ISSET(i->cobj(), &errorfs) )
			error_event.push_back(*i);

	// Reset fd_sets
/*	FD_ZERO(&read_set);
	FD_ZERO(&write_set);
	FD_ZERO(&error_set);

	for(i = read_list.begin(); i != read_list.end(); ++ i)
		FD_SET(i->cobj(), &read_set);
	for(i = write_list.begin(); i != write_list.end(); ++ i)
		FD_SET(i->cobj(), &write_set);
	for(i = error_list.begin(); i != error_list.end(); ++ i)
		FD_SET(i->cobj(), &error_set);*/

	// Emit signals in a seperate list to allow the signal
	// handlers to modify the select list
	std::list<socket>::iterator a;
	for(a = read_event.begin(); a != read_event.end(); ++ a)
		if(a->data->refcount > 1)
			if(!on_socket_event(*a, socket::INCOMING) )
				a->on_io(socket::INCOMING);

	for(a = write_event.begin(); a != write_event.end(); ++ a)
		if(a->data->refcount > 1)
			if(!on_socket_event(*a, socket::OUTGOING) )
				a->on_io(socket::OUTGOING);

	for(a = error_event.begin(); a != error_event.end(); ++ a)
		if(a->data->refcount > 1)
			if(!on_socket_event(*a, socket::IOERROR) )
				a->on_io(socket::IOERROR);
}

bool net6::selector::on_socket_event(socket& sock, socket::condition cond)
{
	return signal_socket_event.emit(sock, cond);
}
<commit_msg>[project @ Added missing #include of <algorithm> (required for std::find, std::remove on MSVC8).]<commit_after>/* net6 - Library providing IPv4/IPv6 network access
 * Copyright (C) 2005 Armin Burgmeier / 0x539 dev group
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "error.hpp"
#include "select.hpp"
#include <algorithm>

net6::selector::selector()
{
/*	FD_ZERO(&read_set);
	FD_ZERO(&write_set);
	FD_ZERO(&error_set);*/
}

net6::selector::~selector()
{
}

void net6::selector::add(const socket& sock, socket::condition condition)
{
	if(condition & socket::INCOMING)
	{
//		FD_SET(sock.cobj(), &read_set);
		read_list.push_back(sock);
	}

	if(condition & socket::OUTGOING)
	{
//		FD_SET(sock.cobj(), &write_set);
		write_list.push_back(sock);
	}

	if(condition & socket::IOERROR)
	{
//		FD_SET(sock.cobj(), &error_set);
		error_list.push_back(sock);
	}
}

void net6::selector::remove(const socket& sock, socket::condition condition)
{
	if(condition & socket::INCOMING)
	{
//		FD_CLR(sock.cobj(), &read_set);
		read_list.erase(std::remove(read_list.begin(), read_list.end(),
		                sock), read_list.end() );
	}

	if(condition & socket::OUTGOING)
	{
//		FD_CLR(sock.cobj(), &write_set);
		write_list.erase(std::remove(write_list.begin(),
		                 write_list.end(), sock), write_list.end() );
	}

	if(condition & socket::IOERROR)
	{
//		FD_CLR(sock.cobj(), &error_set);
		error_list.erase(std::remove(error_list.begin(),
		                 error_list.end(), sock), error_list.end() );
	}
}

bool
net6::selector::check(const socket& sock, socket::condition condition) const
{
	if(condition & socket::INCOMING)
		if(std::find(read_list.begin(), read_list.end(), sock) !=
		   read_list.end() )
			return true;

	if(condition & socket::OUTGOING)
		if(std::find(write_list.begin(), write_list.end(), sock) !=
		   write_list.end() )
			return true;

	if(condition & socket::IOERROR)
		if(std::find(error_list.begin(), error_list.end(), sock) !=
		   error_list.end() )
			return true;

	return false;
}

void net6::selector::select()
{
	select_impl(NULL);
}

void net6::selector::select(unsigned long timeout)
{
	timeval tv;
	tv.tv_sec = timeout / 1000;
	tv.tv_usec = timeout % 1000;
	select_impl(&tv);
}

net6::selector::signal_socket_event_type net6::selector::socket_event() const
{
	return signal_socket_event;
}

void net6::selector::select_impl(timeval* tv)
{
	// Determinate the highest file descriptor number for select()
	socket::socket_type max_fd = 0;
	fd_set readfs, writefs, errorfs;
	std::list<socket>::iterator i;

	FD_ZERO(&readfs);
	FD_ZERO(&writefs);
	FD_ZERO(&errorfs);

	for(i = read_list.begin(); i != read_list.end(); ++ i)
	{
		if(i->cobj() > max_fd)
			max_fd = i->cobj();
		FD_SET(i->cobj(), &readfs);
	}

	for(i = write_list.begin(); i != write_list.end(); ++ i)
	{
		if(i->cobj() > max_fd)
			max_fd = i->cobj();
		FD_SET(i->cobj(), &writefs);
	}

	for(i = error_list.begin(); i != error_list.end(); ++ i)
	{
		if(i->cobj() > max_fd)
			max_fd = i->cobj();
		FD_SET(i->cobj(), &errorfs);
	}

	int retval = ::select(max_fd + 1, &readfs, &writefs,
	                      &errorfs, tv);

	if(retval == -1)
		throw error(net6::error::SYSTEM);

	// Check for selected sockets
	std::list<socket> read_event, write_event, error_event;
	for(i = read_list.begin(); i != read_list.end(); ++ i)
		if(FD_ISSET(i->cobj(), &readfs) )
			read_event.push_back(*i);

	for(i = write_list.begin(); i != write_list.end(); ++ i)
		if(FD_ISSET(i->cobj(), &writefs) )
			write_event.push_back(*i);

	for(i = error_list.begin(); i != error_list.end(); ++ i)
		if(FD_ISSET(i->cobj(), &errorfs) )
			error_event.push_back(*i);

	// Reset fd_sets
/*	FD_ZERO(&read_set);
	FD_ZERO(&write_set);
	FD_ZERO(&error_set);

	for(i = read_list.begin(); i != read_list.end(); ++ i)
		FD_SET(i->cobj(), &read_set);
	for(i = write_list.begin(); i != write_list.end(); ++ i)
		FD_SET(i->cobj(), &write_set);
	for(i = error_list.begin(); i != error_list.end(); ++ i)
		FD_SET(i->cobj(), &error_set);*/

	// Emit signals in a seperate list to allow the signal
	// handlers to modify the select list
	std::list<socket>::iterator a;
	for(a = read_event.begin(); a != read_event.end(); ++ a)
		if(a->data->refcount > 1)
			if(!on_socket_event(*a, socket::INCOMING) )
				a->on_io(socket::INCOMING);

	for(a = write_event.begin(); a != write_event.end(); ++ a)
		if(a->data->refcount > 1)
			if(!on_socket_event(*a, socket::OUTGOING) )
				a->on_io(socket::OUTGOING);

	for(a = error_event.begin(); a != error_event.end(); ++ a)
		if(a->data->refcount > 1)
			if(!on_socket_event(*a, socket::IOERROR) )
				a->on_io(socket::IOERROR);
}

bool net6::selector::on_socket_event(socket& sock, socket::condition cond)
{
	return signal_socket_event.emit(sock, cond);
}
<|endoftext|>


<commit_before>#ifndef CUSTOMPROJECTION_HH
#define CUSTOMPROJECTION_HH

#include <dune/fem/quadrature/cachequad.hh>
#include <dune/fem/operator/common/operator.hh>
#include <dune/fem/function/common/discretefunction.hh>
#include <dune/fem/function/common/discretefunctionadapter.hh>
#include <dune/fem/operator/1order/localmassmatrix.hh>

namespace Stuff {

class CustomProjection {

public:
	template < class OriginFunctionType, class DestinationFunctionType >
	static void project (const OriginFunctionType& f, DestinationFunctionType& discFunc)
	{
		typedef typename DestinationFunctionType::FunctionSpaceType
			DiscreteFunctionSpace;
		typedef typename DiscreteFunctionSpace::GridPartType
			GridPart;
		typedef typename GridPart::template Codim< 0 >::IteratorType
			EntityIteratorType;
		typedef typename GridPart::GridType::template Codim< 0 >::Entity
			EntityType;
		typedef typename GridPart::IntersectionIteratorType
			IntersectionIteratorType;
		typedef typename IntersectionIteratorType::EntityPointer
			EntityPointer;
		typedef typename DestinationFunctionType::LocalFunctionType
			LocalFunctionType;
		typedef Dune::CachingQuadrature< GridPart, 1 >
			FaceQuadratureType;
		typedef typename DiscreteFunctionSpace::BaseFunctionSetType
			BaseFunctionSetType;
		typedef typename DiscreteFunctionSpace::RangeType
			RangeType;
		const DiscreteFunctionSpace& space_ = discFunc.space();
		const GridPart& gridPart_ = space_.gridPart();
		RangeType phi (0.0);
		EntityIteratorType entityItEndLog = space_.end();
		for (   EntityIteratorType it = space_.begin();
				it != entityItEndLog;
				++it )
		{
			EntityType& e = *it;
			LocalFunctionType lf = discFunc.localFunction( e );
			BaseFunctionSetType baseFunctionset = space_.baseFunctionSet( *it );
			unsigned int intersection_count = 0;
			IntersectionIteratorType intItEnd = gridPart_.iend( *it );
			for (   IntersectionIteratorType intIt = gridPart_.ibegin( *it );
					intIt != intItEnd;
					++intIt ) {
				intersection_count++;
				FaceQuadratureType faceQuadrature( gridPart_,
												   intIt,
												   ( 4 * space_.order() ) + 1,
												   FaceQuadratureType::INSIDE );
				typename DestinationFunctionType::RangeType ret;
				for ( int qP = 0; qP < faceQuadrature.nop(); ++qP ) {
					const double intel =
						 faceQuadrature.weight(qP) * e.geometry().integrationElement( faceQuadrature.point(qP) ); // general case

					if ( intIt.boundary() )
					{
						f.evaluate( faceQuadrature.point(qP), ret, intIt );

						for ( int i = 0; i < baseFunctionset.numBaseFunctions(); ++i ) {
							baseFunctionset.evaluate(i, faceQuadrature[qP], phi);
							lf[i] += intel * (ret * phi) ;
						}
					}
				}
			}
		}
	}
};

}//end namespace Stuff
#endif // CUSTOMPROJECTION_HH
<commit_msg>notes for CustomProjection<commit_after>#ifndef CUSTOMPROJECTION_HH
#define CUSTOMPROJECTION_HH

#include <dune/fem/quadrature/cachequad.hh>
#include <dune/fem/operator/common/operator.hh>
#include <dune/fem/function/common/discretefunction.hh>
#include <dune/fem/function/common/discretefunctionadapter.hh>
#include <dune/fem/operator/1order/localmassmatrix.hh>

namespace Stuff {

/** A custom projection of an analytical function that uses a non-standard evalute signature:\n
		<pre>template < class IntersectionIteratorType >\n
		void evaluate( const DomainType& arg, RangeType& ret, const IntersectionIteratorType& faceIter ) const<pre>\n
	\note example being our boundary functions
	\note output currently somewhat meaningless
	\see analyticaldata.hh
**/

class CustomProjection {

public:
	template < class OriginFunctionType, class DestinationFunctionType >
	static void project (const OriginFunctionType& f, DestinationFunctionType& discFunc)
	{
		typedef typename DestinationFunctionType::FunctionSpaceType
			DiscreteFunctionSpace;
		typedef typename DiscreteFunctionSpace::GridPartType
			GridPart;
		typedef typename GridPart::template Codim< 0 >::IteratorType
			EntityIteratorType;
		typedef typename GridPart::GridType::template Codim< 0 >::Entity
			EntityType;
		typedef typename GridPart::IntersectionIteratorType
			IntersectionIteratorType;
		typedef typename IntersectionIteratorType::EntityPointer
			EntityPointer;
		typedef typename DestinationFunctionType::LocalFunctionType
			LocalFunctionType;
		typedef Dune::CachingQuadrature< GridPart, 1 >
			FaceQuadratureType;
		typedef typename DiscreteFunctionSpace::BaseFunctionSetType
			BaseFunctionSetType;
		typedef typename DiscreteFunctionSpace::RangeType
			RangeType;
		const DiscreteFunctionSpace& space_ = discFunc.space();
		const GridPart& gridPart_ = space_.gridPart();
		RangeType phi (0.0);
		EntityIteratorType entityItEndLog = space_.end();
		for (   EntityIteratorType it = space_.begin();
				it != entityItEndLog;
				++it )
		{
			EntityType& e = *it;
			LocalFunctionType lf = discFunc.localFunction( e );
			BaseFunctionSetType baseFunctionset = space_.baseFunctionSet( *it );
			unsigned int intersection_count = 0;
			IntersectionIteratorType intItEnd = gridPart_.iend( *it );
			for (   IntersectionIteratorType intIt = gridPart_.ibegin( *it );
					intIt != intItEnd;
					++intIt ) {
				intersection_count++;
				FaceQuadratureType faceQuadrature( gridPart_,
												   intIt,
												   ( 4 * space_.order() ) + 1,
												   FaceQuadratureType::INSIDE );
				typename DestinationFunctionType::RangeType ret;
				for ( int qP = 0; qP < faceQuadrature.nop(); ++qP ) {
					const double intel =
						 faceQuadrature.weight(qP) * e.geometry().integrationElement( faceQuadrature.point(qP) ); // general case

					if ( intIt.boundary() )
					{
						f.evaluate( faceQuadrature.point(qP), ret, intIt );

						for ( int i = 0; i < baseFunctionset.numBaseFunctions(); ++i ) {
							baseFunctionset.evaluate(i, faceQuadrature[qP], phi);
							lf[i] += intel * (ret * phi) ;
						}
					}
				}
			}
		}
	}
};

}//end namespace Stuff
#endif // CUSTOMPROJECTION_HH
<|endoftext|>


<commit_before>
/*
 *  client.cpp
 *
 *  Handles the client env.
 *
 *  Created by Ryan Faulkner on 2014-06-08
 *  Copyright (c) 2014. All rights reserved.
 */

#include <iostream>
#include <string>
#include <redis3m/connection.h>
#include "parse.h"

using namespace std;

bool handleUserInput(string input) {
    return true;
}

int main() {
    string line;
    Parser* parser = new Parser();
    // RedisHandler rh;

    // Read the input
    while (1) {
        cout << "databayes> ";
        getline (cin, line);
        parser->parse(line);
    }
    return 0;
}
<commit_msg>add - handling for statements not accepted by the parser<commit_after>
/*
 *  client.cpp
 *
 *  Handles the client env.
 *
 *  Created by Ryan Faulkner on 2014-06-08
 *  Copyright (c) 2014. All rights reserved.
 */

#include <iostream>
#include <string>
#include <redis3m/connection.h>
#include "parse.h"

#define BAD_CMD "Bad command."

using namespace std;

bool handleUserInput(string input) {
    return true;
}

int main() {
    string line;
    Parser* parser = new Parser();
    // RedisHandler rh;

    // Read the input
    while (1) {
        cout << "databayes> ";
        getline (cin, line);
        if (!parser->parse(line)) {
            cout << BAD_CMD << endl;
        }

    }
    return 0;
}
<|endoftext|>


<commit_before>
/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/point.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/var.h"

#include "SkBase64.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkColor.h"
#include "SkDebugger.h"
#include "SkGraphics.h"
#include "SkStream.h"
#include "SkString.h"

class SkiaInstance;

// Used by SkDebugf
SkiaInstance* gPluginInstance;

void FlushCallback(void* data, int32_t result);

// Skia's subclass of pp::Instance, our interface with the browser.
class SkiaInstance : public pp::Instance {
public:
    explicit SkiaInstance(PP_Instance instance)
        : pp::Instance(instance)
        , fCanvas(NULL)
        , fPicture(NULL)
        , fFlushLoopRunning(false)
        , fFlushPending(false)

    {
        gPluginInstance = this;
        SkGraphics::Init();
    }

    virtual ~SkiaInstance() {
        SkGraphics::Term();
        gPluginInstance = NULL;
    }

    virtual void HandleMessage(const pp::Var& var_message) {
        // Receive a message from javascript.
        if (var_message.is_string()) {
            SkString msg(var_message.AsString().c_str());
            if (msg.startsWith("init")) {
            } else if (msg.startsWith("LoadSKP")) {
                size_t startIndex = strlen("LoadSKP");
                size_t dataSize = msg.size()/sizeof(char) - startIndex;
                SkBase64 decodedData;
                decodedData.decode(msg.c_str() + startIndex, dataSize);
                size_t decodedSize = 3 * (dataSize / 4);
                SkDebugf("Got size: %d\n", decodedSize);
                if (!decodedData.getData()) {
                    SkDebugf("Failed to decode SKP\n");
                    return;
                }
                SkMemoryStream pictureStream(decodedData.getData(), decodedSize);
                fPicture = new SkPicture(&pictureStream);
                if (fPicture->width() == 0 || fPicture->height() == 0) {
                    SkDebugf("Failed to create SKP.\n");
                    return;
                }
                fDebugger.loadPicture(fPicture);

                // Set up the command list.
                SkTArray<SkString>* commands = fDebugger.getDrawCommandsAsStrings();
                PostMessage("ClearCommands");
                for (int i = 0; i < commands->count(); ++i) {
                    SkString addCommand("AddCommand:");
                    addCommand.append((*commands)[i]);
                    PostMessage(addCommand.c_str());
                }
                PostMessage("UpdateCommands");

                // Set the overview text.
                SkString overviewText;
                fDebugger.getOverviewText(NULL, 0.0, &overviewText, 1);
                overviewText.prepend("SetOverview:");
                PostMessage(overviewText.c_str());

                // Draw the SKP.
                if (!fFlushLoopRunning) {
                    Paint();
                }
            } else if (msg.startsWith("CommandSelected:")) {
                size_t startIndex = strlen("CommandSelected:");
                int index = atoi(msg.c_str() + startIndex);
                fDebugger.setIndex(index);
                if (!fFlushLoopRunning) {
                    Paint();
                }
            } else if (msg.startsWith("Rewind")) {
                fCanvas->clear(SK_ColorWHITE);
                fDebugger.setIndex(0);
                if (!fFlushLoopRunning) {
                    Paint();
                }
            } else if (msg.startsWith("StepBack")) {
                fCanvas->clear(SK_ColorWHITE);
                int currentIndex = fDebugger.index();
                if (currentIndex > 1) {
                    fDebugger.setIndex(currentIndex - 1);
                    if (!fFlushLoopRunning) {
                        Paint();
                    }
                }
            } else if (msg.startsWith("Pause")) {
                // TODO(borenet)
            } else if (msg.startsWith("StepForward")) {
                int currentIndex = fDebugger.index();
                if (currentIndex < fDebugger.getSize() -1) {
                    fDebugger.setIndex(currentIndex + 1);
                    if (!fFlushLoopRunning) {
                        Paint();
                    }
                }
            } else if (msg.startsWith("Play")) {
                fDebugger.setIndex(fDebugger.getSize() - 1);
                if (!fFlushLoopRunning) {
                    Paint();
                }
            }
        }
    }

    void Paint() {
        if (!fImage.is_null()) {
            fDebugger.draw(fCanvas);
            fDeviceContext.PaintImageData(fImage, pp::Point(0, 0));
            if (!fFlushPending) {
                fFlushPending = true;
                fDeviceContext.Flush(pp::CompletionCallback(&FlushCallback, this));
            } else {
                SkDebugf("A flush is pending... Skipping flush.\n");
            }
        } else {
            SkDebugf("No pixels to write to!\n");
        }
    }

    virtual void DidChangeView(const pp::Rect& position, const pp::Rect& clip) {
        if (position.size().width() == fWidth &&
            position.size().height() == fHeight) {
            return;  // We don't care about the position, only the size.
        }
        fWidth = position.size().width();
        fHeight = position.size().height();

        fDeviceContext = pp::Graphics2D(this, pp::Size(fWidth, fHeight), false);
        if (!BindGraphics(fDeviceContext)) {
            SkDebugf("Couldn't bind the device context\n");
            return;
        }
        fImage = pp::ImageData(this,
                               PP_IMAGEDATAFORMAT_BGRA_PREMUL,
                               pp::Size(fWidth, fHeight), false);
        fBitmap.setConfig(SkBitmap::kARGB_8888_Config, fWidth, fHeight);
        fBitmap.setPixels(fImage.data());
        if (fCanvas) {
            delete fCanvas;
        }
        fCanvas = new SkCanvas(fBitmap);
        fCanvas->clear(SK_ColorWHITE);
        if (!fFlushLoopRunning) {
            Paint();
        }
    }

    void OnFlush() {
        fFlushLoopRunning = true;
        fFlushPending = false;
        Paint();
    }

private:
    pp::Graphics2D fDeviceContext;
    pp::ImageData fImage;
    int fWidth;
    int fHeight;

    SkBitmap fBitmap;
    SkCanvas* fCanvas;
    SkDebugger fDebugger;
    SkPicture* fPicture;

    bool fFlushLoopRunning;
    bool fFlushPending;
};

void FlushCallback(void* data, int32_t result) {
    static_cast<SkiaInstance*>(data)->OnFlush();
}

class SkiaModule : public pp::Module {
public:
    SkiaModule() : pp::Module() {}
    virtual ~SkiaModule() {}

    virtual pp::Instance* CreateInstance(PP_Instance instance) {
        return new SkiaInstance(instance);
    }
};

namespace pp {
Module* CreateModule() {
    return new SkiaModule();
}
}  // namespace pp
<commit_msg>Use CreateFromStream in nacl debugger.<commit_after>
/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/point.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/var.h"

#include "SkBase64.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkColor.h"
#include "SkDebugger.h"
#include "SkGraphics.h"
#include "SkStream.h"
#include "SkString.h"

class SkiaInstance;

// Used by SkDebugf
SkiaInstance* gPluginInstance;

void FlushCallback(void* data, int32_t result);

// Skia's subclass of pp::Instance, our interface with the browser.
class SkiaInstance : public pp::Instance {
public:
    explicit SkiaInstance(PP_Instance instance)
        : pp::Instance(instance)
        , fCanvas(NULL)
        , fPicture(NULL)
        , fFlushLoopRunning(false)
        , fFlushPending(false)

    {
        gPluginInstance = this;
        SkGraphics::Init();
    }

    virtual ~SkiaInstance() {
        SkGraphics::Term();
        gPluginInstance = NULL;
    }

    virtual void HandleMessage(const pp::Var& var_message) {
        // Receive a message from javascript.
        if (var_message.is_string()) {
            SkString msg(var_message.AsString().c_str());
            if (msg.startsWith("init")) {
            } else if (msg.startsWith("LoadSKP")) {
                size_t startIndex = strlen("LoadSKP");
                size_t dataSize = msg.size()/sizeof(char) - startIndex;
                SkBase64 decodedData;
                decodedData.decode(msg.c_str() + startIndex, dataSize);
                size_t decodedSize = 3 * (dataSize / 4);
                SkDebugf("Got size: %d\n", decodedSize);
                if (!decodedData.getData()) {
                    SkDebugf("Failed to decode SKP\n");
                    return;
                }
                SkMemoryStream pictureStream(decodedData.getData(), decodedSize);
                fPicture = SkPicture::CreateFromStream(&pictureStream);
                if (fPicture->width() == 0 || fPicture->height() == 0) {
                    SkDebugf("Failed to create SKP.\n");
                    return;
                }
                fDebugger.loadPicture(fPicture);

                // Set up the command list.
                SkTArray<SkString>* commands = fDebugger.getDrawCommandsAsStrings();
                PostMessage("ClearCommands");
                for (int i = 0; i < commands->count(); ++i) {
                    SkString addCommand("AddCommand:");
                    addCommand.append((*commands)[i]);
                    PostMessage(addCommand.c_str());
                }
                PostMessage("UpdateCommands");

                // Set the overview text.
                SkString overviewText;
                fDebugger.getOverviewText(NULL, 0.0, &overviewText, 1);
                overviewText.prepend("SetOverview:");
                PostMessage(overviewText.c_str());

                // Draw the SKP.
                if (!fFlushLoopRunning) {
                    Paint();
                }
            } else if (msg.startsWith("CommandSelected:")) {
                size_t startIndex = strlen("CommandSelected:");
                int index = atoi(msg.c_str() + startIndex);
                fDebugger.setIndex(index);
                if (!fFlushLoopRunning) {
                    Paint();
                }
            } else if (msg.startsWith("Rewind")) {
                fCanvas->clear(SK_ColorWHITE);
                fDebugger.setIndex(0);
                if (!fFlushLoopRunning) {
                    Paint();
                }
            } else if (msg.startsWith("StepBack")) {
                fCanvas->clear(SK_ColorWHITE);
                int currentIndex = fDebugger.index();
                if (currentIndex > 1) {
                    fDebugger.setIndex(currentIndex - 1);
                    if (!fFlushLoopRunning) {
                        Paint();
                    }
                }
            } else if (msg.startsWith("Pause")) {
                // TODO(borenet)
            } else if (msg.startsWith("StepForward")) {
                int currentIndex = fDebugger.index();
                if (currentIndex < fDebugger.getSize() -1) {
                    fDebugger.setIndex(currentIndex + 1);
                    if (!fFlushLoopRunning) {
                        Paint();
                    }
                }
            } else if (msg.startsWith("Play")) {
                fDebugger.setIndex(fDebugger.getSize() - 1);
                if (!fFlushLoopRunning) {
                    Paint();
                }
            }
        }
    }

    void Paint() {
        if (!fImage.is_null()) {
            fDebugger.draw(fCanvas);
            fDeviceContext.PaintImageData(fImage, pp::Point(0, 0));
            if (!fFlushPending) {
                fFlushPending = true;
                fDeviceContext.Flush(pp::CompletionCallback(&FlushCallback, this));
            } else {
                SkDebugf("A flush is pending... Skipping flush.\n");
            }
        } else {
            SkDebugf("No pixels to write to!\n");
        }
    }

    virtual void DidChangeView(const pp::Rect& position, const pp::Rect& clip) {
        if (position.size().width() == fWidth &&
            position.size().height() == fHeight) {
            return;  // We don't care about the position, only the size.
        }
        fWidth = position.size().width();
        fHeight = position.size().height();

        fDeviceContext = pp::Graphics2D(this, pp::Size(fWidth, fHeight), false);
        if (!BindGraphics(fDeviceContext)) {
            SkDebugf("Couldn't bind the device context\n");
            return;
        }
        fImage = pp::ImageData(this,
                               PP_IMAGEDATAFORMAT_BGRA_PREMUL,
                               pp::Size(fWidth, fHeight), false);
        fBitmap.setConfig(SkBitmap::kARGB_8888_Config, fWidth, fHeight);
        fBitmap.setPixels(fImage.data());
        if (fCanvas) {
            delete fCanvas;
        }
        fCanvas = new SkCanvas(fBitmap);
        fCanvas->clear(SK_ColorWHITE);
        if (!fFlushLoopRunning) {
            Paint();
        }
    }

    void OnFlush() {
        fFlushLoopRunning = true;
        fFlushPending = false;
        Paint();
    }

private:
    pp::Graphics2D fDeviceContext;
    pp::ImageData fImage;
    int fWidth;
    int fHeight;

    SkBitmap fBitmap;
    SkCanvas* fCanvas;
    SkDebugger fDebugger;
    SkPicture* fPicture;

    bool fFlushLoopRunning;
    bool fFlushPending;
};

void FlushCallback(void* data, int32_t result) {
    static_cast<SkiaInstance*>(data)->OnFlush();
}

class SkiaModule : public pp::Module {
public:
    SkiaModule() : pp::Module() {}
    virtual ~SkiaModule() {}

    virtual pp::Instance* CreateInstance(PP_Instance instance) {
        return new SkiaInstance(instance);
    }
};

namespace pp {
Module* CreateModule() {
    return new SkiaModule();
}
}  // namespace pp
<|endoftext|>


<commit_before>#include "acmacs-base/range-v3.hh"
#include "acmacs-chart-2/chart.hh"
//#include "draw.hh"
#include "vaccines.hh"

// ----------------------------------------------------------------------

static inline acmacs::PointStyle& point_style_for(acmacs::PointStyle&& aStyle, hidb::Vaccines::PassageType pt)
{
    switch (pt) {
      case hidb::Vaccines::Egg:
          aStyle.aspect = AspectEgg;
          aStyle.rotation = NoRotation;
          break;
      case hidb::Vaccines::Cell:
          aStyle.aspect = AspectNormal;
          aStyle.rotation = NoRotation;
          break;
      case hidb::Vaccines::Reassortant:
          aStyle.aspect = AspectEgg;
          aStyle.rotation = RotationReassortant;
          break;
      case hidb::Vaccines::PassageTypeSize:
          break;
    }
    return aStyle;
}

Vaccines::Vaccines(const acmacs::chart::Chart& aChart)
    : mVaccinesOfChart{hidb::vaccines(aChart)}
{
    for (size_t vaccines_of_chart_index = 0; vaccines_of_chart_index < mVaccinesOfChart.size(); ++vaccines_of_chart_index) {
        auto update = [&](hidb::Vaccines::PassageType pt) {
            if (!mVaccinesOfChart[vaccines_of_chart_index].empty(pt)) {
                mEntries.emplace_back(vaccines_of_chart_index, pt, point_style_for(acmacs::PointStyle(), pt));
            }
        };
        hidb::Vaccines::for_each_passage_type(update);
    }

} // Vaccines::Vaccines

// ----------------------------------------------------------------------

std::string Vaccines::report(const hidb::Vaccines::ReportConfig& config) const
{
    std::string result;
    for (const auto& entry: mEntries) {
        if (*entry.style.shown) {
            const auto& vacc = mVaccinesOfChart[entry.vaccines_of_chart_index];
            const std::string s = vacc.report(entry.passage_type, config, entry.antigen_no);
            if (!s.empty())
                result += fmt::format("{:{}c}{} {} {}\n{}", ' ', config.indent_,  vacc.type(), vacc.name(), entry.style.fill, s);
        }
    }
    return result;

} // Vaccines::report

// ----------------------------------------------------------------------

std::vector<size_t> Vaccines::indices() const
{
    std::vector<size_t> ind;
    for (const auto& entry: mEntries) {
        if (*entry.style.shown) {
            if (const auto* vacc = mVaccinesOfChart[entry.vaccines_of_chart_index].for_passage_type(entry.passage_type, entry.antigen_no); vacc)
                ind.push_back(vacc->chart_antigen_index);
        }
    }
    return ind;

} // Vaccines::indices

// ----------------------------------------------------------------------

std::vector<size_t> Vaccines::indices(const VaccineMatchData& aMatchData) const
{
    std::vector<std::pair<size_t, hidb::Vaccines::PassageType>> ind_passage;
    for (const auto& entry: mEntries) {
        if (entry.match(mVaccinesOfChart, aMatchData)) {
            if (const auto* vacc = mVaccinesOfChart[entry.vaccines_of_chart_index].for_passage_type(entry.passage_type, aMatchData.no() /* entry.antigen_no */); vacc)
                ind_passage.emplace_back(vacc->chart_antigen_index, entry.passage_type);
        }
    }

    const auto to_index = [](const auto& en) { return en.first; };
    if (aMatchData.passage() == "cell-egg") {
        const auto is_cell = [](const auto& en) { return en.second == hidb::Vaccines::Cell; };
        if (ranges::any_of(ind_passage, is_cell))
            return ind_passage | ranges::views::filter(is_cell) | ranges::views::transform(to_index) | ranges::to_vector;
        else
            return ind_passage | ranges::views::transform(to_index) | ranges::to_vector;
    }
    else if (aMatchData.passage() == "egg-cell") {
        const auto is_egg = [](const auto& en) { return en.second == hidb::Vaccines::Egg; };
        if (ranges::any_of(ind_passage, is_egg))
            return ind_passage | ranges::views::filter(is_egg) | ranges::views::transform(to_index) | ranges::to_vector;
        else
            return ind_passage | ranges::views::transform(to_index) | ranges::to_vector;
    }

} // Vaccines::indices

// ----------------------------------------------------------------------

void Vaccines::plot(ChartDraw& aChartDraw) const
{
    for (const auto& entry: mEntries) {
        if (*entry.style.shown) {
            if (const auto* vacc = mVaccinesOfChart[entry.vaccines_of_chart_index].for_passage_type(entry.passage_type, entry.antigen_no); vacc)
                aChartDraw.modify(vacc->chart_antigen_index, entry.style, PointDrawingOrder::Raise);
        }
    }

} // Vaccines::plot

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>bug fix<commit_after>#include "acmacs-base/range-v3.hh"
#include "acmacs-chart-2/chart.hh"
//#include "draw.hh"
#include "vaccines.hh"

// ----------------------------------------------------------------------

static inline acmacs::PointStyle& point_style_for(acmacs::PointStyle&& aStyle, hidb::Vaccines::PassageType pt)
{
    switch (pt) {
      case hidb::Vaccines::Egg:
          aStyle.aspect = AspectEgg;
          aStyle.rotation = NoRotation;
          break;
      case hidb::Vaccines::Cell:
          aStyle.aspect = AspectNormal;
          aStyle.rotation = NoRotation;
          break;
      case hidb::Vaccines::Reassortant:
          aStyle.aspect = AspectEgg;
          aStyle.rotation = RotationReassortant;
          break;
      case hidb::Vaccines::PassageTypeSize:
          break;
    }
    return aStyle;
}

Vaccines::Vaccines(const acmacs::chart::Chart& aChart)
    : mVaccinesOfChart{hidb::vaccines(aChart)}
{
    for (size_t vaccines_of_chart_index = 0; vaccines_of_chart_index < mVaccinesOfChart.size(); ++vaccines_of_chart_index) {
        auto update = [&](hidb::Vaccines::PassageType pt) {
            if (!mVaccinesOfChart[vaccines_of_chart_index].empty(pt)) {
                mEntries.emplace_back(vaccines_of_chart_index, pt, point_style_for(acmacs::PointStyle(), pt));
            }
        };
        hidb::Vaccines::for_each_passage_type(update);
    }

} // Vaccines::Vaccines

// ----------------------------------------------------------------------

std::string Vaccines::report(const hidb::Vaccines::ReportConfig& config) const
{
    std::string result;
    for (const auto& entry: mEntries) {
        if (*entry.style.shown) {
            const auto& vacc = mVaccinesOfChart[entry.vaccines_of_chart_index];
            const std::string s = vacc.report(entry.passage_type, config, entry.antigen_no);
            if (!s.empty())
                result += fmt::format("{:{}c}{} {} {}\n{}", ' ', config.indent_,  vacc.type(), vacc.name(), entry.style.fill, s);
        }
    }
    return result;

} // Vaccines::report

// ----------------------------------------------------------------------

std::vector<size_t> Vaccines::indices() const
{
    std::vector<size_t> ind;
    for (const auto& entry: mEntries) {
        if (*entry.style.shown) {
            if (const auto* vacc = mVaccinesOfChart[entry.vaccines_of_chart_index].for_passage_type(entry.passage_type, entry.antigen_no); vacc)
                ind.push_back(vacc->chart_antigen_index);
        }
    }
    return ind;

} // Vaccines::indices

// ----------------------------------------------------------------------

std::vector<size_t> Vaccines::indices(const VaccineMatchData& aMatchData) const
{
    std::vector<std::pair<size_t, hidb::Vaccines::PassageType>> ind_passage;
    for (const auto& entry: mEntries) {
        if (entry.match(mVaccinesOfChart, aMatchData)) {
            if (const auto* vacc = mVaccinesOfChart[entry.vaccines_of_chart_index].for_passage_type(entry.passage_type, aMatchData.no() /* entry.antigen_no */); vacc)
                ind_passage.emplace_back(vacc->chart_antigen_index, entry.passage_type);
        }
    }

    const auto to_index = [](const auto& en) { return en.first; };
    if (aMatchData.passage() == "cell-egg") {
        const auto is_cell = [](const auto& en) { return en.second == hidb::Vaccines::Cell; };
        if (ranges::any_of(ind_passage, is_cell))
            return ind_passage | ranges::views::filter(is_cell) | ranges::views::transform(to_index) | ranges::to_vector;
        else
            return ind_passage | ranges::views::transform(to_index) | ranges::to_vector;
    }
    else if (aMatchData.passage() == "egg-cell") {
        const auto is_egg = [](const auto& en) { return en.second == hidb::Vaccines::Egg; };
        if (ranges::any_of(ind_passage, is_egg))
            return ind_passage | ranges::views::filter(is_egg) | ranges::views::transform(to_index) | ranges::to_vector;
        else
            return ind_passage | ranges::views::transform(to_index) | ranges::to_vector;
    }
    else
        return ind_passage | ranges::views::transform(to_index) | ranges::to_vector;

} // Vaccines::indices

// ----------------------------------------------------------------------

void Vaccines::plot(ChartDraw& aChartDraw) const
{
    for (const auto& entry: mEntries) {
        if (*entry.style.shown) {
            if (const auto* vacc = mVaccinesOfChart[entry.vaccines_of_chart_index].for_passage_type(entry.passage_type, entry.antigen_no); vacc)
                aChartDraw.modify(vacc->chart_antigen_index, entry.style, PointDrawingOrder::Raise);
        }
    }

} // Vaccines::plot

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p10/procedures/hwp/io/p10_io_lib.H $         */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2019,2020                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p10_io_lib.H
/// @brief Common IO functions and constants
///-----------------------------------------------------------------------------
/// *HW HW Maintainer: Chris Steffen <cwsteffen@us.ibm.com>
/// *HW FW Maintainer: Ilya Smirnov <ismirno@us.ibm.com>
/// *HW Consumed by  : HB
///-----------------------------------------------------------------------------

#include <fapi2.H>
#include <vector>

#ifndef _P10_IO_LIB__
#define _P10_IO_LIB__

//------------------------------------------------------------------------------
// Consts
//------------------------------------------------------------------------------
static const int P10_IO_LIB_NUMBER_OF_IOHS_LANES = 18;
static const int P10_IO_LIB_50G_IOHS_LANES[] = { 0, 2, 4, 6, 8, 9, 11, 15, 17 };

static const int P10_IO_LIB_NUMBER_OF_OMI_LANES = 8;
static const int P10_IO_LIB_NUMBER_OF_OMIC_LANES = 2 * P10_IO_LIB_NUMBER_OF_OMI_LANES;

static const int P10_IO_LIB_NUMBER_OF_IOHS_THREADS = 2;
static const int P10_IO_LIB_NUMBER_OF_OMIC_THREADS = 2;
static const int P10_IO_LIB_NUMBER_OF_THREADS = P10_IO_LIB_NUMBER_OF_IOHS_THREADS + P10_IO_LIB_NUMBER_OF_OMIC_THREADS;

//------------------------------------------------------------------------------
// Functions
//------------------------------------------------------------------------------
/// @brief Determines the thread number for the given iohs target
/// @param[in] i_iohs_target    IOHS target to get thread id for
/// @param[out] o_thread        The thread id for this target
/// @return FAPI_RC_SUCCESS if arguments are valid
fapi2::ReturnCode p10_io_get_iohs_thread(
    const fapi2::Target<fapi2::TARGET_TYPE_IOHS>& i_iohs_target,
    int& o_thread)
{
    fapi2::ATTR_CHIP_UNIT_POS_Type l_iohs_num;
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_iohs_target, l_iohs_num),
             "Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
    o_thread = l_iohs_num % P10_IO_LIB_NUMBER_OF_IOHS_THREADS;
fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Determines the thread number for the given omic target
/// @param[in] i_omic_target    OMIC target to get thread id for
/// @param[out] o_thread        The thread id for this target
/// @return FAPI_RC_SUCCESS if arguments are valid
fapi2::ReturnCode p10_io_get_omic_thread(
    const fapi2::Target<fapi2::TARGET_TYPE_OMIC>& i_omic_target,
    int& o_thread)
{
    fapi2::ATTR_CHIP_UNIT_POS_Type l_omic_num;
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_omic_target, l_omic_num),
             "Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
    o_thread = l_omic_num % P10_IO_LIB_NUMBER_OF_OMIC_THREADS;
    //omic threads start after iohc threads
    o_thread += P10_IO_LIB_NUMBER_OF_IOHS_THREADS;
fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Determines which lanes are enabled for an IOHS target
/// @param[in] i_iohs_target    IOHS target to get lanes for
/// @param[out] o_lanes         The configured lanes
/// @return FAPI_RC_SUCCESS if arguments are valid
fapi2::ReturnCode p10_io_get_iohs_lanes(
    const fapi2::Target<fapi2::TARGET_TYPE_IOHS>& i_iohs_target,
    std::vector<int>& o_lanes)
{
    fapi2::ATTR_IOHS_LINK_TRAIN_Type l_link_train;
    fapi2::ATTR_LINK_SPEED_Type l_link_speed;

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IOHS_LINK_TRAIN, i_iohs_target, l_link_train),
             "Error from FAPI_ATTR_GET (ATTR_IOHS_LINK_TRAIN)");
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_LINK_SPEED, i_iohs_target, l_link_speed),
             "Error from FAPI_ATTR_GET (ATTR_LINK_SPEED)");

    if (l_link_speed == fapi2::ENUM_ATTR_LINK_SPEED_50G)
    {
        for (int l_lane = 0; l_lane < P10_IO_LIB_NUMBER_OF_IOHS_LANES; l_lane++)
        {
            o_lanes.push_back(P10_IO_LIB_50G_IOHS_LANES[l_lane]);
        }
    }
    else
    {
        int l_start_bit = 0;
        int l_end_bit = 0;

        if (l_link_train == fapi2::ENUM_ATTR_IOHS_LINK_TRAIN_ODD_ONLY)
        {
            l_start_bit = P10_IO_LIB_NUMBER_OF_IOHS_LANES / 2;
            l_end_bit = P10_IO_LIB_NUMBER_OF_IOHS_LANES;
        }
        else if (l_link_train == fapi2::ENUM_ATTR_IOHS_LINK_TRAIN_EVEN_ONLY)
        {
            l_end_bit = P10_IO_LIB_NUMBER_OF_IOHS_LANES / 2;
        }
        else if (l_link_train == fapi2::ENUM_ATTR_IOHS_LINK_TRAIN_BOTH)
        {
            l_end_bit = P10_IO_LIB_NUMBER_OF_IOHS_LANES;
        }

        for (int l_lane = l_start_bit; l_lane < l_end_bit; l_lane++)
        {
            o_lanes.push_back(l_lane);
        }

    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Determines which lanes are enabled for an OMIC target
/// @param[in] i_omic_target    OMIC target to get lanes for
/// @param[out] o_lanes         The configured lanes
/// @return FAPI_RC_SUCCESS if arguments are valid
fapi2::ReturnCode p10_io_get_omic_lanes(
    const fapi2::Target<fapi2::TARGET_TYPE_OMIC>& i_omic_target,
    std::vector<int>& o_lanes)
{
    auto l_omi_targets = i_omic_target.getChildren<fapi2::TARGET_TYPE_OMI>();

    for (auto l_omi_target : l_omi_targets)
    {
        fapi2::ATTR_CHIP_UNIT_POS_Type l_omi_num;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_omi_target, l_omi_num),
                 "Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
        l_omi_num = l_omi_num % 2;

        for (int l_lane = l_omi_num * 8; l_lane < (l_omi_num + 1) * 8; l_lane++)
        {
            o_lanes.push_back(l_lane);
        }
    }

fapi_try_exit:
    return fapi2::current_err;
}

#endif
<commit_msg>Fix array out-of-bounds access in p10_io_lib.H<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p10/procedures/hwp/io/p10_io_lib.H $         */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2019,2020                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p10_io_lib.H
/// @brief Common IO functions and constants
///-----------------------------------------------------------------------------
/// *HW HW Maintainer: Chris Steffen <cwsteffen@us.ibm.com>
/// *HW FW Maintainer: Ilya Smirnov <ismirno@us.ibm.com>
/// *HW Consumed by  : HB
///-----------------------------------------------------------------------------

#include <fapi2.H>
#include <vector>
#include <utils.H>

#ifndef _P10_IO_LIB__
#define _P10_IO_LIB__

//------------------------------------------------------------------------------
// Consts
//------------------------------------------------------------------------------
static const int P10_IO_LIB_NUMBER_OF_IOHS_LANES = 18;
static const int P10_IO_LIB_50G_IOHS_LANES[] = { 0, 2, 4, 6, 8, 9, 11, 15, 17 };

static const int P10_IO_LIB_NUMBER_OF_OMI_LANES = 8;
static const int P10_IO_LIB_NUMBER_OF_OMIC_LANES = 2 * P10_IO_LIB_NUMBER_OF_OMI_LANES;

static const int P10_IO_LIB_NUMBER_OF_IOHS_THREADS = 2;
static const int P10_IO_LIB_NUMBER_OF_OMIC_THREADS = 2;
static const int P10_IO_LIB_NUMBER_OF_THREADS = P10_IO_LIB_NUMBER_OF_IOHS_THREADS + P10_IO_LIB_NUMBER_OF_OMIC_THREADS;

//------------------------------------------------------------------------------
// Functions
//------------------------------------------------------------------------------
/// @brief Determines the thread number for the given iohs target
/// @param[in] i_iohs_target    IOHS target to get thread id for
/// @param[out] o_thread        The thread id for this target
/// @return FAPI_RC_SUCCESS if arguments are valid
fapi2::ReturnCode p10_io_get_iohs_thread(
    const fapi2::Target<fapi2::TARGET_TYPE_IOHS>& i_iohs_target,
    int& o_thread)
{
    fapi2::ATTR_CHIP_UNIT_POS_Type l_iohs_num;
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_iohs_target, l_iohs_num),
             "Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
    o_thread = l_iohs_num % P10_IO_LIB_NUMBER_OF_IOHS_THREADS;
fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Determines the thread number for the given omic target
/// @param[in] i_omic_target    OMIC target to get thread id for
/// @param[out] o_thread        The thread id for this target
/// @return FAPI_RC_SUCCESS if arguments are valid
fapi2::ReturnCode p10_io_get_omic_thread(
    const fapi2::Target<fapi2::TARGET_TYPE_OMIC>& i_omic_target,
    int& o_thread)
{
    fapi2::ATTR_CHIP_UNIT_POS_Type l_omic_num;
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_omic_target, l_omic_num),
             "Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
    o_thread = l_omic_num % P10_IO_LIB_NUMBER_OF_OMIC_THREADS;
    //omic threads start after iohc threads
    o_thread += P10_IO_LIB_NUMBER_OF_IOHS_THREADS;
fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Determines which lanes are enabled for an IOHS target
/// @param[in] i_iohs_target    IOHS target to get lanes for
/// @param[out] o_lanes         The configured lanes
/// @return FAPI_RC_SUCCESS if arguments are valid
fapi2::ReturnCode p10_io_get_iohs_lanes(
    const fapi2::Target<fapi2::TARGET_TYPE_IOHS>& i_iohs_target,
    std::vector<int>& o_lanes)
{
    fapi2::ATTR_IOHS_LINK_TRAIN_Type l_link_train;
    fapi2::ATTR_LINK_SPEED_Type l_link_speed;

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IOHS_LINK_TRAIN, i_iohs_target, l_link_train),
             "Error from FAPI_ATTR_GET (ATTR_IOHS_LINK_TRAIN)");
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_LINK_SPEED, i_iohs_target, l_link_speed),
             "Error from FAPI_ATTR_GET (ATTR_LINK_SPEED)");

    if (l_link_speed == fapi2::ENUM_ATTR_LINK_SPEED_50G)
    {
        for (size_t l_lane = 0; l_lane < ARRAY_SIZE(P10_IO_LIB_50G_IOHS_LANES); l_lane++)
        {
            o_lanes.push_back(P10_IO_LIB_50G_IOHS_LANES[l_lane]);
        }
    }
    else
    {
        int l_start_bit = 0;
        int l_end_bit = 0;

        if (l_link_train == fapi2::ENUM_ATTR_IOHS_LINK_TRAIN_ODD_ONLY)
        {
            l_start_bit = P10_IO_LIB_NUMBER_OF_IOHS_LANES / 2;
            l_end_bit = P10_IO_LIB_NUMBER_OF_IOHS_LANES;
        }
        else if (l_link_train == fapi2::ENUM_ATTR_IOHS_LINK_TRAIN_EVEN_ONLY)
        {
            l_end_bit = P10_IO_LIB_NUMBER_OF_IOHS_LANES / 2;
        }
        else if (l_link_train == fapi2::ENUM_ATTR_IOHS_LINK_TRAIN_BOTH)
        {
            l_end_bit = P10_IO_LIB_NUMBER_OF_IOHS_LANES;
        }

        for (int l_lane = l_start_bit; l_lane < l_end_bit; l_lane++)
        {
            o_lanes.push_back(l_lane);
        }

    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Determines which lanes are enabled for an OMIC target
/// @param[in] i_omic_target    OMIC target to get lanes for
/// @param[out] o_lanes         The configured lanes
/// @return FAPI_RC_SUCCESS if arguments are valid
fapi2::ReturnCode p10_io_get_omic_lanes(
    const fapi2::Target<fapi2::TARGET_TYPE_OMIC>& i_omic_target,
    std::vector<int>& o_lanes)
{
    auto l_omi_targets = i_omic_target.getChildren<fapi2::TARGET_TYPE_OMI>();

    for (auto l_omi_target : l_omi_targets)
    {
        fapi2::ATTR_CHIP_UNIT_POS_Type l_omi_num;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_omi_target, l_omi_num),
                 "Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
        l_omi_num = l_omi_num % 2;

        for (int l_lane = l_omi_num * 8; l_lane < (l_omi_num + 1) * 8; l_lane++)
        {
            o_lanes.push_back(l_lane);
        }
    }

fapi_try_exit:
    return fapi2::current_err;
}

#endif
<|endoftext|>


<commit_before><commit_msg>Add and support Effective formula kernel<commit_after><|endoftext|>


<commit_before>/*
    Copyright (C) 2000 by Jerry A. Segler, Jr. Based on csFont
    Major improvements by Andrew Zabolotny, <bit@eltech.ru>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <stdlib.h>
#include "cssysdef.h"
#include "iutil/plugin.h"
#include "iutil/eventh.h"
#include "iutil/comp.h"
#include "iutil/objreg.h"
#include "ivaria/reporter.h"
#include "csutil/csvector.h"
#include "fontplex.h"

CS_IMPLEMENT_PLUGIN

SCF_IMPLEMENT_IBASE (csFontServerMultiplexor)
  SCF_IMPLEMENTS_INTERFACE (iFontServer)
  SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iComponent)
SCF_IMPLEMENT_IBASE_END

SCF_IMPLEMENT_EMBEDDED_IBASE (csFontServerMultiplexor::eiComponent)
  SCF_IMPLEMENTS_INTERFACE (iComponent)
SCF_IMPLEMENT_EMBEDDED_IBASE_END

SCF_IMPLEMENT_FACTORY (csFontServerMultiplexor)

SCF_EXPORT_CLASS_TABLE (fontplex)
  SCF_EXPORT_CLASS_DEP (csFontServerMultiplexor,
    "crystalspace.font.server.multiplexor",
    "Crystal Space font server multiplexor",
    "crystalspace.font.server.")
SCF_EXPORT_CLASS_TABLE_END

csFontServerMultiplexor::csFontServerMultiplexor (iBase *pParent)
{
  SCF_CONSTRUCT_IBASE (pParent);
  SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent);
}

csFontServerMultiplexor::~csFontServerMultiplexor ()
{
}

bool csFontServerMultiplexor::Initialize (iObjectRegistry *object_reg)
{
  // Query the auxiliary font servers in turn
  char tag [20];
  int idx;
  for (idx = 1; ; idx++)
  {
    sprintf (tag, "FontServer.%d", idx);
    iBase* b = CS_QUERY_REGISTRY_TAG (object_reg, tag);
    if (!b) break;
    iFontServer* fs = SCF_QUERY_INTERFACE (b, iFontServer);
    fontservers.Push (fs);
    b->DecRef ();
  }
  if (!fontservers.Length ())
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_WARNING,
        "crystalspace.font.fontplex",
        "Font server multiplexor: WARNING, no slave font servers found!");
  }
  return true;
}

iFont *csFontServerMultiplexor::LoadFont (const char *filename)
{
  int i;
  for (i = 0; i < fontservers.Length (); i++)
  {
    iFont *font = fontservers.Get (i)->LoadFont (filename);
    if (font) return font;
  }
  return NULL;
}

int csFontServerMultiplexor::GetFontCount ()
{
  int i, count = 0;
  for (i = 0; i < fontservers.Length (); i++)
    count += fontservers.Get (i)->GetFontCount ();
  return count;
}

iFont *csFontServerMultiplexor::GetFont (int iIndex)
{
  int i;
  for (i = 0; i < fontservers.Length (); i++)
  {
    int count = fontservers.Get (i)->GetFontCount ();
    if (iIndex < count)
      return fontservers.Get (iIndex)->GetFont (iIndex);
    iIndex -= count;
  }
  return NULL;
}
<commit_msg>fontplex now breaks loading of font servers after 2 consecutive failures (instead after the first failure)<commit_after>/*
    Copyright (C) 2000 by Jerry A. Segler, Jr. Based on csFont
    Major improvements by Andrew Zabolotny, <bit@eltech.ru>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <stdlib.h>
#include "cssysdef.h"
#include "iutil/plugin.h"
#include "iutil/eventh.h"
#include "iutil/comp.h"
#include "iutil/objreg.h"
#include "ivaria/reporter.h"
#include "csutil/csvector.h"
#include "fontplex.h"

CS_IMPLEMENT_PLUGIN

SCF_IMPLEMENT_IBASE (csFontServerMultiplexor)
  SCF_IMPLEMENTS_INTERFACE (iFontServer)
  SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iComponent)
SCF_IMPLEMENT_IBASE_END

SCF_IMPLEMENT_EMBEDDED_IBASE (csFontServerMultiplexor::eiComponent)
  SCF_IMPLEMENTS_INTERFACE (iComponent)
SCF_IMPLEMENT_EMBEDDED_IBASE_END

SCF_IMPLEMENT_FACTORY (csFontServerMultiplexor)

SCF_EXPORT_CLASS_TABLE (fontplex)
  SCF_EXPORT_CLASS_DEP (csFontServerMultiplexor,
    "crystalspace.font.server.multiplexor",
    "Crystal Space font server multiplexor",
    "crystalspace.font.server.")
SCF_EXPORT_CLASS_TABLE_END

csFontServerMultiplexor::csFontServerMultiplexor (iBase *pParent)
{
  SCF_CONSTRUCT_IBASE (pParent);
  SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent);
}

csFontServerMultiplexor::~csFontServerMultiplexor ()
{
}

bool csFontServerMultiplexor::Initialize (iObjectRegistry *object_reg)
{
  // Query the auxiliary font servers in turn
  char tag [20];
  int idx;
  int errorcount = 0;
  for (idx = 1; ; idx++)
  {
    sprintf (tag, "FontServer.%d", idx);
    iBase* b = CS_QUERY_REGISTRY_TAG (object_reg, tag);
    if (!b)
    {
      // in cases where just one entry in the server list doesn't work
      // but later ones would those are loaded, too
      errorcount++;
      if (errorcount == 2) break;
    }
    else
    {
      errorcount = 0;
      iFontServer* fs = SCF_QUERY_INTERFACE (b, iFontServer);
      fontservers.Push (fs);
      b->DecRef ();
    }
  }
  if (!fontservers.Length ())
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_WARNING,
        "crystalspace.font.fontplex",
        "Font server multiplexor: WARNING, no slave font servers found!");
  }
  return true;
}

iFont *csFontServerMultiplexor::LoadFont (const char *filename)
{
  int i;
  for (i = 0; i < fontservers.Length (); i++)
  {
    iFont *font = fontservers.Get (i)->LoadFont (filename);
    if (font) return font;
  }
  return NULL;
}

int csFontServerMultiplexor::GetFontCount ()
{
  int i, count = 0;
  for (i = 0; i < fontservers.Length (); i++)
    count += fontservers.Get (i)->GetFontCount ();
  return count;
}

iFont *csFontServerMultiplexor::GetFont (int iIndex)
{
  int i;
  for (i = 0; i < fontservers.Length (); i++)
  {
    int count = fontservers.Get (i)->GetFontCount ();
    if (iIndex < count)
      return fontservers.Get (iIndex)->GetFont (iIndex);
    iIndex -= count;
  }
  return NULL;
}
<|endoftext|>


<commit_before>/****************************************************************************
 * Copyright (c) 2012-2017 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 ****************************************************************************/
/*!
 * \file   ViewTestCudaHelpers_def.hpp
 * \author Stuart Slattery
 * \brief  tstView.cpp cuda test helpers
 */
//---------------------------------------------------------------------------//

#ifndef DTK_VIEWTESTCUDAHELPERS_DEF_HPP
#define DTK_VIEWTESTCUDAHELPERS_DEF_HPP

#include <cuda_runtime.h>

namespace ViewTestCudaHelpers
{

//---------------------------------------------------------------------------//
// 1d fill kernel.
template <class Scalar>
__global__ void fill1dKernel( DataTransferKit::View<Scalar> view,
                              const int dim1 )
{
    int idx = threadIdx.x + blockIdx.x * blockDim.x;
    if ( idx < dim1 )
    {
        assert( idx < view.size() );
        view[idx] = idx;
    }
}

//---------------------------------------------------------------------------//
// 2d fill kernel
template <class Scalar>
__global__ void fill2dKernel( Scalar *data, const int dim1, const int dim2 )
{
    int idx = threadIdx.x + blockIdx.x * blockDim.x;
    if ( idx < dim1 )
    {
        for ( int j = 0; j < dim2; ++j )
        {
            int index = j * dim1 + idx;
            assert( index < dim1 * dim2 );
            data[index] = idx + j;
        }
    }
}

//---------------------------------------------------------------------------//
// 3d fill kernel
template <class Scalar>
__global__ void fill3dKernel( DataTransferKit::View<Scalar> view,
                              const int dim1, const int dim2, const int dim3 )
{
    int idx = threadIdx.x + blockIdx.x * blockDim.x;
    if ( idx < dim1 )
    {
        for ( int j = 0; j < dim2; ++j )
        {
            for ( int k = 0; k < dim3; ++k )
            {
                int index = k * dim1 * dim2 + j * dim1 + idx;
                assert( index < view.size() );
                view[index] = idx + j + k;
            }
        }
    }
}

//---------------------------------------------------------------------------//
// Fill function.
template <class Scalar>
void fillViewCuda( DataTransferKit::View<Scalar> dtk_view,
                   const std::vector<unsigned> &dims )
{
    int num_dims = dims.size();

    int block_size = 64;
    int num_blocks = dims[0] / block_size;
    if ( dims[0] % block_size > 0 )
        ++num_blocks;

    if ( 1 == num_dims )
    {
        fill1dKernel<Scalar><<<num_blocks, block_size>>>( dtk_view, dims[0] );
    }
    else if ( 2 == num_dims )
    {
        fill2dKernel<Scalar><<<num_blocks, block_size>>>( dtk_view.data(),
                                                          dims[0], dims[1] );
    }
    else if ( 3 == num_dims )
    {
        fill3dKernel<Scalar><<<num_blocks, block_size>>>( dtk_view, dims[0],
                                                          dims[1], dims[2] );
    }

    // NOTE: Synchronization is required because kernels are launched
    // asynchronously. This is the equivalent of calling Kokkos::fence() after
    // a kernel. If these kernels were executed on a specific stream, only
    // that stream would need to be synchronized.
    cudaDeviceSynchronize();
}

//---------------------------------------------------------------------------//

} // end namespace ViewTestCudaHelpers

#endif // end DTK_VIEWTESTCUDAHELPERS_DEF_HPP

//---------------------------------------------------------------------------//
// end ViewTestCudaHelpers_def.hpp
//---------------------------------------------------------------------------//
<commit_msg>Apply new version of clang-format to source code<commit_after>/****************************************************************************
 * Copyright (c) 2012-2017 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 ****************************************************************************/
/*!
 * \file   ViewTestCudaHelpers_def.hpp
 * \author Stuart Slattery
 * \brief  tstView.cpp cuda test helpers
 */
//---------------------------------------------------------------------------//

#ifndef DTK_VIEWTESTCUDAHELPERS_DEF_HPP
#define DTK_VIEWTESTCUDAHELPERS_DEF_HPP

#include <cuda_runtime.h>

namespace ViewTestCudaHelpers
{

//---------------------------------------------------------------------------//
// 1d fill kernel.
template <class Scalar>
__global__ void fill1dKernel( DataTransferKit::View<Scalar> view,
                              const int dim1 )
{
    int idx = threadIdx.x + blockIdx.x * blockDim.x;
    if ( idx < dim1 )
    {
        assert( idx < view.size() );
        view[idx] = idx;
    }
}

//---------------------------------------------------------------------------//
// 2d fill kernel
template <class Scalar>
__global__ void fill2dKernel( Scalar *data, const int dim1, const int dim2 )
{
    int idx = threadIdx.x + blockIdx.x * blockDim.x;
    if ( idx < dim1 )
    {
        for ( int j = 0; j < dim2; ++j )
        {
            int index = j * dim1 + idx;
            assert( index < dim1 * dim2 );
            data[index] = idx + j;
        }
    }
}

//---------------------------------------------------------------------------//
// 3d fill kernel
template <class Scalar>
__global__ void fill3dKernel( DataTransferKit::View<Scalar> view,
                              const int dim1, const int dim2, const int dim3 )
{
    int idx = threadIdx.x + blockIdx.x * blockDim.x;
    if ( idx < dim1 )
    {
        for ( int j = 0; j < dim2; ++j )
        {
            for ( int k = 0; k < dim3; ++k )
            {
                int index = k * dim1 * dim2 + j * dim1 + idx;
                assert( index < view.size() );
                view[index] = idx + j + k;
            }
        }
    }
}

//---------------------------------------------------------------------------//
// Fill function.
template <class Scalar>
void fillViewCuda( DataTransferKit::View<Scalar> dtk_view,
                   const std::vector<unsigned> &dims )
{
    int num_dims = dims.size();

    int block_size = 64;
    int num_blocks = dims[0] / block_size;
    if ( dims[0] % block_size > 0 )
        ++num_blocks;

    if ( 1 == num_dims )
    {
        fill1dKernel<Scalar><<<num_blocks, block_size>>>( dtk_view, dims[0] );
    }
    else if ( 2 == num_dims )
    {
        fill2dKernel<Scalar>
            <<<num_blocks, block_size>>>( dtk_view.data(), dims[0], dims[1] );
    }
    else if ( 3 == num_dims )
    {
        fill3dKernel<Scalar>
            <<<num_blocks, block_size>>>( dtk_view, dims[0], dims[1], dims[2] );
    }

    // NOTE: Synchronization is required because kernels are launched
    // asynchronously. This is the equivalent of calling Kokkos::fence() after
    // a kernel. If these kernels were executed on a specific stream, only
    // that stream would need to be synchronized.
    cudaDeviceSynchronize();
}

//---------------------------------------------------------------------------//

} // end namespace ViewTestCudaHelpers

#endif // end DTK_VIEWTESTCUDAHELPERS_DEF_HPP

//---------------------------------------------------------------------------//
// end ViewTestCudaHelpers_def.hpp
//---------------------------------------------------------------------------//
<|endoftext|>


<commit_before>#pragma once

#include <iostream>

#include "binary.hxx"
#include "bitnode.hxx"

namespace despairagus {
	namespace bitwisetrie {
		using std::cout;
		using std::ostream;

		template <typename A>
		class bitwisetrie final {
			template<typename B>
			using conref = const B &;

			using bitA = std::bitset<sizeof(A) << 3>;
			using byte = unsigned char;
			using bit = bool;

		public:
			explicit bitwisetrie(void) = delete;

		private:
		};
	}
}<commit_msg>added size of max depth added root node<commit_after>#pragma once

#include <iostream>

#include "binary.hxx"
#include "bitnode.hxx"

namespace despairagus {
	namespace bitwisetrie {
		using std::cout;
		using std::ostream;

		template <typename A>
		class bitwisetrie final {
			template<typename B>
			using conref = const B &;

			using bitA = std::bitset<sizeof(A) << 3>;
			using byte = unsigned char;
			using bit = bool;

			constexpr static const size_t limit{sizeof(A) << 3};

		public:
			explicit bitwisetrie(void) = delete;

		private:
			bitnode<A>* root;
		};
	}
}<|endoftext|>