<commit_before>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"
#include "World.h"
#include "Action.h"
#include "FPSRoleLocal.h"
#include "StarControl.h"
#include "RayControl.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//设置角色初始位置。以门处作为原点，三维坐标系vec3是向量
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);
	g_pSysControl->SetMouseGrab(1);

	m_pStarControl = new CStarControl();
	m_pRayControl = new CRayControl();

	return 1;
}

int CGameProcess::ShutDown()			//关闭游戏进程
{
	delete m_pRole;
	delete m_pSkillSystem;
	delete m_pCameraBase;
	delete m_pStarControl;
	delete m_pRayControl;

	DelAllListen();
	return 0;
}

int CGameProcess::Update()
{
	float ifps = g_Engine.pGame->GetIFps();

	if (g_Engine.pInput->IsKeyDown('1'))
	{
		CAction* pAction = m_pRole->OrceAction("attack02");
		if (pAction)
		{
			pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('2'))
	{
		CAction* pAction = m_pRole->OrceAction("skill01");
		if (pAction)
		{
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('3'))
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CRoleBase* pTarget = NULL;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 15.0f)
				{
					pTarget = m_vAIList[i];
					break;
				}
			}
			if (pTarget)
			{
				CVector<int> vTarget;
				vTarget.Append(pTarget->GetRoleID());
				pAction->SetupSkillBulletTarget(vTarget);
				m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('4'))//多发子弹
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
				{
					vTarget.Append(m_vAIList[i]->GetRoleID());
				}
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('5'))
	{
		CAction* pAction = m_pRole->OrceAction("skill03");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			pAction->SetupSkillTargetPoint(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('6'))
	{
		CAction* pAction = m_pRole->OrceAction("skill06");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vPos.Append(m_vAIList[i]->GetPosition());

			}
			pAction->SetupSkillTargetPoint(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('7'))
	{
		CAction* pAction = m_pRole->OrceAction("skill05");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vTarget.Append(m_vAIList[i]->GetRoleID());
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('8'))
	{
		CAction* pAction = m_pRole->OrceAction("skill07");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vPos.Append(m_vAIList[i]->GetPosition());
			}
			pAction->SetupSkillBulletPosition(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('9'))
	{
		CAction* pAction = m_pRole->OrceAction("skill08");
		if (pAction)
		{
			m_pRole->StopMove();
			pAction->SetupSkillBulletDirection(1);
		}

	}
	else if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC))
	{
		g_Engine.pApp->Exit();
	}
	if(g_Engine.pInput->IsLBDown())
	{
		vec3 p0,p1;
		BlueRay::GetPlayerMouseDirection(p0,p1);
		vec3 vRetPoint,vRetNormal;
		int nS = -1;
		g_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS);

		if(-1 != nS)
		{
			m_pRole->MoveToPath(vRetPoint);
		}
	}
	for(int i = 0;i < 20;i++)
	{
		if(!m_vAIList[i]->IsMoveing())
		{
			vec3 vPos = vec3(g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),1.1f);
			m_vAIList[i]->MoveToPath(vPos);
		}

		m_vAIList[i]->Update(ifps);
	}
	if (g_Engine.pInput->IsLBDown())	//shubiaozuojian
	{
		g_pSysControl->SetMouseGrab(1);
		m_pStarControl->Click();
	}
	if (g_Engine.pInput->IsKeyDown(CInput::KEY_ESC))
	{
		g_pSysControl->SetMouseGrab(0);
	}
	m_pCameraBase->SetMouseControls(g_pSysControl->GetMouseGrab());
	m_pCameraBase->Update(ifps);

	m_pRole->SetActorDirection(m_pCameraBase->GetViewDirection());
	m_pRole->UpdateActor(ifps);
	m_pCameraBase->SetPosition(m_pRole->GetActorPosition() + m_pRole->GetCameraOffset());

	vec3 x = m_pCameraBase->GetModelview().getRow3(0);
	vec3 y = m_pCameraBase->GetModelview().getRow3(1);
	vec3 z = m_pCameraBase->GetModelview().getRow3(2);

	mat4 r = mat4_identity;

	r.setColumn3(0, -x);	//
	r.setColumn3(1, z);		//
	r.setColumn3(2, y);		//

	return 0;
}

<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"
#include "World.h"
#include "Action.h"
#include "FPSRoleLocal.h"
#include "StarControl.h"
#include "RayControl.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//设置角色初始位置。以门处作为原点，三维坐标系vec3是向量
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);
	g_pSysControl->SetMouseGrab(1);

	m_pStarControl = new CStarControl();
	m_pRayControl = new CRayControl();

	return 1;
}

int CGameProcess::ShutDown()			//关闭游戏进程
{
	delete m_pRole;
	delete m_pSkillSystem;
	delete m_pCameraBase;
	delete m_pStarControl;
	delete m_pRayControl;

	DelAllListen();
	return 0;
}

int CGameProcess::Update()
{
	float ifps = g_Engine.pGame->GetIFps();

	if (g_Engine.pInput->IsKeyDown('1'))
	{
		CAction* pAction = m_pRole->OrceAction("attack02");
		if (pAction)
		{
			pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('2'))
	{
		CAction* pAction = m_pRole->OrceAction("skill01");
		if (pAction)
		{
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('3'))
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CRoleBase* pTarget = NULL;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 15.0f)
				{
					pTarget = m_vAIList[i];
					break;
				}
			}
			if (pTarget)
			{
				CVector<int> vTarget;
				vTarget.Append(pTarget->GetRoleID());
				pAction->SetupSkillBulletTarget(vTarget);
				m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('4'))//多发子弹
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
				{
					vTarget.Append(m_vAIList[i]->GetRoleID());
				}
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('5'))
	{
		CAction* pAction = m_pRole->OrceAction("skill03");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			pAction->SetupSkillTargetPoint(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('6'))
	{
		CAction* pAction = m_pRole->OrceAction("skill06");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vPos.Append(m_vAIList[i]->GetPosition());

			}
			pAction->SetupSkillTargetPoint(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('7'))
	{
		CAction* pAction = m_pRole->OrceAction("skill05");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vTarget.Append(m_vAIList[i]->GetRoleID());
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('8'))
	{
		CAction* pAction = m_pRole->OrceAction("skill07");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vPos.Append(m_vAIList[i]->GetPosition());
			}
			pAction->SetupSkillBulletPosition(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('9'))
	{
		CAction* pAction = m_pRole->OrceAction("skill08");
		if (pAction)
		{
			m_pRole->StopMove();
			pAction->SetupSkillBulletDirection(1);
		}

	}
	else if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC))
	{
		g_Engine.pApp->Exit();
	}
	if(g_Engine.pInput->IsLBDown())
	{
		vec3 p0,p1;
		BlueRay::GetPlayerMouseDirection(p0,p1);
		vec3 vRetPoint,vRetNormal;
		int nS = -1;
		g_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS);

		if(-1 != nS)
		{
			m_pRole->MoveToPath(vRetPoint);
		}
	}
	for(int i = 0;i < 20;i++)
	{
		if(!m_vAIList[i]->IsMoveing())
		{
			vec3 vPos = vec3(g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),1.1f);
			m_vAIList[i]->MoveToPath(vPos);
		}

		m_vAIList[i]->Update(ifps);
	}
	if (g_Engine.pInput->IsLBDown())	//shubiaozuojian
	{
		g_pSysControl->SetMouseGrab(1);
		m_pStarControl->Click();
	}
	if (g_Engine.pInput->IsKeyDown(CInput::KEY_ESC))
	{
		g_pSysControl->SetMouseGrab(0);
	}
	m_pCameraBase->SetMouseControls(g_pSysControl->GetMouseGrab());
	m_pCameraBase->Update(ifps);

	m_pRole->SetActorDirection(m_pCameraBase->GetViewDirection());
	m_pRole->UpdateActor(ifps);
	m_pCameraBase->SetPosition(m_pRole->GetActorPosition() + m_pRole->GetCameraOffset());

	vec3 x = m_pCameraBase->GetModelview().getRow3(0);
	vec3 y = m_pCameraBase->GetModelview().getRow3(1);
	vec3 z = m_pCameraBase->GetModelview().getRow3(2);

	mat4 r = mat4_identity;

	r.setColumn3(0, -x);	//
	r.setColumn3(1, z);		//
	r.setColumn3(2, y);		//

	m_pRole->UpdateTransform(r);

	return 0;
}

<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2004 by Sashmit Bhaduri                                 *
 *   smt@vfemail.net                                                       *
 *                                                                         *
 *   Licensed under GPL.                                                   *
 ***************************************************************************/

#include "articleviewer.h"
#include "feed.h"

#include <kapplication.h>
#include <kglobalsettings.h>
#include <kstandarddirs.h>
#include <klocale.h>

#include <qdatetime.h>
#include <qvaluelist.h>

using namespace Akregator;

// from kmail::headerstyle.cpp
static inline QString directionOf(const QString &str)
{
    return str.isRightToLeft() ? "rtl" : "ltr" ;
}

int pointsToPixel(const QPaintDeviceMetrics &metrics, int pointSize)
{
    return ( pointSize * metrics.logicalDpiY() + 36 ) / 72 ;
}

ArticleViewer::ArticleViewer(QWidget *parent, const char *name)
    : KHTMLPart(parent, name), m_metrics(widget())
{
    generateCSS();
    // to be on a safe side
    setJScriptEnabled(false);
    setJavaEnabled(false);
    setMetaRefreshEnabled(false);
    setPluginsEnabled(false);
    setDNDEnabled(false);
    setAutoloadImages(true);
    setStatusMessagesEnabled(true);
}

void ArticleViewer::openDefault()
{
    openURL( ::locate( "data", "akregatorpart/welcome.html" ) );
}

void ArticleViewer::generateCSS()
{
    const QColorGroup & cg = QApplication::palette().active();
	m_htmlHead=QString("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
						"<title></title>");
    m_htmlHead += QString (
    "\n")
    .arg(KGlobalSettings::generalFont().family()).
    arg(QString::number( pointsToPixel( m_metrics, KGlobalSettings::generalFont().pointSize()))+"px").
    arg(cg.text().name()).
    arg(cg.base().name()).
    arg(cg.link().name()).
    arg(cg.background().name()).
    arg(cg.text().name()).
    arg(cg.highlight().name()).
    arg(cg.highlightedText().name());
}

void ArticleViewer::reload()
{
    generateCSS();
    begin( KURL( "file:"+KGlobal::dirs()->saveLocation("cache", "akregator/Media/") ) );
    write(m_htmlHead + m_currentText);
    end();
}

QString ArticleViewer::formatArticle(Feed *f, MyArticle a)
{
    QString text;
    text = QString("
\n").arg(QApplication::reverseLayout() ? "rtl" : "ltr");

    if (!a.title().isEmpty())
    {
        text += QString("
\n").arg(directionOf(a.title()));
        text += a.title()+"
\n";
    }
    if (a.pubDate().isValid())
    {
        text += QString("").arg(directionOf(i18n("Date")));
        text += QString ("%1:").arg(i18n("Date"));
        text += "";
        text += KGlobal::locale()->formatDateTime(a.pubDate(), false, false)+"\n"; // TODO: might need RTL?
    }
    text += "
\n"; // end headerbox

    if (f && !f->image.isNull())
        text += QString("htmlUrl+"\">title()+".png"+"\">\n");

    text += "
"+a.description();
    if (a.link().isValid())
    {
        if (!a.description().isNull())
            text += "
\n";
        text += "" + i18n( "Full Story" ) + "";
        if (!a.description().isNull())
            text += "
\n";
    }
    text += "
";
    return text;

}

void ArticleViewer::show(Feed *f)
{
    QString art, text;

    begin( KURL( "file:"+KGlobal::dirs()->saveLocation("cache", "akregator/Media/") ) );
    write(m_htmlHead);

    ArticleSequence::iterator it;
    for ( it = f->articles.begin(); it != f->articles.end(); ++it )
    {
        art=formatArticle(0, *it); // we set f to 0 to not show feed image
        text += art;
        write(art);
    }

    m_currentText = text + "";
    write("");
    end();
}

void ArticleViewer::show(Feed *f, MyArticle a)
{
    begin( KURL( "file:"+KGlobal::dirs()->saveLocation("cache", "akregator/Media/") ) );

    QString text=formatArticle(f, a) +"";
    m_currentText=text;

    write(m_htmlHead + text);
    end();
}

#include "articleviewer.moc"
<commit_msg>pretty (um, I think) up combined mode<commit_after>/***************************************************************************
 *   Copyright (C) 2004 by Sashmit Bhaduri                                 *
 *   smt@vfemail.net                                                       *
 *                                                                         *
 *   Licensed under GPL.                                                   *
 ***************************************************************************/

#include "articleviewer.h"
#include "feed.h"

#include <kapplication.h>
#include <kglobalsettings.h>
#include <kstandarddirs.h>
#include <klocale.h>

#include <qdatetime.h>
#include <qvaluelist.h>

using namespace Akregator;

// from kmail::headerstyle.cpp
static inline QString directionOf(const QString &str)
{
    return str.isRightToLeft() ? "rtl" : "ltr" ;
}

int pointsToPixel(const QPaintDeviceMetrics &metrics, int pointSize)
{
    return ( pointSize * metrics.logicalDpiY() + 36 ) / 72 ;
}

ArticleViewer::ArticleViewer(QWidget *parent, const char *name)
    : KHTMLPart(parent, name), m_metrics(widget())
{
    generateCSS();
    // to be on a safe side
    setJScriptEnabled(false);
    setJavaEnabled(false);
    setMetaRefreshEnabled(false);
    setPluginsEnabled(false);
    setDNDEnabled(false);
    setAutoloadImages(true);
    setStatusMessagesEnabled(true);
}

void ArticleViewer::openDefault()
{
    openURL( ::locate( "data", "akregatorpart/welcome.html" ) );
}

void ArticleViewer::generateCSS()
{
    const QColorGroup & cg = QApplication::palette().active();
	m_htmlHead=QString("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
						"<title></title>");
    m_htmlHead += QString (
    "\n")
    .arg(KGlobalSettings::generalFont().family()).
    arg(QString::number( pointsToPixel( m_metrics, KGlobalSettings::generalFont().pointSize()))+"px").
    arg(cg.text().name()).
    arg(cg.base().name()).
    arg(cg.link().name()).
    arg(cg.background().name()).
    arg(cg.text().name()).
    arg(cg.highlight().name()).
    arg(cg.highlightedText().name());
}

void ArticleViewer::reload()
{
    generateCSS();
    begin( KURL( "file:"+KGlobal::dirs()->saveLocation("cache", "akregator/Media/") ) );
    write(m_htmlHead + m_currentText);
    end();
}

QString ArticleViewer::formatArticle(Feed *f, MyArticle a)
{
    QString text;
    text = QString("
\n").arg(QApplication::reverseLayout() ? "rtl" : "ltr");

    if (!a.title().isEmpty())
    {
        text += QString("
\n").arg(directionOf(a.title()));
        text += a.title()+"
\n";
    }
    if (a.pubDate().isValid())
    {
        text += QString("").arg(directionOf(i18n("Date")));
        text += QString ("%1:").arg(i18n("Date"));
        text += "";
        text += KGlobal::locale()->formatDateTime(a.pubDate(), false, false)+"\n"; // TODO: might need RTL?
    }
    text += "
\n"; // end headerbox

    if (f && !f->image.isNull())
        text += QString("htmlUrl+"\">title()+".png"+"\">\n");

    text += "
"+a.description();
    if (a.link().isValid())
    {
        if (!a.description().isNull())
            text += "
\n";
        text += "" + i18n( "Full Story" ) + "";
        if (!a.description().isNull())
            text += "
\n";
    }
    text += "
";
    return text;

}

void ArticleViewer::show(Feed *f)
{
    QString art, text;

    begin( KURL( "file:"+KGlobal::dirs()->saveLocation("cache", "akregator/Media/") ) );
    write(m_htmlHead);

    ArticleSequence::iterator it;
    for ( it = f->articles.begin(); it != f->articles.end(); ++it )
    {
        // we set f to 0 to not show feed image
        art="

"+formatArticle(0, *it)+"

";
        text += art;
        write(art);
    }

    m_currentText = text + "";
    write("");
    end();
}

void ArticleViewer::show(Feed *f, MyArticle a)
{
    begin( KURL( "file:"+KGlobal::dirs()->saveLocation("cache", "akregator/Media/") ) );

    QString text=formatArticle(f, a) +"";
    m_currentText=text;

    write(m_htmlHead + text);
    end();
}

#include "articleviewer.moc"
<|endoftext|>


<commit_before><commit_msg>Update android/ringqt/project/main.cpp<commit_after><|endoftext|>


<commit_before>#include "stdafx.h"

int _tmain(int, _TCHAR*[])
{
	FreeConsole();
	RegisterHotKey(nullptr, 1, MOD_CONTROL | MOD_ALT, VK_CANCEL);
	MSG msg = {0};
	while (GetMessage(&msg, nullptr, 0, 0) != NULL)
	{
		if (msg.message == WM_HOTKEY)
		{
			auto hDevInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_DISPLAY, REGSTR_KEY_PCIENUM, nullptr, DIGCF_PRESENT | DIGCF_ALLCLASSES);
			SP_DEVINFO_DATA deviceInfoData;
			deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
			for (DWORD i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &deviceInfoData); i++)
			{
				SP_PROPCHANGE_PARAMS params;
				params.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
				params.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
				params.Scope = DICS_FLAG_GLOBAL ;
				params.StateChange = DICS_DISABLE;
				SetupDiSetClassInstallParams(hDevInfo, &deviceInfoData, &params.ClassInstallHeader, sizeof(params));
				SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, hDevInfo, &deviceInfoData);
				params.StateChange = DICS_ENABLE;
				SetupDiSetClassInstallParams(hDevInfo, &deviceInfoData, &params.ClassInstallHeader, sizeof(params));
				SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, hDevInfo, &deviceInfoData);
			}
		}
	}

	return EXIT_SUCCESS;
}
<commit_msg>Minor fixes and formatting changes<commit_after>#include "stdafx.h"

int _tmain(int, _TCHAR*[])
{
    FreeConsole();
    RegisterHotKey(nullptr, NULL, MOD_CONTROL | MOD_ALT, VK_CANCEL);
    MSG msg = { nullptr };
    while (GetMessage(&msg, nullptr, 0, 0))
    {
        if (msg.message == WM_HOTKEY)
        {
            auto hDevInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_DISPLAY, REGSTR_KEY_PCIENUM, nullptr, DIGCF_PRESENT | DIGCF_ALLCLASSES);
            SP_DEVINFO_DATA deviceInfoData;
            deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
            for (DWORD i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &deviceInfoData); i++)
            {
                SP_PROPCHANGE_PARAMS params;
                params.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
                params.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
                params.Scope = DICS_FLAG_GLOBAL;
                params.StateChange = DICS_DISABLE;
                SetupDiSetClassInstallParams(hDevInfo, &deviceInfoData, &params.ClassInstallHeader, sizeof(params));
                SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, hDevInfo, &deviceInfoData);
                params.StateChange = DICS_ENABLE;
                SetupDiSetClassInstallParams(hDevInfo, &deviceInfoData, &params.ClassInstallHeader, sizeof(params));
                SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, hDevInfo, &deviceInfoData);
            }
        }
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 * $Log$
 * Revision 1.10  2003/12/17 00:18:38  cargilld
 * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.
 *
 * Revision 1.9  2003/10/01 16:32:41  neilg
 * improve handling of out of memory conditions, bug #23415.  Thanks to David Cargill.
 *
 * Revision 1.8  2003/10/01 00:27:12  knoaman
 * Performance: call a static method to check the validity of URI instead of
 * creating/deleting local objects.
 *
 * Revision 1.7  2003/09/30 21:31:30  peiyongz
 * Implementation of Serialization/Deserialization
 *
 * Revision 1.6  2003/05/18 14:02:07  knoaman
 * Memory manager implementation: pass per instance manager.
 *
 * Revision 1.5  2003/05/16 06:01:57  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.4  2003/05/15 18:53:26  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.3  2002/12/18 14:17:55  gareth
 * Fix to bug #13438. When you eant a vector that calls delete[] on its members you should use RefArrayVectorOf.
 *
 * Revision 1.2  2002/11/04 14:53:27  tng
 * C++ Namespace Support.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:40  peiyongz
 * sane_include
 *
 * Revision 1.10  2001/10/10 14:18:26  peiyongz
 * no message
 *
 * Revision 1.9  2001/10/09 20:53:58  peiyongz
 * init(): take 1 arg.
 *
 * Revision 1.8  2001/10/02 18:59:29  peiyongz
 * Invalid_Facet_Tag to display the tag name
 *
 * Revision 1.7  2001/09/24 15:33:15  peiyongz
 * DTV Reorganization: virtual methods moved to *.cpp
 *
 * Revision 1.6  2001/09/19 18:49:17  peiyongz
 * DTV reorganization: move inline to class declaration to avoid inline
 * function interdependency.
 *
 * Revision 1.5  2001/09/18 20:38:03  peiyongz
 * DTV reorganization: inherit from AbstractStringValidator.
 *
 * Revision 1.4  2001/08/21 18:42:53  peiyongz
 * Bugzilla# 2816: cleanUp() declared with external linkage and called
 *                          before defined as inline
 *
 * Revision 1.3  2001/08/14 22:11:56  peiyongz
 * new exception message added
 *
 * Revision 1.2  2001/08/10 16:21:19  peiyongz
 * use XMLUri instead of XMLURL
 *
 * Revision 1.1  2001/08/01 18:49:16  peiyongz
 * AnyRUIDatatypeValidator
 *
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/datatype/AnyURIDatatypeValidator.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeFacetException.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>

XERCES_CPP_NAMESPACE_BEGIN

//
//http://www.template.com
//
static const XMLCh BASE_URI[] =
{
    chLatin_h, chLatin_t, chLatin_t, chLatin_p,
    chColon, chForwardSlash, chForwardSlash,
    chLatin_w, chLatin_w, chLatin_w, chPeriod,
    chLatin_t, chLatin_e, chLatin_m, chLatin_p, chLatin_l,
    chLatin_a, chLatin_t, chLatin_e, chPeriod,
    chLatin_c, chLatin_o, chLatin_m, chNull
};

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
AnyURIDatatypeValidator::AnyURIDatatypeValidator(MemoryManager* const manager)
:AbstractStringValidator(0, 0, 0, DatatypeValidator::AnyURI, manager)
{}

AnyURIDatatypeValidator::~AnyURIDatatypeValidator()
{
}

AnyURIDatatypeValidator::AnyURIDatatypeValidator(
                          DatatypeValidator*            const baseValidator
                        , RefHashTableOf<KVStringPair>* const facets
                        , RefArrayVectorOf<XMLCh>*      const enums
                        , const int                           finalSet
                        , MemoryManager* const manager)
:AbstractStringValidator(baseValidator, facets, finalSet, DatatypeValidator::AnyURI, manager)
{
    try
    {
        init(enums, manager);
    }
    catch(const OutOfMemoryException&)
    {
        throw;
    }
    catch (...)
    {
        throw;
    }
}

DatatypeValidator* AnyURIDatatypeValidator::newInstance(
                                      RefHashTableOf<KVStringPair>* const facets
                                    , RefArrayVectorOf<XMLCh>*           const enums
                                    , const int                           finalSet
                                    , MemoryManager* const manager)
{
    return (DatatypeValidator*) new (manager) AnyURIDatatypeValidator(this, facets, enums, finalSet, manager);
}

// ---------------------------------------------------------------------------
//  Utilities
// ---------------------------------------------------------------------------

void AnyURIDatatypeValidator::checkValueSpace(const XMLCh* const content
                                              , MemoryManager* const manager)
{

    // check 3.2.17.c0 must: URI (rfc 2396/2723)
    try
    {
        // Support for relative URLs
        // According to Java 1.1: URLs may also be specified with a
        // String and the URL object that it is related to.
        //
        if (XMLString::stringLen(content))
        {
              if (!XMLUri::isValidURI(true, content))
                ThrowXMLwithMemMgr1(InvalidDatatypeValueException
                    , XMLExcepts::VALUE_URI_Malformed
                    , content
                    , manager);
        }
    }
    catch(const OutOfMemoryException&)
    {
        throw;
    }
    catch (...)
    {
        ThrowXMLwithMemMgr1(InvalidDatatypeValueException
                , XMLExcepts::VALUE_URI_Malformed
                , content
                , manager);
    }

}

/***
 * Support for Serialization/De-serialization
 ***/

IMPL_XSERIALIZABLE_TOCREATE(AnyURIDatatypeValidator)

void AnyURIDatatypeValidator::serialize(XSerializeEngine& serEng)
{
    AbstractStringValidator::serialize(serEng);
}

XERCES_CPP_NAMESPACE_END

/**
  * End of file AnyURIDatatypeValidator.cpp
  */
<commit_msg>remove unused static member<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001-2004 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 * $Log$
 * Revision 1.11  2004/01/12 23:02:18  neilg
 * remove unused static member
 *
 * Revision 1.10  2003/12/17 00:18:38  cargilld
 * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.
 *
 * Revision 1.9  2003/10/01 16:32:41  neilg
 * improve handling of out of memory conditions, bug #23415.  Thanks to David Cargill.
 *
 * Revision 1.8  2003/10/01 00:27:12  knoaman
 * Performance: call a static method to check the validity of URI instead of
 * creating/deleting local objects.
 *
 * Revision 1.7  2003/09/30 21:31:30  peiyongz
 * Implementation of Serialization/Deserialization
 *
 * Revision 1.6  2003/05/18 14:02:07  knoaman
 * Memory manager implementation: pass per instance manager.
 *
 * Revision 1.5  2003/05/16 06:01:57  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.4  2003/05/15 18:53:26  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.3  2002/12/18 14:17:55  gareth
 * Fix to bug #13438. When you eant a vector that calls delete[] on its members you should use RefArrayVectorOf.
 *
 * Revision 1.2  2002/11/04 14:53:27  tng
 * C++ Namespace Support.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:40  peiyongz
 * sane_include
 *
 * Revision 1.10  2001/10/10 14:18:26  peiyongz
 * no message
 *
 * Revision 1.9  2001/10/09 20:53:58  peiyongz
 * init(): take 1 arg.
 *
 * Revision 1.8  2001/10/02 18:59:29  peiyongz
 * Invalid_Facet_Tag to display the tag name
 *
 * Revision 1.7  2001/09/24 15:33:15  peiyongz
 * DTV Reorganization: virtual methods moved to *.cpp
 *
 * Revision 1.6  2001/09/19 18:49:17  peiyongz
 * DTV reorganization: move inline to class declaration to avoid inline
 * function interdependency.
 *
 * Revision 1.5  2001/09/18 20:38:03  peiyongz
 * DTV reorganization: inherit from AbstractStringValidator.
 *
 * Revision 1.4  2001/08/21 18:42:53  peiyongz
 * Bugzilla# 2816: cleanUp() declared with external linkage and called
 *                          before defined as inline
 *
 * Revision 1.3  2001/08/14 22:11:56  peiyongz
 * new exception message added
 *
 * Revision 1.2  2001/08/10 16:21:19  peiyongz
 * use XMLUri instead of XMLURL
 *
 * Revision 1.1  2001/08/01 18:49:16  peiyongz
 * AnyRUIDatatypeValidator
 *
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/datatype/AnyURIDatatypeValidator.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeFacetException.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
AnyURIDatatypeValidator::AnyURIDatatypeValidator(MemoryManager* const manager)
:AbstractStringValidator(0, 0, 0, DatatypeValidator::AnyURI, manager)
{}

AnyURIDatatypeValidator::~AnyURIDatatypeValidator()
{
}

AnyURIDatatypeValidator::AnyURIDatatypeValidator(
                          DatatypeValidator*            const baseValidator
                        , RefHashTableOf<KVStringPair>* const facets
                        , RefArrayVectorOf<XMLCh>*      const enums
                        , const int                           finalSet
                        , MemoryManager* const manager)
:AbstractStringValidator(baseValidator, facets, finalSet, DatatypeValidator::AnyURI, manager)
{
    try
    {
        init(enums, manager);
    }
    catch(const OutOfMemoryException&)
    {
        throw;
    }
    catch (...)
    {
        throw;
    }
}

DatatypeValidator* AnyURIDatatypeValidator::newInstance(
                                      RefHashTableOf<KVStringPair>* const facets
                                    , RefArrayVectorOf<XMLCh>*           const enums
                                    , const int                           finalSet
                                    , MemoryManager* const manager)
{
    return (DatatypeValidator*) new (manager) AnyURIDatatypeValidator(this, facets, enums, finalSet, manager);
}

// ---------------------------------------------------------------------------
//  Utilities
// ---------------------------------------------------------------------------

void AnyURIDatatypeValidator::checkValueSpace(const XMLCh* const content
                                              , MemoryManager* const manager)
{

    // check 3.2.17.c0 must: URI (rfc 2396/2723)
    try
    {
        // Support for relative URLs
        // According to Java 1.1: URLs may also be specified with a
        // String and the URL object that it is related to.
        //
        if (XMLString::stringLen(content))
        {
              if (!XMLUri::isValidURI(true, content))
                ThrowXMLwithMemMgr1(InvalidDatatypeValueException
                    , XMLExcepts::VALUE_URI_Malformed
                    , content
                    , manager);
        }
    }
    catch(const OutOfMemoryException&)
    {
        throw;
    }
    catch (...)
    {
        ThrowXMLwithMemMgr1(InvalidDatatypeValueException
                , XMLExcepts::VALUE_URI_Malformed
                , content
                , manager);
    }

}

/***
 * Support for Serialization/De-serialization
 ***/

IMPL_XSERIALIZABLE_TOCREATE(AnyURIDatatypeValidator)

void AnyURIDatatypeValidator::serialize(XSerializeEngine& serEng)
{
    AbstractStringValidator::serialize(serEng);
}

XERCES_CPP_NAMESPACE_END

/**
  * End of file AnyURIDatatypeValidator.cpp
  */
<|endoftext|>


<commit_before>#include "skp_local_application.h"
#include "skpLog.h"
#include "gmock/gmock.h"
//#include <gperftools/profiler.h>
//#include <gperftools/heap-profiler.h>

SkpLog *g_log = skp_null;

int main(int argc, char *argv[])
{
    //ProfilerStart(NULL);
    //HeapProfilerStart(NULL);

    g_log = new SkpLog("", "main_server_", Skp::LOG_ERROR, /*Skp::LOG_TO_FILE | */Skp::LOG_TO_STDERR,skp_true,0,1024 * 1024 *100, skp_true);

//    testing::InitGoogleMock(&argc, argv);
//    return RUN_ALL_TESTS();

    SkpLocalApplication app(argc, argv);
    int res = app.exec();

    //ProfilerStop();
    //HeapProfilerStop();
    return res;
}
<commit_msg>update<commit_after>#include "skp_local_application.h"
#include "skpLog.h"
#include "gmock/gmock.h"
//#include <gperftools/profiler.h>
//#include <gperftools/heap-profiler.h>

SkpLog *g_log = skp_null;

int main(int argc, char *argv[])
{
    //ProfilerStart(NULL);
    //HeapProfilerStart(NULL);

    g_log = new SkpLog("", "main_server_", Skp::LOG_ERROR, /*Skp::LOG_TO_FILE | */Skp::LOG_TO_STDERR,skp_true,0,1024 * 1024 *100, skp_true);

//    testing::InitGoogleMock(&argc, argv);
//    return RUN_ALL_TESTS();

    SkpLocalApplication app(argc, argv);
    int res = app.exec();

    //ProfilerStop();
    //HeapProfilerStop();
    return res;
}
<|endoftext|>


<commit_before>/**
 * Copyright 2013 Truphone
 */
#include "SpyCommand.h"

#include <QString>
#include <QList>
#include <QObject>
#include <QSignalSpy>

#include "Utils.h"
#include "Connection.h"

namespace truphone
{
namespace test
{
namespace cascades
{
    /*!
     * \brief The Spy class is a wrapper for the Signal Spy
     *
     * @since test-cascades 1.0.0
     */
    class Spy : public QObject
    {
    public:
        /*!
         * \brief Spy Create a new spy
         *
         * \param name The name of the spy
         * \param object The object name to spy on
         * \param signal The signal on @c object to spy on
         * \param parent The parent object
         *
         * @since test-cascades 1.0.0
         */
        Spy(const QString &name,
            const QString &object,
            const QString &signal,
            QObject * parent = 0)
            : QObject(parent),
              mySpyName(name),
              myObject(object),
              mySignal(signal),
              spy(NULL),
              spyObject(NULL)
        {
        }

        /*!
         * \brief ~Spy Destructor
         *
         * @since test-cascades 1.0.0
         */
        virtual ~Spy()
        {
            this->kill();
        }

        /*!
         * \brief connect Create and connect the SignalSpy to the object
         *
         * \return True if the connection worked
         *
         * @since test-cascades 1.0.0
         */
        bool connect()
        {
            bool ret = true;
            if (this->spy)
            {
                delete this->spy;
            }
            if (this->myObject.isNull() or this->myObject.isEmpty())
            {
                ret = false;
            }
            if (ret)
            {
                this->spyObject = Utils::findObject(this->myObject);
            }
            if (not this->spyObject)
            {
                ret = false;
            }
            if (this->mySignal.isNull() or this->mySignal.isEmpty())
            {
                ret = false;
            }
            if (ret)
            {
                const char * const signalName = this->mySignal.toUtf8().constData();
                this->spy = new QSignalSpy(this->spyObject, signalName);
                ret = this->spy->isValid();
            }
            return ret;
        }

        /*!
         * \brief count The number of signals that were fired once spying started
         *
         * \param valid Pointer to a boolean valid that states if the return count
         * can be trusted. If the spy is broken or not connected then @c valid
         * will be set to false.
         *
         * \return The number of times the assigned signal has fired
         *
         * @since test-cascades 1.0.0
         */
        int count(bool * valid = 0) const
        {
            int c = 0;

            if (this->spy and this->spy->isValid())
            {
                c = this->spy->count();
                if (valid)
                {
                    *valid = true;
                }
            }

            return c;
        }

        /*!
         * \brief kill Kills the spy and removes it from the object
         *
         * @since test-cascades 1.0.0
         */
        void kill()
        {
            if (this->spy)
            {
                delete this->spy;
            }
            this->spy = NULL;
        }

    protected:
    private:
        /*!
         * \brief mySpyName The name of the spy
         */
        const QString mySpyName;
        /*!
         * \brief myObject The object to spy on
         */
        const QString myObject;
        /*!
         * \brief mySignal The signal to spy on
         */
        const QString mySignal;
        /*!
         * \brief spy Our spy
         */
        QSignalSpy * spy;
        /*!
         * \brief spyObject The object to spy on
         */
        QObject * spyObject;
    };

    /*!
     * \brief The SpyCommandPrivate class is used to maintain all the spies
     *
     * @since test-cascades 1.0.0
     */
    class SpyCommandPrivate : public QObject
    {
    public:
        /*!
         * \brief SpyCommandPrivate Constructor
         *
         * \param parent The parent object
         *
         * @since test-cascades 1.0.0
         */
        explicit SpyCommandPrivate(QObject * parent = 0)
            : QObject(parent)
        {
        }
        /*!
         * \brief ~SpyCommandPrivate Destructor.
         *
         * @since test-cascades 1.0.0
         */
        virtual ~SpyCommandPrivate()
        {
            Q_FOREACH(Spy * spy, this->spies)
            {
                if (spy)
                {
                    spy->kill();
                    delete spy;
                }
            }
            this->spies.clear();
        }
        /*!
         * \brief addSpy Add a new spy
         *
         * \param name The name of the spy
         * \param object The object to spy on
         * \param signal The signal to spy on
         * \return @c true if the signal is created and connected ok
         *
         * @since test-cascades 1.0.0
         */
        bool addSpy(const QString &name,
                    const QString &object,
                    const QString &signal)
        {
            bool ret = false;
            Spy * const spy = new Spy(name, object, signal, this);
            if (spy)
            {
                ret = spy->connect();
                if (ret)
                {
                    this->spies.insert(name, spy);
                }
                else
                {
                    delete spy;
                }
            }

            return ret;
        }
        /*!
         * \brief getSpy Return a spy
         *
         * \param name The name of the spy to get
         * \return The spy instance
         *
         * @since test-cascades 1.0.0
         */
        Spy * getSpy(const QString &name)
        {
            return this->spies[name];
        }
        /*!
         * \brief removeSpy Remove, disconnet and delete as spy
         *
         * \param name The name of the spy
         * \return @c true if the spy was found and deleted
         *
         * @since test-cascades 1.0.0
         */
        bool removeSpy(const QString &name)
        {
            bool found = false;
            Spy * const spy = this->spies[name];
            if (spy)
            {
                spy->kill();
                delete spy;
                this->spies.remove(name);
                found = true;
            }
            return found;
        }

    protected:
    private:
        /*!
         * \brief spies All the spies.
         */
        QHash<QString, Spy*> spies;
    };

    const QString SpyCommand::CMD_NAME = "spy";
    SpyCommandPrivate * SpyCommand::spyPrivateSingleton;

    SpyCommand::SpyCommand(Connection * const socket,
                           QObject* parent)
        : Command(parent),
          client(socket),
          spyPrivate(((spyPrivateSingleton == NULL)
                      ? spyPrivateSingleton = new SpyCommandPrivate() : spyPrivateSingleton))
    {
    }

    SpyCommand::~SpyCommand()
    {
    }

    bool SpyCommand::executeCommand(QStringList * const arguments)
    {
        bool ret = false;

        if (arguments->size() >= 2)
        {
            const QString command = arguments->first();
            arguments->removeFirst();
            if (command == "create")
            {
                if (arguments->size() == 3)
                {
                    const QString name = arguments->first();
                    arguments->removeFirst();;
                    const QString object = arguments->first();
                    arguments->removeFirst();
                    const QString signal = arguments->first();
                    arguments->removeFirst();
                    ret = this->spyPrivate->addSpy(name,
                                                   object,
                                                   "2" + signal);
                    if (not ret)
                    {
                        this->client->write
                                (tr("ERROR: Couldn't connect to the signal on that object")
                                 + "\r\n");
                    }
                }
                else
                {
                    this->client->write(tr("ERROR: The create command needs a name," \
                                        "object and signal") + "\r\n");
                }
            }
            else if (command == "count")
            {
                if (arguments->size() >=2 )
                {
                    const QString name = arguments->first();
                    arguments->removeFirst();;
                    bool countOk = false;
                    const int expectedCount = arguments->first().toInt(&countOk);
                    if (not countOk)
                    {
                        this->client->write(tr("ERROR: The expected count number isn't a number")
                                            + "\r\n");
                    }
                    else
                    {
                        const Spy * const spy = this->spyPrivate->getSpy(name);
                        if (not spy)
                        {
                            this->client->write(tr("ERROR: Couldn't find a spy with that name")
                                                + "\r\n");
                        }
                        else
                        {
                            bool valid = false;
                            const int count = spy->count(&valid);
                            if (not valid)
                            {
                                this->client->write(tr("ERROR: Couldn't get the signal " \
                                                    "count for the spy") + "\r\n");
                            }
                            else
                            {
                                if (count == expectedCount)
                                {
                                    ret = true;
                                }
                                else
                                {
                                    this->client->write(tr("ERROR: The spy's signal " \
                                        "count doesn't match the expected count") + "\r\n");
                                }
                            }
                        }
                    }
                }
                else
                {
                    this->client->write(tr("ERROR: Count needs at least two parameter") + "\r\n");
                }
            }
            else if (command == "kill")
            {
                const QString name = arguments->first();
                if (this->spyPrivate->removeSpy(name))
                {
                    ret = true;
                }
                else
                {
                    this->client->write(tr("ERROR: Can't delete an unknown spy") + "\r\n");
                }
            }
            else
            {
                this->client->write(tr("ERROR: Unknown spy command") + "\r\n");
            }
        }
        else
        {
            this->client->write(tr("ERROR: Spy commands need at least two parameters") + "\r\n");
        }

        return ret;
    }

    void SpyCommand::showHelp()
    {
        this->client->write(tr("> spy create <spyName> <object> <signal> - create a new Spy")
                            + "\r\n");
        this->client->write(tr("> spy count <spyName> <count> - check that the signal count for " \
                            "a spy is <count>") + "\r\n");
        this->client->write(tr("> spy kill <spyName> - remove a spy") + "\r\n");
    }
}  // namespace cascades
}  // namespace test
}  // namespace truphone
<commit_msg>Spy command now accepts parameters.<commit_after>/**
 * Copyright 2013 Truphone
 */
#include "SpyCommand.h"

#include <QString>
#include <QList>
#include <QObject>
#include <QSignalSpy>

#include "Utils.h"
#include "Connection.h"

namespace truphone
{
namespace test
{
namespace cascades
{
    /*!
     * \brief The Spy class is a wrapper for the Signal Spy
     *
     * @since test-cascades 1.0.0
     */
    class Spy : public QObject
    {
    public:
        /*!
         * \brief Spy Create a new spy
         *
         * \param name The name of the spy
         * \param object The object name to spy on
         * \param signal The signal on @c object to spy on
         * \param parent The parent object
         *
         * @since test-cascades 1.0.0
         */
        Spy(const QString &name,
            const QString &object,
            const QString &signal,
            QObject * parent = 0)
            : QObject(parent),
              mySpyName(name),
              myObject(object),
              mySignal(signal),
              spy(NULL),
              spyObject(NULL)
        {
        }

        /*!
         * \brief ~Spy Destructor
         *
         * @since test-cascades 1.0.0
         */
        virtual ~Spy()
        {
            this->kill();
        }

        /*!
         * \brief connect Create and connect the SignalSpy to the object
         *
         * \return True if the connection worked
         *
         * @since test-cascades 1.0.0
         */
        bool connect()
        {
            bool ret = true;
            if (this->spy)
            {
                delete this->spy;
            }
            if (this->myObject.isNull() or this->myObject.isEmpty())
            {
                ret = false;
            }
            if (ret)
            {
                this->spyObject = Utils::findObject(this->myObject);
            }
            if (not this->spyObject)
            {
                ret = false;
            }
            if (this->mySignal.isNull() or this->mySignal.isEmpty())
            {
                ret = false;
            }
            if (ret)
            {
                const char * const signalName = this->mySignal.toUtf8().constData();
                this->spy = new QSignalSpy(this->spyObject, signalName);
                ret = this->spy->isValid();
            }
            return ret;
        }

        /*!
         * \brief count The number of signals that were fired once spying started
         *
         * \param valid Pointer to a boolean valid that states if the return count
         * can be trusted. If the spy is broken or not connected then @c valid
         * will be set to false.
         *
         * \return The number of times the assigned signal has fired
         *
         * @since test-cascades 1.0.0
         */
        int count(bool * valid = 0) const
        {
            int c = 0;

            if (this->spy and this->spy->isValid())
            {
                c = this->spy->count();
                if (valid)
                {
                    *valid = true;
                }
            }

            return c;
        }

        /*!
         * \brief kill Kills the spy and removes it from the object
         *
         * @since test-cascades 1.0.0
         */
        void kill()
        {
            if (this->spy)
            {
                delete this->spy;
            }
            this->spy = NULL;
        }

    protected:
    private:
        /*!
         * \brief mySpyName The name of the spy
         */
        const QString mySpyName;
        /*!
         * \brief myObject The object to spy on
         */
        const QString myObject;
        /*!
         * \brief mySignal The signal to spy on
         */
        const QString mySignal;
        /*!
         * \brief spy Our spy
         */
        QSignalSpy * spy;
        /*!
         * \brief spyObject The object to spy on
         */
        QObject * spyObject;
    };

    /*!
     * \brief The SpyCommandPrivate class is used to maintain all the spies
     *
     * @since test-cascades 1.0.0
     */
    class SpyCommandPrivate : public QObject
    {
    public:
        /*!
         * \brief SpyCommandPrivate Constructor
         *
         * \param parent The parent object
         *
         * @since test-cascades 1.0.0
         */
        explicit SpyCommandPrivate(QObject * parent = 0)
            : QObject(parent)
        {
        }
        /*!
         * \brief ~SpyCommandPrivate Destructor.
         *
         * @since test-cascades 1.0.0
         */
        virtual ~SpyCommandPrivate()
        {
            Q_FOREACH(Spy * spy, this->spies)
            {
                if (spy)
                {
                    spy->kill();
                    delete spy;
                }
            }
            this->spies.clear();
        }
        /*!
         * \brief addSpy Add a new spy
         *
         * \param name The name of the spy
         * \param object The object to spy on
         * \param signal The signal to spy on
         * \return @c true if the signal is created and connected ok
         *
         * @since test-cascades 1.0.0
         */
        bool addSpy(const QString &name,
                    const QString &object,
                    const QString &signal)
        {
            bool ret = false;
            Spy * const spy = new Spy(name, object, signal, this);
            if (spy)
            {
                ret = spy->connect();
                if (ret)
                {
                    this->spies.insert(name, spy);
                }
                else
                {
                    delete spy;
                }
            }

            return ret;
        }
        /*!
         * \brief getSpy Return a spy
         *
         * \param name The name of the spy to get
         * \return The spy instance
         *
         * @since test-cascades 1.0.0
         */
        Spy * getSpy(const QString &name)
        {
            return this->spies[name];
        }
        /*!
         * \brief removeSpy Remove, disconnet and delete as spy
         *
         * \param name The name of the spy
         * \return @c true if the spy was found and deleted
         *
         * @since test-cascades 1.0.0
         */
        bool removeSpy(const QString &name)
        {
            bool found = false;
            Spy * const spy = this->spies[name];
            if (spy)
            {
                spy->kill();
                delete spy;
                this->spies.remove(name);
                found = true;
            }
            return found;
        }

    protected:
    private:
        /*!
         * \brief spies All the spies.
         */
        QHash<QString, Spy*> spies;
    };

    const QString SpyCommand::CMD_NAME = "spy";
    SpyCommandPrivate * SpyCommand::spyPrivateSingleton;

    SpyCommand::SpyCommand(Connection * const socket,
                           QObject* parent)
        : Command(parent),
          client(socket),
          spyPrivate(((spyPrivateSingleton == NULL)
                      ? spyPrivateSingleton = new SpyCommandPrivate() : spyPrivateSingleton))
    {
    }

    SpyCommand::~SpyCommand()
    {
    }

    bool SpyCommand::executeCommand(QStringList * const arguments)
    {
        bool ret = false;

        if (arguments->size() >= 2)
        {
            const QString command = arguments->first();
            arguments->removeFirst();
            if (command == "create")
            {
                if (arguments->size() >= 3)
                {
                    const QString name = arguments->first();
                    arguments->removeFirst();;
                    const QString object = arguments->first();
                    arguments->removeFirst();
                    const QString signal = arguments->join("");
                    arguments->removeFirst();
                    ret = this->spyPrivate->addSpy(name,
                                                   object,
                                                   "2" + signal);
                    if (not ret)
                    {
                        this->client->write
                                (tr("ERROR: Couldn't connect to the signal on that object")
                                 + "\r\n");
                    }
                }
                else
                {
                    this->client->write(tr("ERROR: The create command needs a name," \
                                        "object and signal") + "\r\n");
                }
            }
            else if (command == "count")
            {
                if (arguments->size() >=2 )
                {
                    const QString name = arguments->first();
                    arguments->removeFirst();;
                    bool countOk = false;
                    const int expectedCount = arguments->first().toInt(&countOk);
                    if (not countOk)
                    {
                        this->client->write(tr("ERROR: The expected count number isn't a number")
                                            + "\r\n");
                    }
                    else
                    {
                        const Spy * const spy = this->spyPrivate->getSpy(name);
                        if (not spy)
                        {
                            this->client->write(tr("ERROR: Couldn't find a spy with that name")
                                                + "\r\n");
                        }
                        else
                        {
                            bool valid = false;
                            const int count = spy->count(&valid);
                            if (not valid)
                            {
                                this->client->write(tr("ERROR: Couldn't get the signal " \
                                                    "count for the spy") + "\r\n");
                            }
                            else
                            {
                                if (count == expectedCount)
                                {
                                    ret = true;
                                }
                                else
                                {
                                    this->client->write(tr("ERROR: The spy's signal " \
                                        "count doesn't match the expected count") + "\r\n");
                                }
                            }
                        }
                    }
                }
                else
                {
                    this->client->write(tr("ERROR: Count needs at least two parameter") + "\r\n");
                }
            }
            else if (command == "kill")
            {
                const QString name = arguments->first();
                if (this->spyPrivate->removeSpy(name))
                {
                    ret = true;
                }
                else
                {
                    this->client->write(tr("ERROR: Can't delete an unknown spy") + "\r\n");
                }
            }
            else
            {
                this->client->write(tr("ERROR: Unknown spy command") + "\r\n");
            }
        }
        else
        {
            this->client->write(tr("ERROR: Spy commands need at least two parameters") + "\r\n");
        }

        return ret;
    }

    void SpyCommand::showHelp()
    {
        this->client->write(tr("> spy create <spyName> <object> <signal> - create a new Spy")
                            + "\r\n");
        this->client->write(tr("> spy count <spyName> <count> - check that the signal count for " \
                            "a spy is <count>") + "\r\n");
        this->client->write(tr("> spy kill <spyName> - remove a spy") + "\r\n");
    }
}  // namespace cascades
}  // namespace test
}  // namespace truphone
<|endoftext|>


<commit_before>#include <stan/math/prim.hpp>
#include <gtest/gtest.h>
#include <vector>

TEST(MathFunctionsPoissonBinomialLogProbs, check_scalar_y) {
  using stan::math::poisson_binomial_log_probs;
  using vec = Eigen::Matrix<double, Eigen::Dynamic, 1>;

  vec p(3, 1);
  p << 0.5, 0.2, 0.7;
  std::vector<double> vals{-2.12026, -0.84397, -0.967584, -2.65926};

  for (int i = 0; i < 4; i++) {
    auto x = poisson_binomial_log_probs(i, p);
    EXPECT_EQ(x.rows(), i + 1);
    EXPECT_EQ(x.cols(), 1);
    for (int j = 0; j <= i; ++j) {
      EXPECT_NEAR(vals[j], x(j), 0.001);
    }
  }
}

TEST(MathFunctionsPoissonBinomialLogProbs, check_vectorial_y) {
  using stan::math::poisson_binomial_log_probs;
  using vec = Eigen::Matrix<double, Eigen::Dynamic, 1>;

  vec p(3, 1);
  p << 0.5, 0.2, 0.7;
  std::vector<int> y{0, 1};
  auto x = poisson_binomial_log_probs(y, p);

  EXPECT_EQ(x.size(), 2);
  EXPECT_EQ(x[0].rows(), 1);
  EXPECT_EQ(x[0].cols(), 1);
  EXPECT_EQ(x[1].rows(), 2);
  EXPECT_EQ(x[1].cols(), 1);
}

TEST(MathFunctionsPoissonBinomialLogProbs, check_vectorial_y_vectorial_theta) {
  using stan::math::poisson_binomial_log_probs;
  using vec = Eigen::Matrix<double, Eigen::Dynamic, 1>;

  vec p(3, 1);
  p << 0.5, 0.2, 0.7;
  std::vector<int> y{0, 1};
  std::vector<vec> ps{p, p};
  auto x = poisson_binomial_log_probs(y, ps);

  EXPECT_EQ(x.size(), 2);
  EXPECT_EQ(x[0].rows(), 1);
  EXPECT_EQ(x[0].cols(), 1);
  EXPECT_EQ(x[1].rows(), 2);
  EXPECT_EQ(x[1].cols(), 1);
}<commit_msg>Cpplint again<commit_after>#include <stan/math/prim.hpp>
#include <gtest/gtest.h>
#include <vector>

TEST(MathFunctionsPoissonBinomialLogProbs, check_scalar_y) {
  using stan::math::poisson_binomial_log_probs;
  using vec = Eigen::Matrix<double, Eigen::Dynamic, 1>;

  vec p(3, 1);
  p << 0.5, 0.2, 0.7;
  std::vector<double> vals{-2.12026, -0.84397, -0.967584, -2.65926};

  for (int i = 0; i < 4; i++) {
    auto x = poisson_binomial_log_probs(i, p);
    EXPECT_EQ(x.rows(), i + 1);
    EXPECT_EQ(x.cols(), 1);
    for (int j = 0; j <= i; ++j) {
      EXPECT_NEAR(vals[j], x(j), 0.001);
    }
  }
}

TEST(MathFunctionsPoissonBinomialLogProbs, check_vectorial_y) {
  using stan::math::poisson_binomial_log_probs;
  using vec = Eigen::Matrix<double, Eigen::Dynamic, 1>;

  vec p(3, 1);
  p << 0.5, 0.2, 0.7;
  std::vector<int> y{0, 1};
  auto x = poisson_binomial_log_probs(y, p);

  EXPECT_EQ(x.size(), 2);
  EXPECT_EQ(x[0].rows(), 1);
  EXPECT_EQ(x[0].cols(), 1);
  EXPECT_EQ(x[1].rows(), 2);
  EXPECT_EQ(x[1].cols(), 1);
}

TEST(MathFunctionsPoissonBinomialLogProbs, check_vectorial_y_vectorial_theta) {
  using stan::math::poisson_binomial_log_probs;
  using vec = Eigen::Matrix<double, Eigen::Dynamic, 1>;

  vec p(3, 1);
  p << 0.5, 0.2, 0.7;
  std::vector<int> y{0, 1};
  std::vector<vec> ps{p, p};
  auto x = poisson_binomial_log_probs(y, ps);

  EXPECT_EQ(x.size(), 2);
  EXPECT_EQ(x[0].rows(), 1);
  EXPECT_EQ(x[0].cols(), 1);
  EXPECT_EQ(x[1].rows(), 2);
  EXPECT_EQ(x[1].cols(), 1);
}
<|endoftext|>


<commit_before>/*
* Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR
* IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

// Testcase Description: This test case checks whether hipStreamSynchronize() is taking
// lesser time after the Callback() function launched by hipStreamAddCallback() api.

/* HIT_START
 * BUILD: %t %s ../../test_common.cpp NVCC_OPTIONS --std=c++11
 * TEST: %t
 * HIT_END
 */

#include <stdio.h>
#include <chrono>
#include <atomic>
#include "hip/hip_runtime.h"
#include "test_common.h"

#ifdef __HIP_PLATFORM_AMD__
#define HIPRT_CB
#endif

#define SECONDS_TO_WAIT 2
#define TO_MICROSECONDS 1000000

hipStream_t mystream;
size_t N_elmts = 4096;
bool cbDone = false;
std::atomic<int> Data_mismatch{0};

__global__ void vector_square(float* C_d, float* A_d, size_t N_elmts) {
  size_t offset = (blockIdx.x * blockDim.x + threadIdx.x);
  size_t stride = blockDim.x * gridDim.x;

  for (size_t i = offset; i < N_elmts; i += stride) {
    C_d[i] = A_d[i] * A_d[i];
  }

  // Delay the thread 1
  if (offset == 1) {
    unsigned long long int wait_t = 3200000000, start = clock64(), cur;
    do {
      cur = clock64() - start;
    } while (cur < wait_t);
  }
}

float *A_h, *C_h;

static void HIPRT_CB Callback1(hipStream_t stream, hipError_t status,
                               void* userData) {
  // Validate the data
  for (size_t i = 0; i < N_elmts; i++) {
    if (C_h[i] != A_h[i] * A_h[i]) {
      Data_mismatch++;
    }
  }

  // Delay the callback completion
  std::this_thread::sleep_for (std::chrono::seconds(SECONDS_TO_WAIT));
  cbDone = true;
}

int main(int argc, char* argv[]) {
  float *A_d, *C_d;
  size_t Nbytes = N_elmts * sizeof(float);
  float tElapsed = 1.0f;

  A_h = (float*)malloc(Nbytes);
  HIPCHECK(A_h == 0 ? hipErrorOutOfMemory : hipSuccess);
  C_h = (float*)malloc(Nbytes);
  HIPCHECK(C_h == 0 ? hipErrorOutOfMemory : hipSuccess);

  // Fill with Phi + i
  for (size_t i = 0; i < N_elmts; i++) {
    A_h[i] = 1.618f + i;
  }

  HIPCHECK(hipMalloc(&A_d, Nbytes));
  HIPCHECK(hipMalloc(&C_d, Nbytes));

  HIPCHECK(hipStreamCreateWithFlags(&mystream, hipStreamNonBlocking));

  HIPCHECK(hipMemcpyAsync(A_d, A_h, Nbytes, hipMemcpyHostToDevice, mystream));

  const unsigned threadsPerBlock = 256;
  const unsigned blocks = (N_elmts + 255)/threadsPerBlock;

  hipLaunchKernelGGL((vector_square), dim3(blocks), dim3(threadsPerBlock), 0,
                      mystream, C_d, A_d, N_elmts);
  HIPCHECK(hipMemcpyAsync(C_h, C_d, Nbytes, hipMemcpyDeviceToHost, mystream));
  HIPCHECK(hipStreamAddCallback(mystream, Callback1, NULL, 0));

  // Wait untill Callback() function changes the cbDone value to true
  while (!cbDone) {
    std::this_thread::sleep_for (std::chrono::milliseconds(10));
  }

  // Since the callback is supposed to be called only after an implicit stream
  // synchronization, and the runtime cannot continue until the callback is done
  // hipStreamSynchronize call should not take much time.
  auto start = std::chrono::high_resolution_clock::now();
  HIPCHECK(hipStreamSynchronize(mystream));
  auto stop = std::chrono::high_resolution_clock::now();
  auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);

  HIPCHECK(hipStreamDestroy(mystream));
  HIPCHECK(hipFree(A_d));
  HIPCHECK(hipFree(C_d));
  free(A_h);
  free(C_h);

  if (Data_mismatch.load() != 0) {
    failed("Output from kernel execution is not as expected");
  }

  // HIP runtime cannot proceed further in the queue until callback completes
  // Stream synchronize should not have much task to do after callback
  // It should just be an extra empty marker wait
  // Therefore the hipStreamSynchronize() in the
  // main thread should hardly take any time to complete.

  if (duration.count() < 100) {
    passed();
  } else {
    failed("hipStreamSynchronize is taking more time than expected after Callback()");
  }
}
<commit_msg>SWDEV-346657 - increase time for random failure (#3025)<commit_after>/*
* Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR
* IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

// Testcase Description: This test case checks whether hipStreamSynchronize() is taking
// lesser time after the Callback() function launched by hipStreamAddCallback() api.

/* HIT_START
 * BUILD: %t %s ../../test_common.cpp NVCC_OPTIONS --std=c++11
 * TEST: %t
 * HIT_END
 */

#include <stdio.h>
#include <chrono>
#include <atomic>
#include "hip/hip_runtime.h"
#include "test_common.h"

#ifdef __HIP_PLATFORM_AMD__
#define HIPRT_CB
#endif

#define SECONDS_TO_WAIT 2
#define TO_MICROSECONDS 1000000

hipStream_t mystream;
size_t N_elmts = 4096;
bool cbDone = false;
std::atomic<int> Data_mismatch{0};

__global__ void vector_square(float* C_d, float* A_d, size_t N_elmts) {
  size_t offset = (blockIdx.x * blockDim.x + threadIdx.x);
  size_t stride = blockDim.x * gridDim.x;

  for (size_t i = offset; i < N_elmts; i += stride) {
    C_d[i] = A_d[i] * A_d[i];
  }

  // Delay the thread 1
  if (offset == 1) {
    unsigned long long int wait_t = 3200000000, start = clock64(), cur;
    do {
      cur = clock64() - start;
    } while (cur < wait_t);
  }
}

float *A_h, *C_h;

static void HIPRT_CB Callback1(hipStream_t stream, hipError_t status,
                               void* userData) {
  // Validate the data
  for (size_t i = 0; i < N_elmts; i++) {
    if (C_h[i] != A_h[i] * A_h[i]) {
      Data_mismatch++;
    }
  }

  // Delay the callback completion
  std::this_thread::sleep_for (std::chrono::seconds(SECONDS_TO_WAIT));
  cbDone = true;
}

int main(int argc, char* argv[]) {
  float *A_d, *C_d;
  size_t Nbytes = N_elmts * sizeof(float);
  float tElapsed = 1.0f;

  A_h = (float*)malloc(Nbytes);
  HIPCHECK(A_h == 0 ? hipErrorOutOfMemory : hipSuccess);
  C_h = (float*)malloc(Nbytes);
  HIPCHECK(C_h == 0 ? hipErrorOutOfMemory : hipSuccess);

  // Fill with Phi + i
  for (size_t i = 0; i < N_elmts; i++) {
    A_h[i] = 1.618f + i;
  }

  HIPCHECK(hipMalloc(&A_d, Nbytes));
  HIPCHECK(hipMalloc(&C_d, Nbytes));

  HIPCHECK(hipStreamCreateWithFlags(&mystream, hipStreamNonBlocking));

  HIPCHECK(hipMemcpyAsync(A_d, A_h, Nbytes, hipMemcpyHostToDevice, mystream));

  const unsigned threadsPerBlock = 256;
  const unsigned blocks = (N_elmts + 255)/threadsPerBlock;

  hipLaunchKernelGGL((vector_square), dim3(blocks), dim3(threadsPerBlock), 0,
                      mystream, C_d, A_d, N_elmts);
  HIPCHECK(hipMemcpyAsync(C_h, C_d, Nbytes, hipMemcpyDeviceToHost, mystream));
  HIPCHECK(hipStreamAddCallback(mystream, Callback1, NULL, 0));

  // Wait untill Callback() function changes the cbDone value to true
  while (!cbDone) {
    std::this_thread::sleep_for (std::chrono::milliseconds(10));
  }

  // Since the callback is supposed to be called only after an implicit stream
  // synchronization, and the runtime cannot continue until the callback is done
  // hipStreamSynchronize call should not take much time.
  auto start = std::chrono::high_resolution_clock::now();
  HIPCHECK(hipStreamSynchronize(mystream));
  auto stop = std::chrono::high_resolution_clock::now();
  auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);

  HIPCHECK(hipStreamDestroy(mystream));
  HIPCHECK(hipFree(A_d));
  HIPCHECK(hipFree(C_d));
  free(A_h);
  free(C_h);

  if (Data_mismatch.load() != 0) {
    failed("Output from kernel execution is not as expected");
  }

  // HIP runtime cannot proceed further in the queue until callback completes
  // Stream synchronize should not have much task to do after callback
  // It should just be an extra empty marker wait
  // Therefore the hipStreamSynchronize() in the
  // main thread should hardly take any time to complete.

  if (duration.count() < 200) {
    passed();
  } else {
    failed("hipStreamSynchronize is taking more time than expected after Callback()");
  }
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//
//  File: ProcessVorticity.cpp
//
//  For more information, please see: http://www.nektar.info/
//
//  The MIT License
//
//  Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
//  Department of Aeronautics, Imperial College London (UK), and Scientific
//  Computing and Imaging Institute, University of Utah (USA).
//
//  License for the specific language governing rights and limitations under
//  Permission is hereby granted, free of charge, to any person obtaining a
//  copy of this software and associated documentation files (the "Software"),
//  to deal in the Software without restriction, including without limitation
//  the rights to use, copy, modify, merge, publish, distribute, sublicense,
//  and/or sell copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included
//  in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
//  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
//  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//  DEALINGS IN THE SOFTWARE.
//
//  Description: Computes Q Criterion field.
//
////////////////////////////////////////////////////////////////////////////////

#include <string>
#include <iostream>
using namespace std;

#include "ProcessQCriterion.h"

#include <LibUtilities/BasicUtils/SharedArray.hpp>
#include <LibUtilities/BasicUtils/ParseUtils.hpp>

namespace Nektar
{
    namespace Utilities
    {
        ModuleKey ProcessQCriterion::className =
            GetModuleFactory().RegisterCreatorFunction(
                ModuleKey(eProcessModule, "QCriterion"),
                ProcessQCriterion::create, "Computes Q Criterion (but now it's actually just a test).");

        ProcessQCriterion::ProcessQCriterion(FieldSharedPtr f) : ProcessModule(f)
        {
        }

        ProcessQCriterion::~ProcessQCriterion()
        {
        }

        void ProcessQCriterion::Process(po::variables_map &vm)
        {
            if (m_f->m_verbose)
            {
                cout << "ProcessQCriterion: Calculating Q Criterion..." << endl;
            }

            int i, j;
            int expdim    = m_f->m_graph->GetMeshDimension();
            int spacedim  = expdim;
            if ((m_f->m_fielddef[0]->m_numHomogeneousDir) == 1 ||
                (m_f->m_fielddef[0]->m_numHomogeneousDir) == 2)
            {
                spacedim = 3;
            }
            int nfields = m_f->m_fielddef[0]->m_fields.size();
            if (spacedim == 1)
            {
                ASSERTL0(false, "Error: ProcessQCriterion for a 1D problem cannot "
                                "be computed")
            }
            int addfields = (spacedim == 2)? 1:3;

            int npoints = m_f->m_exp[0]->GetNpoints();
            Array<OneD, Array<OneD, NekDouble> > grad(nfields*nfields);
            Array<OneD, Array<OneD, NekDouble> > outfield(addfields);
            m_f->m_exp.resize(nfields+addfields);

            for (i = 0; i < nfields*nfields; ++i)
            {
                grad[i] = Array<OneD, NekDouble>(npoints);
            }

            for (i = 0; i < addfields; ++i)
            {
                outfield[i] = Array<OneD, NekDouble>(npoints);
            }

            // Calculate Gradient & Vorticity
            if (spacedim == 2)
            {
                for (i = 0; i < nfields; ++i)
                {
                    m_f->m_exp[i]->PhysDeriv(m_f->m_exp[i]->GetPhys(),
                                             grad[i*nfields],
                                             grad[i*nfields+1]);
                }
                // W_z = Vx - Uy
                Vmath::Vsub(npoints, grad[1*nfields+0], 1,
                            grad[0*nfields+1], 1,
                            outfield[0], 1);
            }
            else
            {
                for (i = 0; i < nfields; ++i)
                {

                    m_f->m_exp[i]->PhysDeriv(m_f->m_exp[i]->GetPhys(),
                                             grad[i*nfields],
                                             grad[i*nfields+1],
                                             grad[i*nfields+2]);
                }

                // W_x = Wy - Vz
                Vmath::Vsub(npoints, grad[2*nfields+1], 1, grad[1*nfields+2], 1,
                            outfield[0],1);
                // W_y = Uz - Wx
                Vmath::Vsub(npoints, grad[0*nfields+2], 1, grad[2*nfields+0], 1,
                            outfield[1], 1);
                // W_z = Vx - Uy
                Vmath::Vsub(npoints, grad[1*nfields+0], 1, grad[0*nfields+1], 1,
                            outfield[2], 1);
            }

            for (i = 0; i < addfields; ++i)
            {
                m_f->m_exp[nfields + i] = m_f->AppendExpList();
                m_f->m_exp[nfields + i]->UpdatePhys() = outfield[i];
                m_f->m_exp[nfields + i]->FwdTrans(outfield[i],
                                    m_f->m_exp[nfields + i]->UpdateCoeffs());
            }

            vector<string > outname;
            if (addfields == 1)
            {
                outname.push_back("W_z");
            }
            else
            {
                outname.push_back("Q_x");
                outname.push_back("Q_y");
                outname.push_back("Q_z");
            }

            std::vector<LibUtilities::FieldDefinitionsSharedPtr> FieldDef
                = m_f->m_exp[0]->GetFieldDefinitions();
            std::vector<std::vector<NekDouble> > FieldData(FieldDef.size());

            for (j = 0; j < nfields + addfields; ++j)
            {
                for (i = 0; i < FieldDef.size(); ++i)
                {
                    if (j >= nfields)
                    {
                        FieldDef[i]->m_fields.push_back(outname[j-nfields]);
                    }
                    else
                    {
                        FieldDef[i]->m_fields.push_back(m_f->m_fielddef[0]->m_fields[j]);
                    }
                    m_f->m_exp[j]->AppendFieldData(FieldDef[i], FieldData[i]);
                }
            }

            m_f->m_fielddef = FieldDef;
            m_f->m_data     = FieldData;

        }
    }
}
<commit_msg>Q-Criterion implemented<commit_after>////////////////////////////////////////////////////////////////////////////////
//
//  File: ProcessVorticity.cpp
//
//  For more information, please see: http://www.nektar.info/
//
//  The MIT License
//
//  Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
//  Department of Aeronautics, Imperial College London (UK), and Scientific
//  Computing and Imaging Institute, University of Utah (USA).
//
//  License for the specific language governing rights and limitations under
//  Permission is hereby granted, free of charge, to any person obtaining a
//  copy of this software and associated documentation files (the "Software"),
//  to deal in the Software without restriction, including without limitation
//  the rights to use, copy, modify, merge, publish, distribute, sublicense,
//  and/or sell copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included
//  in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
//  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
//  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//  DEALINGS IN THE SOFTWARE.
//
//  Description: Computes Q Criterion field.
//
////////////////////////////////////////////////////////////////////////////////

#include <string>
#include <iostream>
using namespace std;

#include "ProcessQCriterion.h"

#include <LibUtilities/BasicUtils/SharedArray.hpp>
#include <LibUtilities/BasicUtils/ParseUtils.hpp>

namespace Nektar
{
    namespace Utilities
    {
        ModuleKey ProcessQCriterion::className =
		GetModuleFactory().RegisterCreatorFunction(
												   ModuleKey(eProcessModule, "QCriterion"),
												   ProcessQCriterion::create, "Computes Q Criterion (but now it's actually just a test).");

        ProcessQCriterion::ProcessQCriterion(FieldSharedPtr f) : ProcessModule(f)
        {
        }

        ProcessQCriterion::~ProcessQCriterion()
        {
        }

        void ProcessQCriterion::Process(po::variables_map &vm)
        {
            if (m_f->m_verbose)
            {
                cout << "ProcessQCriterion: Calculating Q Criterion..." << endl;
            }

            int i, j;
            int expdim    = m_f->m_graph->GetMeshDimension();
            int spacedim  = expdim;
            if ((m_f->m_fielddef[0]->m_numHomogeneousDir) == 1 ||
                (m_f->m_fielddef[0]->m_numHomogeneousDir) == 2)
            {
                spacedim = 3;
            }
            int nfields = m_f->m_fielddef[0]->m_fields.size();
            if (spacedim == 1 || spacedim == 2)
            {
                ASSERTL0(false, "Error: ProcessQCriterion must be computed for a 3D (or quasi-3D) case.")
            }
            //int addfields = (spacedim == 2)? 1:3;
			int addfields = 1; //For calculating Q-Criterion only 1 field must be added

            int npoints = m_f->m_exp[0]->GetNpoints();

            //Array<OneD, Array<OneD, NekDouble> > grad(nfields*nfields);
            //Array<OneD, Array<OneD, NekDouble> > outfield(addfields);

			Array<OneD, Array<OneD, NekDouble> > grad(nfields * nfields);

			Array<OneD, Array<OneD, NekDouble> > omega(nfields * nfields);
			Array<OneD, Array<OneD, NekDouble> > S    (nfields * nfields);

			Array<OneD, Array<OneD, NekDouble> > outfield (addfields);
			Array<OneD, Array<OneD, NekDouble> > outfield1(addfields);
			Array<OneD, Array<OneD, NekDouble> > outfield2(addfields);
			Array<OneD, Array<OneD, NekDouble> > outfield3(addfields);

            m_f->m_exp.resize(nfields+addfields);

            for (i = 0; i < nfields*nfields; ++i)
            {
                grad[i] = Array<OneD, NekDouble>(npoints);
            }

            for (i = 0; i < addfields; ++i)
            {
                outfield[i] = Array<OneD, NekDouble>(npoints); //Will store the Q-Criterion
				outfield1[i] = Array<OneD, NekDouble>(npoints);
				outfield2[i] = Array<OneD, NekDouble>(npoints);
				outfield3[i] = Array<OneD, NekDouble>(npoints);

				omega[i] = Array<OneD, NekDouble>(npoints);
				S[i] = Array<OneD, NekDouble>(npoints);
            }

            // Calculate Gradient & Vorticity
			//            if (spacedim == 2)
			//            {
			//                cerr << "Q-Criterion calculation needs a 3D mesh." << endl;
			//            }
			for (i = 0; i < nfields; ++i)
			{

				m_f->m_exp[i]->PhysDeriv(m_f->m_exp[i]->GetPhys(),
										 grad[i*nfields],
										 grad[i*nfields+1],
										 grad[i*nfields+2]);
			}

			// W_x = Wy - Vz
			//Vmath::Vsub(npoints, grad[2*nfields+1], 1, grad[1*nfields+2], 1,
			//            outfield[0],1);
			// W_y = Uz - Wx
			//Vmath::Vsub(npoints, grad[0*nfields+2], 1, grad[2*nfields+0], 1,
			//            outfield[1], 1);
			// W_z = Vx - Uy
			//Vmath::Vsub(npoints, grad[1*nfields+0], 1, grad[0*nfields+1], 1,
			//            outfield[2], 1);

			//=================================================================
			//=================================================================
			//=================================================================

			// W_x = Wy - Vz
			Vmath::Vsub(npoints, grad[2 * nfields + 1], 1, grad[1 * nfields + 2], 1,
						outfield1[0], 1);
			// W_x^2
			Vmath::Vmul(npoints, outfield1[0], 1, outfield1[0], 1, outfield1[0], 1);

			// W_y = Uz - Wx
			Vmath::Vsub(npoints, grad[0 * nfields + 2], 1, grad[2 * nfields + 0], 1,
						outfield2[0], 1);
			// W_y^2
			Vmath::Vmul(npoints, outfield2[0], 1, outfield2[0], 1, outfield2[0], 1);

			// W_z = Vx - Uy
			Vmath::Vsub(npoints, grad[1 * nfields + 0], 1, grad[0 * nfields + 1], 1,
						outfield3[0], 1);
			// W_z^2
			Vmath::Vmul(npoints, outfield3[0], 1, outfield3[0], 1, outfield3[0], 1);

			// add fields omega = 0.5*(W_x^2 + W_y^2 + W_z^2)

			NekDouble fac = 0.5;
			Vmath::Vadd(npoints, &outfield1[0][0], 1, &outfield2[0][0], 1, &omega[0][0], 1);
			Vmath::Vadd(npoints, &omega[0][0], 1, &outfield3[0][0], 1, &omega[0][0], 1);

			for (int k = 0; k < addfields; ++k)
			{
				Vmath::Smul(npoints, fac, &omega[k][0], 1, &omega[k][0], 1);
			}

			Vmath::Zero(npoints, &outfield1[0][0], 1);
			Vmath::Zero(npoints, &outfield2[0][0], 1);
			Vmath::Zero(npoints, &outfield3[0][0], 1);

			Vmath::Vmul(npoints, grad[0 * nfields + 0], 1, grad[0 * nfields + 0], 1,
						outfield1[0], 1);
			Vmath::Vmul(npoints, grad[1 * nfields + 1], 1, grad[1 * nfields + 1], 1,
						outfield2[0], 1);
			Vmath::Vmul(npoints, grad[2 * nfields + 2], 1, grad[2 * nfields + 2], 1,
						outfield3[0], 1);

			Vmath::Vadd(npoints, &outfield1[0][0], 1, &outfield2[0][0], 1, &S[0][0], 1);
			Vmath::Vadd(npoints, &S[0][0], 1, &outfield3[0][0], 1, &S[0][0], 1);

			// W_y + V_z
			Vmath::Vadd(npoints, grad[2 * nfields + 1], 1, grad[1 * nfields + 2], 1,
						outfield1[0], 1);
			Vmath::Vmul(npoints, &outfield1[0][0], 1, &outfield1[0][0], 1,
						&outfield1[0][0], 1);

			// U_z + W_x
			Vmath::Vadd(npoints, grad[0 * nfields + 2], 1, grad[2 * nfields + 0], 1,
						outfield2[0], 1);
			Vmath::Vmul(npoints, &outfield2[0][0], 1, &outfield2[0][0], 1,
						&outfield2[0][0], 1);

			// V_x + U_y
			Vmath::Vadd(npoints, grad[1 * nfields + 0], 1, grad[0 * nfields + 1], 1,
						outfield3[0], 1);
			Vmath::Vmul(npoints, &outfield3[0][0], 1, &outfield3[0][0], 1,
						&outfield3[0][0], 1);

			Vmath::Vadd(npoints, &outfield1[0][0], 1, &outfield2[0][0], 1,
						&outfield2[0][0], 1);
			Vmath::Vadd(npoints, &outfield2[0][0], 1, &outfield3[0][0], 1,
						&outfield3[0][0], 1);

			for (int k = 0; k < addfields; ++k)
			{
				Vmath::Smul(npoints, fac, &outfield3[k][0], 1, &outfield3[k][0], 1);
			}

			Vmath::Vadd(npoints, &outfield3[0][0], 1, &S[0][0], 1, &S[0][0], 1);
			Vmath::Vsub(npoints, omega[0], 1, S[0], 1, outfield[0], 1);

			for (int k = 0; k < addfields; ++k)
			{
				Vmath::Smul(npoints, fac, &outfield[k][0], 1, &outfield[k][0], 1);
			}

			//=================================================================
			//=================================================================
			//=================================================================

            for (i = 0; i < addfields; ++i)
            {
                m_f->m_exp[nfields + i] = m_f->AppendExpList();
                m_f->m_exp[nfields + i]->UpdatePhys() = outfield[i];
                m_f->m_exp[nfields + i]->FwdTrans(outfield[i],
												  m_f->m_exp[nfields + i]->UpdateCoeffs());
            }

			//            vector<string > outname;
			//            if (addfields == 1)
			//            {
			//                outname.push_back("W_z");
			//            }
			//            else
			//            {
			//                outname.push_back("Q_x");
			//                outname.push_back("Q_y");
			//                outname.push_back("Q_z");
			//            }

			vector<string> outname;
			outname.push_back("Q");

            std::vector<LibUtilities::FieldDefinitionsSharedPtr> FieldDef
			= m_f->m_exp[0]->GetFieldDefinitions();
            std::vector<std::vector<NekDouble> > FieldData(FieldDef.size());

            for (j = 0; j < nfields + addfields; ++j)
            {
                for (i = 0; i < FieldDef.size(); ++i)
                {
                    if (j >= nfields)
                    {
                        FieldDef[i]->m_fields.push_back(outname[j-nfields]);
                    }
                    else
                    {
                        FieldDef[i]->m_fields.push_back(m_f->m_fielddef[0]->m_fields[j]);
                    }
                    m_f->m_exp[j]->AppendFieldData(FieldDef[i], FieldData[i]);
                }
            }

            m_f->m_fielddef = FieldDef;
            m_f->m_data     = FieldData;

        }
    }
}
<|endoftext|>