text
stringlengths 54
60.6k
|
|---|
<commit_before>// @(#)root/auth:$Id$
// Author: Gerardo Ganis 08/07/05
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TRootAuth //
// //
// TVirtualAuth implementation based on the old client authentication //
// code. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TAuthenticate.h"
#include "TEnv.h"
#include "TError.h"
#include "THostAuth.h"
#include "TRootAuth.h"
#include "TRootSecContext.h"
#include "TSocket.h"
#include "TSystem.h"
#include "TUrl.h"
//______________________________________________________________________________
TSecContext *TRootAuth::Authenticate(TSocket *s, const char *host,
const char *user, Option_t *opts)
{
// Runs authentication on socket s.
// Invoked when dynamic loading is needed.
// Returns 1 on success, 0 on failure.
TSecContext *ctx = 0;
Int_t rc = 0;
Int_t rproto = s->GetRemoteProtocol() % 1000;
if (s->GetServType() == (Int_t)TSocket::kROOTD) {
if (rproto > 6 && rproto < 10) {
// Middle aged versions expect client protocol now
s->Send(Form("%d", TSocket::GetClientProtocol()), kROOTD_PROTOCOL2);
Int_t kind = 0;
s->Recv(rproto, kind);
s->SetRemoteProtocol(rproto);
}
}
// Find out if we are a PROOF master
Bool_t isPROOF = (s->GetServType() == (Int_t)TSocket::kPROOFD);
Bool_t isMASTER = kFALSE;
if (isPROOF) {
// Master by default
isMASTER = kTRUE;
// Parse option
TString opt(TUrl(s->GetUrl()).GetOptions());
if (!strncasecmp(opt.Data()+1, "C", 1)) {
isMASTER = kFALSE;
}
}
// Find out whether we are a proof serv
Bool_t isPROOFserv = (opts[0] == 'P') ? kTRUE : kFALSE;
// Build the protocol string for TAuthenticate
TString proto = TUrl(s->GetUrl()).GetProtocol();
if (proto == "") {
proto = "root";
} else if (proto.Contains("sockd") || proto.Contains("rootd") ||
proto.Contains("proofd")) {
proto.ReplaceAll("d",1,"",0);
}
proto += Form(":%d",rproto);
// Init authentication
TAuthenticate *auth =
new TAuthenticate(s, host, proto, user);
// If PROOF client and trasmission of the SRP password is
// requested make sure that ReUse is switched on to get and
// send also the Public Key
// Masters do this automatically upon reception of valid info
// (see TSlave.cxx)
if (isMASTER && !isPROOFserv) {
if (gEnv->GetValue("Proofd.SendSRPPwd",0)) {
Int_t kSRP = TAuthenticate::kSRP;
TString detsSRP(auth->GetHostAuth()->GetDetails(kSRP));
Int_t pos = detsSRP.Index("ru:0");
if (pos > -1) {
detsSRP.ReplaceAll("ru:0",4,"ru:1",4);
auth->GetHostAuth()->SetDetails(kSRP,detsSRP);
} else {
TSubString ss = detsSRP.SubString("ru:no",TString::kIgnoreCase);
if (!ss.IsNull()) {
detsSRP.ReplaceAll(ss.Data(),5,"ru:1",4);
auth->GetHostAuth()->SetDetails(kSRP,detsSRP);
}
}
}
}
// No control on credential forwarding in case of SSH authentication;
// switched it off on PROOF servers, unless the user knows what (s)he
// is doing
if (isPROOFserv) {
if (!(gEnv->GetValue("ProofServ.UseSSH",0)))
auth->GetHostAuth()->RemoveMethod(TAuthenticate::kSSH);
}
// Attempt authentication
if (!auth->Authenticate()) {
// Close the socket if unsuccessful
if (auth->HasTimedOut() > 0)
Error("Authenticate",
"timeout expired for %s@%s", auth->GetUser(), host);
else
Error("Authenticate",
"authentication failed for %s@%s", auth->GetUser(), host);
// This is to terminate properly remote proofd in case of failure
if (isPROOF)
s->Send(Form("%d %s", gSystem->GetPid(), host), kROOTD_CLEANUP);
} else {
// Set return flag;
rc = 1;
// Search pointer to relevant TSecContext
ctx = auth->GetSecContext();
s->SetSecContext(ctx);
}
// Cleanup
delete auth;
// If we are talking to a recent proofd send over a buffer with the
// remaining authentication related stuff
if (rc && isPROOF && rproto > 11) {
Bool_t client = !isPROOFserv;
if (TAuthenticate::ProofAuthSetup(s, client) !=0 ) {
Error("Authenticate", "PROOF: failed to finalize setup");
}
}
// We are done
return ctx;
}
//______________________________________________________________________________
Int_t TRootAuth::ClientVersion()
{
// Return client version;
return TSocket::GetClientProtocol();
}
//______________________________________________________________________________
void TRootAuth::ErrorMsg(const char *where, Int_t ecode)
{
// Print error string corresponding to ecode, prepending location
TAuthenticate::AuthError(where, ecode);
}
<commit_msg>Possible fix for a Coverity report<commit_after>// @(#)root/auth:$Id$
// Author: Gerardo Ganis 08/07/05
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TRootAuth //
// //
// TVirtualAuth implementation based on the old client authentication //
// code. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TAuthenticate.h"
#include "TEnv.h"
#include "TError.h"
#include "THostAuth.h"
#include "TRootAuth.h"
#include "TRootSecContext.h"
#include "TSocket.h"
#include "TSystem.h"
#include "TUrl.h"
//______________________________________________________________________________
TSecContext *TRootAuth::Authenticate(TSocket *s, const char *host,
const char *user, Option_t *opts)
{
// Runs authentication on socket s.
// Invoked when dynamic loading is needed.
// Returns 1 on success, 0 on failure.
TSecContext *ctx = 0;
Int_t rc = 0;
Int_t rproto = s->GetRemoteProtocol() % 1000;
if (s->GetServType() == (Int_t)TSocket::kROOTD) {
if (rproto > 6 && rproto < 10) {
// Middle aged versions expect client protocol now
s->Send(Form("%d", TSocket::GetClientProtocol()), kROOTD_PROTOCOL2);
Int_t kind = 0;
if (s->Recv(rproto, kind) < 0) {
Error("Authenticate", "receiving remote protocol");
return ctx;
}
s->SetRemoteProtocol(rproto);
}
}
// Find out if we are a PROOF master
Bool_t isPROOF = (s->GetServType() == (Int_t)TSocket::kPROOFD);
Bool_t isMASTER = kFALSE;
if (isPROOF) {
// Master by default
isMASTER = kTRUE;
// Parse option
TString opt(TUrl(s->GetUrl()).GetOptions());
if (!strncasecmp(opt.Data()+1, "C", 1)) {
isMASTER = kFALSE;
}
}
// Find out whether we are a proof serv
Bool_t isPROOFserv = (opts[0] == 'P') ? kTRUE : kFALSE;
// Build the protocol string for TAuthenticate
TString proto = TUrl(s->GetUrl()).GetProtocol();
if (proto == "") {
proto = "root";
} else if (proto.Contains("sockd") || proto.Contains("rootd") ||
proto.Contains("proofd")) {
proto.ReplaceAll("d",1,"",0);
}
proto += Form(":%d",rproto);
// Init authentication
TAuthenticate *auth =
new TAuthenticate(s, host, proto, user);
// If PROOF client and trasmission of the SRP password is
// requested make sure that ReUse is switched on to get and
// send also the Public Key
// Masters do this automatically upon reception of valid info
// (see TSlave.cxx)
if (isMASTER && !isPROOFserv) {
if (gEnv->GetValue("Proofd.SendSRPPwd",0)) {
Int_t kSRP = TAuthenticate::kSRP;
TString detsSRP(auth->GetHostAuth()->GetDetails(kSRP));
Int_t pos = detsSRP.Index("ru:0");
if (pos > -1) {
detsSRP.ReplaceAll("ru:0",4,"ru:1",4);
auth->GetHostAuth()->SetDetails(kSRP,detsSRP);
} else {
TSubString ss = detsSRP.SubString("ru:no",TString::kIgnoreCase);
if (!ss.IsNull()) {
detsSRP.ReplaceAll(ss.Data(),5,"ru:1",4);
auth->GetHostAuth()->SetDetails(kSRP,detsSRP);
}
}
}
}
// No control on credential forwarding in case of SSH authentication;
// switched it off on PROOF servers, unless the user knows what (s)he
// is doing
if (isPROOFserv) {
if (!(gEnv->GetValue("ProofServ.UseSSH",0)))
auth->GetHostAuth()->RemoveMethod(TAuthenticate::kSSH);
}
// Attempt authentication
if (!auth->Authenticate()) {
// Close the socket if unsuccessful
if (auth->HasTimedOut() > 0)
Error("Authenticate",
"timeout expired for %s@%s", auth->GetUser(), host);
else
Error("Authenticate",
"authentication failed for %s@%s", auth->GetUser(), host);
// This is to terminate properly remote proofd in case of failure
if (isPROOF)
s->Send(Form("%d %s", gSystem->GetPid(), host), kROOTD_CLEANUP);
} else {
// Set return flag;
rc = 1;
// Search pointer to relevant TSecContext
ctx = auth->GetSecContext();
s->SetSecContext(ctx);
}
// Cleanup
delete auth;
// If we are talking to a recent proofd send over a buffer with the
// remaining authentication related stuff
if (rc && isPROOF && rproto > 11) {
Bool_t client = !isPROOFserv;
if (TAuthenticate::ProofAuthSetup(s, client) !=0 ) {
Error("Authenticate", "PROOF: failed to finalize setup");
}
}
// We are done
return ctx;
}
//______________________________________________________________________________
Int_t TRootAuth::ClientVersion()
{
// Return client version;
return TSocket::GetClientProtocol();
}
//______________________________________________________________________________
void TRootAuth::ErrorMsg(const char *where, Int_t ecode)
{
// Print error string corresponding to ecode, prepending location
TAuthenticate::AuthError(where, ecode);
}
<|endoftext|>
|
<commit_before><commit_msg>MC_sphericity<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: VColumn.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: oj $ $Date: 2001-03-02 15:26:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#define CONNECTIVITY_PROPERTY_NAME_SPACE dbtools
#ifndef _CONNECTIVITY_PROPERTYIDS_HXX_
#include "propertyids.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
// -------------------------------------------------------------------------
using namespace connectivity::dbtools;
using namespace connectivity::sdbcx;
using namespace cppu;
using namespace connectivity;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
// using namespace ::com::sun::star::sdbc;
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OColumn::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException)
{
if(isNew())
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VColumnDescription");
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VColumn");
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OColumn::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
if(isNew())
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.ColumnDescription");
else
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Column");
return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
for (sal_Int32 i=0; i<aSupported.getLength(); ++i, ++pSupported)
if (pSupported->equals(_rServiceName))
return sal_True;
return sal_False;
}
// -------------------------------------------------------------------------
OColumn::OColumn(sal_Bool _bCase) : OColumnDescriptor_BASE(m_aMutex)
, ODescriptor(OColumnDescriptor_BASE::rBHelper,_bCase,sal_True)
, m_Precision(0)
, m_Type(0)
, m_Scale(0)
, m_IsNullable(sal_True)
, m_IsAutoIncrement(sal_False)
, m_IsRowVersion(sal_False)
, m_IsCurrency(sal_False)
{
construct();
}
// -------------------------------------------------------------------------
OColumn::OColumn( const ::rtl::OUString& _Name,
const ::rtl::OUString& _TypeName,
const ::rtl::OUString& _DefaultValue,
sal_Int32 _IsNullable,
sal_Int32 _Precision,
sal_Int32 _Scale,
sal_Int32 _Type,
sal_Bool _IsAutoIncrement,
sal_Bool _IsRowVersion,
sal_Bool _IsCurrency,
sal_Bool _bCase)
: OColumnDescriptor_BASE(m_aMutex)
, ODescriptor(OColumnDescriptor_BASE::rBHelper,_bCase)
, m_TypeName(_TypeName)
, m_DefaultValue(_DefaultValue)
, m_Precision(_Precision)
, m_Type(_Type)
, m_Scale(_Scale)
, m_IsNullable(_IsNullable)
, m_IsAutoIncrement(_IsAutoIncrement)
, m_IsRowVersion(_IsRowVersion)
, m_IsCurrency(_IsCurrency)
{
m_Name = _Name;
construct();
}
// -------------------------------------------------------------------------
OColumn::~OColumn()
{
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OColumn::createArrayHelper( sal_Int32 _nId) const
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;
describeProperties(aProps);
changePropertyAttributte(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& SAL_CALL OColumn::getInfoHelper()
{
return *OColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -----------------------------------------------------------------------------
void SAL_CALL OColumn::acquire() throw(::com::sun::star::uno::RuntimeException)
{
OColumnDescriptor_BASE::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OColumn::release() throw(::com::sun::star::uno::RuntimeException)
{
OColumnDescriptor_BASE::release();
}
// -----------------------------------------------------------------------------
Any SAL_CALL OColumn::queryInterface( const Type & rType ) throw(RuntimeException)
{
Any aRet = ODescriptor::queryInterface( rType);
if(!aRet.hasValue())
{
if(!isNew())
aRet = OColumn_BASE::queryInterface(rType);
if(!aRet.hasValue())
aRet = OColumnDescriptor_BASE::queryInterface( rType);
}
return aRet;
}
// -------------------------------------------------------------------------
Sequence< Type > SAL_CALL OColumn::getTypes( ) throw(RuntimeException)
{
if(isNew())
return ::comphelper::concatSequences(ODescriptor::getTypes(),OColumnDescriptor_BASE::getTypes());
return ::comphelper::concatSequences(ODescriptor::getTypes(),OColumn_BASE::getTypes(),OColumnDescriptor_BASE::getTypes());
}
// -------------------------------------------------------------------------
void OColumn::construct()
{
ODescriptor::construct();
sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;
registerProperty(PROPERTY_TYPENAME, PROPERTY_ID_TYPENAME, nAttrib,&m_TypeName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
registerProperty(PROPERTY_DESCRIPTION, PROPERTY_ID_DESCRIPTION, nAttrib,&m_Description, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
registerProperty(PROPERTY_DEFAULTVALUE, PROPERTY_ID_DEFAULTVALUE, nAttrib,&m_DefaultValue, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
registerProperty(PROPERTY_PRECISION, PROPERTY_ID_PRECISION, nAttrib,&m_Precision, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
registerProperty(PROPERTY_TYPE, PROPERTY_ID_TYPE, nAttrib,&m_Type, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
registerProperty(PROPERTY_SCALE, PROPERTY_ID_SCALE, nAttrib,&m_Scale, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
registerProperty(PROPERTY_ISNULLABLE, PROPERTY_ID_ISNULLABLE, nAttrib,&m_IsNullable, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
registerProperty(PROPERTY_ISAUTOINCREMENT, PROPERTY_ID_ISAUTOINCREMENT, nAttrib,&m_IsAutoIncrement, ::getBooleanCppuType());
registerProperty(PROPERTY_ISROWVERSION, PROPERTY_ID_ISROWVERSION, nAttrib,&m_IsRowVersion, ::getBooleanCppuType());
registerProperty(PROPERTY_ISCURRENCY, PROPERTY_ID_ISCURRENCY, nAttrib,&m_IsCurrency, ::getBooleanCppuType());
}
// -------------------------------------------------------------------------
void OColumn::disposing(void)
{
OPropertySetHelper::disposing();
::osl::MutexGuard aGuard(m_aMutex);
if (OColumnDescriptor_BASE::rBHelper.bDisposed)
throw DisposedException();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > SAL_CALL OColumn::createDataDescriptor( ) throw(RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
if (OColumnDescriptor_BASE::rBHelper.bDisposed)
throw DisposedException();
return this;
}
// -------------------------------------------------------------------------
<commit_msg>allow copyctr<commit_after>/*************************************************************************
*
* $RCSfile: VColumn.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: oj $ $Date: 2001-03-22 07:54:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#define CONNECTIVITY_PROPERTY_NAME_SPACE dbtools
#ifndef _CONNECTIVITY_PROPERTYIDS_HXX_
#include "propertyids.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
// -------------------------------------------------------------------------
using namespace connectivity::dbtools;
using namespace connectivity::sdbcx;
using namespace cppu;
using namespace connectivity;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
// using namespace ::com::sun::star::sdbc;
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OColumn::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException)
{
if(isNew())
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VColumnDescription");
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VColumn");
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OColumn::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
if(isNew())
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.ColumnDescription");
else
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Column");
return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
for (sal_Int32 i=0; i<aSupported.getLength(); ++i, ++pSupported)
if (pSupported->equals(_rServiceName))
return sal_True;
return sal_False;
}
// -------------------------------------------------------------------------
OColumn::OColumn(sal_Bool _bCase) : OColumnDescriptor_BASE(m_aMutex)
, ODescriptor(OColumnDescriptor_BASE::rBHelper,_bCase,sal_True)
, m_Precision(0)
, m_Type(0)
, m_Scale(0)
, m_IsNullable(sal_True)
, m_IsAutoIncrement(sal_False)
, m_IsRowVersion(sal_False)
, m_IsCurrency(sal_False)
{
construct();
}
// -------------------------------------------------------------------------
OColumn::OColumn( const ::rtl::OUString& _Name,
const ::rtl::OUString& _TypeName,
const ::rtl::OUString& _DefaultValue,
sal_Int32 _IsNullable,
sal_Int32 _Precision,
sal_Int32 _Scale,
sal_Int32 _Type,
sal_Bool _IsAutoIncrement,
sal_Bool _IsRowVersion,
sal_Bool _IsCurrency,
sal_Bool _bCase)
: OColumnDescriptor_BASE(m_aMutex)
, ODescriptor(OColumnDescriptor_BASE::rBHelper,_bCase)
, m_TypeName(_TypeName)
, m_DefaultValue(_DefaultValue)
, m_Precision(_Precision)
, m_Type(_Type)
, m_Scale(_Scale)
, m_IsNullable(_IsNullable)
, m_IsAutoIncrement(_IsAutoIncrement)
, m_IsRowVersion(_IsRowVersion)
, m_IsCurrency(_IsCurrency)
{
m_Name = _Name;
construct();
}
// -------------------------------------------------------------------------
OColumn::~OColumn()
{
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OColumn::createArrayHelper( sal_Int32 _nId) const
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;
describeProperties(aProps);
changePropertyAttributte(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& SAL_CALL OColumn::getInfoHelper()
{
return *OColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -----------------------------------------------------------------------------
void SAL_CALL OColumn::acquire() throw(::com::sun::star::uno::RuntimeException)
{
OColumnDescriptor_BASE::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OColumn::release() throw(::com::sun::star::uno::RuntimeException)
{
OColumnDescriptor_BASE::release();
}
// -----------------------------------------------------------------------------
Any SAL_CALL OColumn::queryInterface( const Type & rType ) throw(RuntimeException)
{
Any aRet = ODescriptor::queryInterface( rType);
if(!aRet.hasValue())
{
if(!isNew())
aRet = OColumn_BASE::queryInterface(rType);
if(!aRet.hasValue())
aRet = OColumnDescriptor_BASE::queryInterface( rType);
}
return aRet;
}
// -------------------------------------------------------------------------
Sequence< Type > SAL_CALL OColumn::getTypes( ) throw(RuntimeException)
{
if(isNew())
return ::comphelper::concatSequences(ODescriptor::getTypes(),OColumnDescriptor_BASE::getTypes());
return ::comphelper::concatSequences(ODescriptor::getTypes(),OColumn_BASE::getTypes(),OColumnDescriptor_BASE::getTypes());
}
// -------------------------------------------------------------------------
void OColumn::construct()
{
ODescriptor::construct();
sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;
registerProperty(PROPERTY_TYPENAME, PROPERTY_ID_TYPENAME, nAttrib,&m_TypeName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
registerProperty(PROPERTY_DESCRIPTION, PROPERTY_ID_DESCRIPTION, nAttrib,&m_Description, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
registerProperty(PROPERTY_DEFAULTVALUE, PROPERTY_ID_DEFAULTVALUE, nAttrib,&m_DefaultValue, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
registerProperty(PROPERTY_PRECISION, PROPERTY_ID_PRECISION, nAttrib,&m_Precision, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
registerProperty(PROPERTY_TYPE, PROPERTY_ID_TYPE, nAttrib,&m_Type, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
registerProperty(PROPERTY_SCALE, PROPERTY_ID_SCALE, nAttrib,&m_Scale, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
registerProperty(PROPERTY_ISNULLABLE, PROPERTY_ID_ISNULLABLE, nAttrib,&m_IsNullable, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
registerProperty(PROPERTY_ISAUTOINCREMENT, PROPERTY_ID_ISAUTOINCREMENT, nAttrib,&m_IsAutoIncrement, ::getBooleanCppuType());
registerProperty(PROPERTY_ISROWVERSION, PROPERTY_ID_ISROWVERSION, nAttrib,&m_IsRowVersion, ::getBooleanCppuType());
registerProperty(PROPERTY_ISCURRENCY, PROPERTY_ID_ISCURRENCY, nAttrib,&m_IsCurrency, ::getBooleanCppuType());
}
// -------------------------------------------------------------------------
void OColumn::disposing(void)
{
OPropertySetHelper::disposing();
::osl::MutexGuard aGuard(m_aMutex);
if (OColumnDescriptor_BASE::rBHelper.bDisposed)
throw DisposedException();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > SAL_CALL OColumn::createDataDescriptor( ) throw(RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
if (OColumnDescriptor_BASE::rBHelper.bDisposed)
throw DisposedException();
OColumn* pNewColumn = new OColumn( m_Name,
m_TypeName,
m_DefaultValue,
m_IsNullable,
m_Precision,
m_Scale,
m_Type,
m_IsAutoIncrement,
m_IsRowVersion,
m_IsCurrency,
isCaseSensitive());
pNewColumn->m_Description = m_Description;
pNewColumn->setNew(sal_True);
return pNewColumn;
}
// -------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <set>
#include "base/file_util.h"
#include "base/memory/scoped_callback_factory.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/message_loop_proxy.h"
#include "base/scoped_temp_dir.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/quota/mock_quota_manager.h"
#include "webkit/quota/mock_special_storage_policy.h"
#include "webkit/quota/mock_storage_client.h"
namespace quota {
const char kTestOrigin1[] = "http://host1:1/";
const char kTestOrigin2[] = "http://host2:1/";
const char kTestOrigin3[] = "http://host3:1/";
const GURL kOrigin1(kTestOrigin1);
const GURL kOrigin2(kTestOrigin2);
const GURL kOrigin3(kTestOrigin3);
class MockQuotaManagerTest : public testing::Test {
public:
MockQuotaManagerTest()
: callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
deletion_callback_count_(0) {
}
void SetUp() {
ASSERT_TRUE(data_dir_.CreateUniqueTempDir());
policy_ = new MockSpecialStoragePolicy;
manager_ = new MockQuotaManager(
false /* is_incognito */,
data_dir_.path(),
base::MessageLoopProxy::CreateForCurrentThread(),
base::MessageLoopProxy::CreateForCurrentThread(),
policy_);
}
void TearDown() {
// Make sure the quota manager cleans up correctly.
manager_ = NULL;
MessageLoop::current()->RunAllPending();
}
void GetModifiedOrigins(StorageType type, base::Time since) {
manager_->GetOriginsModifiedSince(type, since,
callback_factory_.NewCallback(
&MockQuotaManagerTest::GotModifiedOrigins));
}
void GotModifiedOrigins(const std::set<GURL>& origins, StorageType type) {
origins_ = origins;
type_ = type;
}
void DeleteOriginData(const GURL& origin, StorageType type) {
manager_->DeleteOriginData(origin, type,
callback_factory_.NewCallback(
&MockQuotaManagerTest::DeletedOriginData));
}
void DeletedOriginData(QuotaStatusCode status) {
++deletion_callback_count_;
EXPECT_EQ(quota::kQuotaStatusOk, status);
}
int deletion_callback_count() const {
return deletion_callback_count_;
}
MockQuotaManager* manager() const {
return manager_.get();
}
const std::set<GURL>& origins() const {
return origins_;
}
const StorageType type() const {
return type_;
}
private:
ScopedTempDir data_dir_;
base::ScopedCallbackFactory<MockQuotaManagerTest> callback_factory_;
scoped_refptr<MockQuotaManager> manager_;
scoped_refptr<MockSpecialStoragePolicy> policy_;
int deletion_callback_count_;
std::set<GURL> origins_;
StorageType type_;
DISALLOW_COPY_AND_ASSIGN(MockQuotaManagerTest);
};
TEST_F(MockQuotaManagerTest, BasicOriginManipulation) {
EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));
manager()->AddOrigin(kOrigin1, kStorageTypeTemporary, base::Time::Now());
EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));
manager()->AddOrigin(kOrigin1, kStorageTypePersistent, base::Time::Now());
EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));
manager()->AddOrigin(kOrigin2, kStorageTypeTemporary, base::Time::Now());
EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
EXPECT_TRUE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));
}
TEST_F(MockQuotaManagerTest, OriginDeletion) {
manager()->AddOrigin(kOrigin1, kStorageTypeTemporary, base::Time::Now());
manager()->AddOrigin(kOrigin2, kStorageTypeTemporary, base::Time::Now());
DeleteOriginData(kOrigin2, kStorageTypeTemporary);
MessageLoop::current()->RunAllPending();
EXPECT_EQ(1, deletion_callback_count());
EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
}
TEST_F(MockQuotaManagerTest, ModifiedOrigins) {
base::Time now = base::Time::Now();
base::Time then = base::Time();
base::TimeDelta an_hour = base::TimeDelta::FromMilliseconds(3600000);
base::TimeDelta a_minute = base::TimeDelta::FromMilliseconds(60000);
GetModifiedOrigins(kStorageTypeTemporary, then);
MessageLoop::current()->RunAllPending();
EXPECT_TRUE(origins().empty());
manager()->AddOrigin(kOrigin1, kStorageTypeTemporary, now - an_hour);
GetModifiedOrigins(kStorageTypeTemporary, then);
MessageLoop::current()->RunAllPending();
EXPECT_EQ(kStorageTypeTemporary, type());
EXPECT_EQ(1UL, origins().size());
EXPECT_EQ(1UL, origins().count(kOrigin1));
EXPECT_EQ(0UL, origins().count(kOrigin2));
manager()->AddOrigin(kOrigin2, kStorageTypeTemporary, now);
GetModifiedOrigins(kStorageTypeTemporary, then);
MessageLoop::current()->RunAllPending();
EXPECT_EQ(kStorageTypeTemporary, type());
EXPECT_EQ(2UL, origins().size());
EXPECT_EQ(1UL, origins().count(kOrigin1));
EXPECT_EQ(1UL, origins().count(kOrigin2));
GetModifiedOrigins(kStorageTypeTemporary, now - a_minute);
MessageLoop::current()->RunAllPending();
EXPECT_EQ(kStorageTypeTemporary, type());
EXPECT_EQ(1UL, origins().size());
EXPECT_EQ(0UL, origins().count(kOrigin1));
EXPECT_EQ(1UL, origins().count(kOrigin2));
}
} // Namespace quota
<commit_msg>Fix "Mac Clang (dbg)" build TBR=mkwst TEST=builds OK Review URL: http://codereview.chromium.org/7583004<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <set>
#include "base/file_util.h"
#include "base/memory/scoped_callback_factory.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/message_loop_proxy.h"
#include "base/scoped_temp_dir.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/quota/mock_quota_manager.h"
#include "webkit/quota/mock_special_storage_policy.h"
#include "webkit/quota/mock_storage_client.h"
namespace quota {
const char kTestOrigin1[] = "http://host1:1/";
const char kTestOrigin2[] = "http://host2:1/";
const char kTestOrigin3[] = "http://host3:1/";
const GURL kOrigin1(kTestOrigin1);
const GURL kOrigin2(kTestOrigin2);
const GURL kOrigin3(kTestOrigin3);
class MockQuotaManagerTest : public testing::Test {
public:
MockQuotaManagerTest()
: callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
deletion_callback_count_(0) {
}
void SetUp() {
ASSERT_TRUE(data_dir_.CreateUniqueTempDir());
policy_ = new MockSpecialStoragePolicy;
manager_ = new MockQuotaManager(
false /* is_incognito */,
data_dir_.path(),
base::MessageLoopProxy::CreateForCurrentThread(),
base::MessageLoopProxy::CreateForCurrentThread(),
policy_);
}
void TearDown() {
// Make sure the quota manager cleans up correctly.
manager_ = NULL;
MessageLoop::current()->RunAllPending();
}
void GetModifiedOrigins(StorageType type, base::Time since) {
manager_->GetOriginsModifiedSince(type, since,
callback_factory_.NewCallback(
&MockQuotaManagerTest::GotModifiedOrigins));
}
void GotModifiedOrigins(const std::set<GURL>& origins, StorageType type) {
origins_ = origins;
type_ = type;
}
void DeleteOriginData(const GURL& origin, StorageType type) {
manager_->DeleteOriginData(origin, type,
callback_factory_.NewCallback(
&MockQuotaManagerTest::DeletedOriginData));
}
void DeletedOriginData(QuotaStatusCode status) {
++deletion_callback_count_;
EXPECT_EQ(quota::kQuotaStatusOk, status);
}
int deletion_callback_count() const {
return deletion_callback_count_;
}
MockQuotaManager* manager() const {
return manager_.get();
}
const std::set<GURL>& origins() const {
return origins_;
}
const StorageType& type() const {
return type_;
}
private:
ScopedTempDir data_dir_;
base::ScopedCallbackFactory<MockQuotaManagerTest> callback_factory_;
scoped_refptr<MockQuotaManager> manager_;
scoped_refptr<MockSpecialStoragePolicy> policy_;
int deletion_callback_count_;
std::set<GURL> origins_;
StorageType type_;
DISALLOW_COPY_AND_ASSIGN(MockQuotaManagerTest);
};
TEST_F(MockQuotaManagerTest, BasicOriginManipulation) {
EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));
manager()->AddOrigin(kOrigin1, kStorageTypeTemporary, base::Time::Now());
EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));
manager()->AddOrigin(kOrigin1, kStorageTypePersistent, base::Time::Now());
EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));
manager()->AddOrigin(kOrigin2, kStorageTypeTemporary, base::Time::Now());
EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
EXPECT_TRUE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypePersistent));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypePersistent));
}
TEST_F(MockQuotaManagerTest, OriginDeletion) {
manager()->AddOrigin(kOrigin1, kStorageTypeTemporary, base::Time::Now());
manager()->AddOrigin(kOrigin2, kStorageTypeTemporary, base::Time::Now());
DeleteOriginData(kOrigin2, kStorageTypeTemporary);
MessageLoop::current()->RunAllPending();
EXPECT_EQ(1, deletion_callback_count());
EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kStorageTypeTemporary));
EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kStorageTypeTemporary));
}
TEST_F(MockQuotaManagerTest, ModifiedOrigins) {
base::Time now = base::Time::Now();
base::Time then = base::Time();
base::TimeDelta an_hour = base::TimeDelta::FromMilliseconds(3600000);
base::TimeDelta a_minute = base::TimeDelta::FromMilliseconds(60000);
GetModifiedOrigins(kStorageTypeTemporary, then);
MessageLoop::current()->RunAllPending();
EXPECT_TRUE(origins().empty());
manager()->AddOrigin(kOrigin1, kStorageTypeTemporary, now - an_hour);
GetModifiedOrigins(kStorageTypeTemporary, then);
MessageLoop::current()->RunAllPending();
EXPECT_EQ(kStorageTypeTemporary, type());
EXPECT_EQ(1UL, origins().size());
EXPECT_EQ(1UL, origins().count(kOrigin1));
EXPECT_EQ(0UL, origins().count(kOrigin2));
manager()->AddOrigin(kOrigin2, kStorageTypeTemporary, now);
GetModifiedOrigins(kStorageTypeTemporary, then);
MessageLoop::current()->RunAllPending();
EXPECT_EQ(kStorageTypeTemporary, type());
EXPECT_EQ(2UL, origins().size());
EXPECT_EQ(1UL, origins().count(kOrigin1));
EXPECT_EQ(1UL, origins().count(kOrigin2));
GetModifiedOrigins(kStorageTypeTemporary, now - a_minute);
MessageLoop::current()->RunAllPending();
EXPECT_EQ(kStorageTypeTemporary, type());
EXPECT_EQ(1UL, origins().size());
EXPECT_EQ(0UL, origins().count(kOrigin1));
EXPECT_EQ(1UL, origins().count(kOrigin2));
}
} // Namespace quota
<|endoftext|>
|
<commit_before>#include "gtest/gtest.h"
#include <list>
#include "../src/scene/Ionosphere.h"
#include "../src/tracer/Ray.h"
#include "../src/core/Config.h"
#include "../src/exporter/Data.h"
#include "../src/exporter/MatlabExporter.h"
namespace {
using namespace raytracer::exporter;
using namespace raytracer::math;
using namespace raytracer::scene;
using namespace raytracer::core;
class ValidationTest : public ::testing::Test {
};
TEST_F(ValidationTest, ElectronDensityProfiles) {
list<Data> dataSet;
Config celestialConfig = Config("config/scenario_default.json");
double SZA = 76 * Constants::PI / 180;
double R = 3390e3;
int dh = 400;
const Json::Value ionosphereConfig = celestialConfig.getArray("ionosphere");
for (int idx = 0; idx < ionosphereConfig.size(); idx++) {
int hS = ionosphereConfig[idx].get("start", 0).asInt();
int hE = ionosphereConfig[idx].get("end", 0).asInt();
double electronPeakDensity = atof(ionosphereConfig[idx].get("electronPeakDensity", "").asCString());
double peakProductionAltitude = ionosphereConfig[idx].get("peakProductionAltitude", "").asDouble();
Json::Value stratificationRaw = ionosphereConfig[idx].get("stratification", "");
const char * stratificationType = stratificationRaw.asCString();
for (int h = hS; h < hE; h += dh) {
Vector3d N = Vector3d(sin(SZA), cos(SZA), 0).norm();
Plane3d mesh = Plane3d(N, Vector3d((R+h)*N.x, (R+h)*N.y, (R+h)*N.z));
mesh.size = 1000;
Ionosphere io = Ionosphere(mesh);
io.layerHeight = dh;
io.setElectronPeakDensity(electronPeakDensity);
io.setPeakProductionAltitude(peakProductionAltitude);
ASSERT_LT(0, io.getElectronPeakDensity());
ASSERT_LT(0, io.getPeakProductionAltitude());
ASSERT_LT(50e3, io.getAltitude());
ASSERT_LT(0, io.getElectronNumberDensity());
Data d;
d.x = mesh.centerpoint.x;
d.y = mesh.centerpoint.y;
d.n_e = io.getElectronNumberDensity();
dataSet.push_back(d);
}
}
MatlabExporter me;
me.dump("Debug/data_LS270_SA75_DS0.dat", dataSet);
}
}
<commit_msg>validationtest exports electrondensities comparable with real research situations<commit_after>#include "gtest/gtest.h"
#include <list>
#include "../src/scene/Ionosphere.h"
#include "../src/tracer/Ray.h"
#include "../src/core/Config.h"
#include "../src/exporter/Data.h"
#include "../src/exporter/MatlabExporter.h"
namespace {
using namespace raytracer::exporter;
using namespace raytracer::math;
using namespace raytracer::scene;
using namespace raytracer::core;
class ValidationTest : public ::testing::Test {
};
TEST_F(ValidationTest, ElectronDensityProfiles) {
list<Data> dataSet;
Config celestialConfig = Config("config/scenario_LS270_SA250_DS0.json");
double SZA = 76 * Constants::PI / 180;
double R = 3390e3;
int dh = 100;
const Json::Value ionosphereConfig = celestialConfig.getArray("ionosphere");
for (int h = 50e3; h < 250e3; h += dh) {
Vector3d N = Vector3d(sin(SZA), cos(SZA), 0).norm();
Plane3d mesh = Plane3d(N, Vector3d((R+h)*N.x, (R+h)*N.y, (R+h)*N.z));
mesh.size = 1000;
Ionosphere io = Ionosphere(mesh);
io.layerHeight = dh;
ASSERT_NEAR(SZA, io.getMesh().normal.angle(Vector3d::SUBSOLAR), 0.001);
for (int idx = 0; idx < ionosphereConfig.size(); idx++) {
double electronPeakDensity = atof(ionosphereConfig[idx].get("electronPeakDensity", "").asCString());
double peakProductionAltitude = ionosphereConfig[idx].get("peakProductionAltitude", "").asDouble();
double neutralScaleHeight = ionosphereConfig[idx].get("neutralScaleHeight", "").asDouble();
ASSERT_LT(0, electronPeakDensity);
ASSERT_LT(0, peakProductionAltitude);
ASSERT_LT(0, neutralScaleHeight);
io.superimposeElectronNumberDensity(electronPeakDensity, peakProductionAltitude, neutralScaleHeight);
ASSERT_NEAR(h, io.getAltitude(), 1);
}
Data d;
d.x = mesh.centerpoint.x;
d.y = mesh.centerpoint.y;
d.n_e = io.getElectronNumberDensity();
dataSet.push_back(d);
}
MatlabExporter me;
me.dump("Debug/data_LS270_SA75_DS0.dat", dataSet);
}
}
<|endoftext|>
|
<commit_before>#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"
int main(int argc, char** argv) {
namespace tf = tensorflow;
tf::Session* session;
tf::Status status = tf::NewSession(tf::SessionOptions(), &session);
if (!status.ok()) {
std::cout << status.ToString() << std::endl;
return 1;
}
tf::GraphDef graph_def;
status = ReadBinaryProto(tf::Env::Default(), "graph.pb", &graph_def);
if (!status.ok()) {
std::cout << status.ToString() << std::endl;
return 1;
}
status = session->Create(graph_def);
if (!status.ok()) {
std::cout << status.ToString() << std::endl;
return 1;
}
tf::Tensor x(tf::DT_FLOAT, tf::TensorShape()), y(tf::DT_FLOAT, tf::TensorShape());
x.scalar<float>()() = 23.0;
y.scalar<float>()() = 19.0;
std::vector<std::pair<tf::string, tf::Tensor>> input_tensors = {{"x", x}, {"y", y}};
std::vector<tf::Tensor> output_tensors;
status = session->Run(input_tensors, {"z"}, {}, &output_tensors);
if (!status.ok()) {
std::cout << status.ToString() << std::endl;
return 1;
}
tf::Tensor output = output_tensors[0];
std::cout << "Success: " << output.scalar<float>() << "!" << std::endl;
session->Close();
return 0;
}
<commit_msg>Added function to check status<commit_after>#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"
/**
* Checks if the given status is ok.
* If not, the status is printed and the
* program is terminated.
*/
void checkStatus(const tensorflow::Status& status) {
if (!status.ok()) {
std::cout << status.ToString() << std::endl;
exit(1);
}
}
int main(int argc, char** argv) {
namespace tf = tensorflow;
tf::Session* session;
tf::Status status = tf::NewSession(tf::SessionOptions(), &session);
checkStatus(status);
tf::GraphDef graph_def;
status = ReadBinaryProto(tf::Env::Default(), "graph.pb", &graph_def);
checkStatus(status);
status = session->Create(graph_def);
checkStatus(status);
tf::Tensor x(tf::DT_FLOAT, tf::TensorShape()), y(tf::DT_FLOAT, tf::TensorShape());
x.scalar<float>()() = 23.0;
y.scalar<float>()() = 19.0;
std::vector<std::pair<tf::string, tf::Tensor>> input_tensors = {{"x", x}, {"y", y}};
std::vector<tf::Tensor> output_tensors;
status = session->Run(input_tensors, {"z"}, {}, &output_tensors);
checkStatus(status);
tf::Tensor output = output_tensors[0];
std::cout << "Success: " << output.scalar<float>() << "!" << std::endl;
session->Close();
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// HACK for crbug.com/142782. I've put it all the way up here to avoid a merge
// collision
namespace base {
namespace mac {
bool IsOSSnowLeopardOrLater() { return true; }
} // namespace mac
} // namespace base
#include "net/socket/nss_ssl_util.h"
#include <nss.h>
#include <secerr.h>
#include <ssl.h>
#include <sslerr.h>
#include <string>
#include "base/bind.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "build/build_config.h"
#include "crypto/nss_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#elif defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif
namespace net {
class NSSSSLInitSingleton {
public:
NSSSSLInitSingleton() {
crypto::EnsureNSSInit();
NSS_SetDomesticPolicy();
#if defined(USE_SYSTEM_SSL)
// Use late binding to avoid scary but benign warning
// "Symbol `SSL_ImplementedCiphers' has different size in shared object,
// consider re-linking"
// TODO(wtc): Use the new SSL_GetImplementedCiphers and
// SSL_GetNumImplementedCiphers functions when we require NSS 3.12.6.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=496993.
const PRUint16* pSSL_ImplementedCiphers = static_cast<const PRUint16*>(
dlsym(RTLD_DEFAULT, "SSL_ImplementedCiphers"));
if (pSSL_ImplementedCiphers == NULL) {
NOTREACHED() << "Can't get list of supported ciphers";
return;
}
#else
#define pSSL_ImplementedCiphers SSL_ImplementedCiphers
#endif
// Explicitly enable exactly those ciphers with keys of at least 80 bits
for (int i = 0; i < SSL_NumImplementedCiphers; i++) {
SSLCipherSuiteInfo info;
if (SSL_GetCipherSuiteInfo(pSSL_ImplementedCiphers[i], &info,
sizeof(info)) == SECSuccess) {
SSL_CipherPrefSetDefault(pSSL_ImplementedCiphers[i],
(info.effectiveKeyBits >= 80));
}
}
// Enable SSL.
SSL_OptionSetDefault(SSL_SECURITY, PR_TRUE);
// Disable ECDSA cipher suites on platforms that do not support ECDSA
// signed certificates, as servers may use the presence of such
// ciphersuites as a hint to send an ECDSA certificate.
#if defined(OS_WIN)
if (base::win::GetVersion() < base::win::VERSION_VISTA)
DisableECDSA();
#elif defined(OS_MACOSX)
if (!base::mac::IsOSSnowLeopardOrLater())
DisableECDSA();
#endif
// All other SSL options are set per-session by SSLClientSocket and
// SSLServerSocket.
}
~NSSSSLInitSingleton() {
// Have to clear the cache, or NSS_Shutdown fails with SEC_ERROR_BUSY.
SSL_ClearSessionCache();
}
void DisableECDSA() {
const PRUint16* ciphersuites = SSL_GetImplementedCiphers();
const unsigned num_ciphersuites = SSL_GetNumImplementedCiphers();
SECStatus rv;
SSLCipherSuiteInfo info;
for (unsigned i = 0; i < num_ciphersuites; i++) {
rv = SSL_GetCipherSuiteInfo(ciphersuites[i], &info, sizeof(info));
if (rv == SECSuccess && info.authAlgorithm == ssl_auth_ecdsa)
SSL_CipherPrefSetDefault(ciphersuites[i], PR_FALSE);
}
}
};
static base::LazyInstance<NSSSSLInitSingleton> g_nss_ssl_init_singleton =
LAZY_INSTANCE_INITIALIZER;
// Initialize the NSS SSL library if it isn't already initialized. This must
// be called before any other NSS SSL functions. This function is
// thread-safe, and the NSS SSL library will only ever be initialized once.
// The NSS SSL library will be properly shut down on program exit.
void EnsureNSSSSLInit() {
// Initializing SSL causes us to do blocking IO.
// Temporarily allow it until we fix
// http://code.google.com/p/chromium/issues/detail?id=59847
base::ThreadRestrictions::ScopedAllowIO allow_io;
g_nss_ssl_init_singleton.Get();
}
// Map a Chromium net error code to an NSS error code.
// See _MD_unix_map_default_error in the NSS source
// tree for inspiration.
PRErrorCode MapErrorToNSS(int result) {
if (result >=0)
return result;
switch (result) {
case ERR_IO_PENDING:
return PR_WOULD_BLOCK_ERROR;
case ERR_ACCESS_DENIED:
case ERR_NETWORK_ACCESS_DENIED:
// For connect, this could be mapped to PR_ADDRESS_NOT_SUPPORTED_ERROR.
return PR_NO_ACCESS_RIGHTS_ERROR;
case ERR_NOT_IMPLEMENTED:
return PR_NOT_IMPLEMENTED_ERROR;
case ERR_SOCKET_NOT_CONNECTED:
return PR_NOT_CONNECTED_ERROR;
case ERR_INTERNET_DISCONNECTED: // Equivalent to ENETDOWN.
return PR_NETWORK_UNREACHABLE_ERROR; // Best approximation.
case ERR_CONNECTION_TIMED_OUT:
case ERR_TIMED_OUT:
return PR_IO_TIMEOUT_ERROR;
case ERR_CONNECTION_RESET:
return PR_CONNECT_RESET_ERROR;
case ERR_CONNECTION_ABORTED:
return PR_CONNECT_ABORTED_ERROR;
case ERR_CONNECTION_REFUSED:
return PR_CONNECT_REFUSED_ERROR;
case ERR_ADDRESS_UNREACHABLE:
return PR_HOST_UNREACHABLE_ERROR; // Also PR_NETWORK_UNREACHABLE_ERROR.
case ERR_ADDRESS_INVALID:
return PR_ADDRESS_NOT_AVAILABLE_ERROR;
case ERR_NAME_NOT_RESOLVED:
return PR_DIRECTORY_LOOKUP_ERROR;
default:
LOG(WARNING) << "MapErrorToNSS " << result
<< " mapped to PR_UNKNOWN_ERROR";
return PR_UNKNOWN_ERROR;
}
}
// The default error mapping function.
// Maps an NSS error code to a network error code.
int MapNSSError(PRErrorCode err) {
// TODO(port): fill this out as we learn what's important
switch (err) {
case PR_WOULD_BLOCK_ERROR:
return ERR_IO_PENDING;
case PR_ADDRESS_NOT_SUPPORTED_ERROR: // For connect.
case PR_NO_ACCESS_RIGHTS_ERROR:
return ERR_ACCESS_DENIED;
case PR_IO_TIMEOUT_ERROR:
return ERR_TIMED_OUT;
case PR_CONNECT_RESET_ERROR:
return ERR_CONNECTION_RESET;
case PR_CONNECT_ABORTED_ERROR:
return ERR_CONNECTION_ABORTED;
case PR_CONNECT_REFUSED_ERROR:
return ERR_CONNECTION_REFUSED;
case PR_NOT_CONNECTED_ERROR:
return ERR_SOCKET_NOT_CONNECTED;
case PR_HOST_UNREACHABLE_ERROR:
case PR_NETWORK_UNREACHABLE_ERROR:
return ERR_ADDRESS_UNREACHABLE;
case PR_ADDRESS_NOT_AVAILABLE_ERROR:
return ERR_ADDRESS_INVALID;
case PR_INVALID_ARGUMENT_ERROR:
return ERR_INVALID_ARGUMENT;
case PR_END_OF_FILE_ERROR:
return ERR_CONNECTION_CLOSED;
case PR_NOT_IMPLEMENTED_ERROR:
return ERR_NOT_IMPLEMENTED;
case SEC_ERROR_LIBRARY_FAILURE:
return ERR_UNEXPECTED;
case SEC_ERROR_INVALID_ARGS:
return ERR_INVALID_ARGUMENT;
case SEC_ERROR_NO_MEMORY:
return ERR_OUT_OF_MEMORY;
case SEC_ERROR_NO_KEY:
return ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY;
case SEC_ERROR_INVALID_KEY:
case SSL_ERROR_SIGN_HASHES_FAILURE:
return ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED;
// A handshake (initial or renegotiation) may fail because some signature
// (for example, the signature in the ServerKeyExchange message for an
// ephemeral Diffie-Hellman cipher suite) is invalid.
case SEC_ERROR_BAD_SIGNATURE:
return ERR_SSL_PROTOCOL_ERROR;
case SSL_ERROR_SSL_DISABLED:
return ERR_NO_SSL_VERSIONS_ENABLED;
case SSL_ERROR_NO_CYPHER_OVERLAP:
case SSL_ERROR_PROTOCOL_VERSION_ALERT:
case SSL_ERROR_UNSUPPORTED_VERSION:
return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
case SSL_ERROR_HANDSHAKE_FAILURE_ALERT:
case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT:
case SSL_ERROR_ILLEGAL_PARAMETER_ALERT:
return ERR_SSL_PROTOCOL_ERROR;
case SSL_ERROR_DECOMPRESSION_FAILURE_ALERT:
return ERR_SSL_DECOMPRESSION_FAILURE_ALERT;
case SSL_ERROR_BAD_MAC_ALERT:
return ERR_SSL_BAD_RECORD_MAC_ALERT;
case SSL_ERROR_UNSAFE_NEGOTIATION:
return ERR_SSL_UNSAFE_NEGOTIATION;
case SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY:
return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY;
case SSL_ERROR_HANDSHAKE_NOT_COMPLETED:
return ERR_SSL_HANDSHAKE_NOT_COMPLETED;
case SEC_ERROR_BAD_KEY:
case SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE:
// TODO(wtc): the following errors may also occur in contexts unrelated
// to the peer's public key. We should add new error codes for them, or
// map them to ERR_SSL_BAD_PEER_PUBLIC_KEY only in the right context.
// General unsupported/unknown key algorithm error.
case SEC_ERROR_UNSUPPORTED_KEYALG:
// General DER decoding errors.
case SEC_ERROR_BAD_DER:
case SEC_ERROR_EXTRA_INPUT:
return ERR_SSL_BAD_PEER_PUBLIC_KEY;
default: {
if (IS_SSL_ERROR(err)) {
LOG(WARNING) << "Unknown SSL error " << err
<< " mapped to net::ERR_SSL_PROTOCOL_ERROR";
return ERR_SSL_PROTOCOL_ERROR;
}
LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
return ERR_FAILED;
}
}
}
// Returns parameters to attach to the NetLog when we receive an error in
// response to a call to an NSS function. Used instead of
// NetLogSSLErrorCallback with events of type TYPE_SSL_NSS_ERROR.
Value* NetLogSSLFailedNSSFunctionCallback(
const char* function,
const char* param,
int ssl_lib_error,
NetLog::LogLevel /* log_level */) {
DictionaryValue* dict = new DictionaryValue();
dict->SetString("function", function);
if (param[0] != '\0')
dict->SetString("param", param);
dict->SetInteger("ssl_lib_error", ssl_lib_error);
return dict;
}
void LogFailedNSSFunction(const BoundNetLog& net_log,
const char* function,
const char* param) {
DCHECK(function);
DCHECK(param);
net_log.AddEvent(
NetLog::TYPE_SSL_NSS_ERROR,
base::Bind(&NetLogSSLFailedNSSFunctionCallback,
function, param, PR_GetError()));
}
} // namespace net
<commit_msg>net: cleanup code to disable ECDSA<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/socket/nss_ssl_util.h"
#include <nss.h>
#include <secerr.h>
#include <ssl.h>
#include <sslerr.h>
#include <string>
#include "base/bind.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "build/build_config.h"
#include "crypto/nss_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
namespace net {
class NSSSSLInitSingleton {
public:
NSSSSLInitSingleton() {
crypto::EnsureNSSInit();
NSS_SetDomesticPolicy();
#if defined(USE_SYSTEM_SSL)
// Use late binding to avoid scary but benign warning
// "Symbol `SSL_ImplementedCiphers' has different size in shared object,
// consider re-linking"
// TODO(wtc): Use the new SSL_GetImplementedCiphers and
// SSL_GetNumImplementedCiphers functions when we require NSS 3.12.6.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=496993.
const PRUint16* pSSL_ImplementedCiphers = static_cast<const PRUint16*>(
dlsym(RTLD_DEFAULT, "SSL_ImplementedCiphers"));
if (pSSL_ImplementedCiphers == NULL) {
NOTREACHED() << "Can't get list of supported ciphers";
return;
}
#else
#define pSSL_ImplementedCiphers SSL_ImplementedCiphers
#endif
// Disable ECDSA cipher suites on platforms that do not support ECDSA
// signed certificates, as servers may use the presence of such
// ciphersuites as a hint to send an ECDSA certificate.
bool disableECDSA = false;
#if defined(OS_WIN)
if (base::win::GetVersion() < base::win::VERSION_VISTA)
disableECDSA = true;
#endif
// Explicitly enable exactly those ciphers with keys of at least 80 bits
for (int i = 0; i < SSL_NumImplementedCiphers; i++) {
SSLCipherSuiteInfo info;
if (SSL_GetCipherSuiteInfo(pSSL_ImplementedCiphers[i], &info,
sizeof(info)) == SECSuccess) {
SSL_CipherPrefSetDefault(pSSL_ImplementedCiphers[i],
(info.effectiveKeyBits >= 80));
if (info.authAlgorithm == ssl_auth_ecdsa && disableECDSA)
SSL_CipherPrefSetDefault(pSSL_ImplementedCiphers[i], PR_FALSE);
}
}
// Enable SSL.
SSL_OptionSetDefault(SSL_SECURITY, PR_TRUE);
// All other SSL options are set per-session by SSLClientSocket and
// SSLServerSocket.
}
~NSSSSLInitSingleton() {
// Have to clear the cache, or NSS_Shutdown fails with SEC_ERROR_BUSY.
SSL_ClearSessionCache();
}
};
static base::LazyInstance<NSSSSLInitSingleton> g_nss_ssl_init_singleton =
LAZY_INSTANCE_INITIALIZER;
// Initialize the NSS SSL library if it isn't already initialized. This must
// be called before any other NSS SSL functions. This function is
// thread-safe, and the NSS SSL library will only ever be initialized once.
// The NSS SSL library will be properly shut down on program exit.
void EnsureNSSSSLInit() {
// Initializing SSL causes us to do blocking IO.
// Temporarily allow it until we fix
// http://code.google.com/p/chromium/issues/detail?id=59847
base::ThreadRestrictions::ScopedAllowIO allow_io;
g_nss_ssl_init_singleton.Get();
}
// Map a Chromium net error code to an NSS error code.
// See _MD_unix_map_default_error in the NSS source
// tree for inspiration.
PRErrorCode MapErrorToNSS(int result) {
if (result >=0)
return result;
switch (result) {
case ERR_IO_PENDING:
return PR_WOULD_BLOCK_ERROR;
case ERR_ACCESS_DENIED:
case ERR_NETWORK_ACCESS_DENIED:
// For connect, this could be mapped to PR_ADDRESS_NOT_SUPPORTED_ERROR.
return PR_NO_ACCESS_RIGHTS_ERROR;
case ERR_NOT_IMPLEMENTED:
return PR_NOT_IMPLEMENTED_ERROR;
case ERR_SOCKET_NOT_CONNECTED:
return PR_NOT_CONNECTED_ERROR;
case ERR_INTERNET_DISCONNECTED: // Equivalent to ENETDOWN.
return PR_NETWORK_UNREACHABLE_ERROR; // Best approximation.
case ERR_CONNECTION_TIMED_OUT:
case ERR_TIMED_OUT:
return PR_IO_TIMEOUT_ERROR;
case ERR_CONNECTION_RESET:
return PR_CONNECT_RESET_ERROR;
case ERR_CONNECTION_ABORTED:
return PR_CONNECT_ABORTED_ERROR;
case ERR_CONNECTION_REFUSED:
return PR_CONNECT_REFUSED_ERROR;
case ERR_ADDRESS_UNREACHABLE:
return PR_HOST_UNREACHABLE_ERROR; // Also PR_NETWORK_UNREACHABLE_ERROR.
case ERR_ADDRESS_INVALID:
return PR_ADDRESS_NOT_AVAILABLE_ERROR;
case ERR_NAME_NOT_RESOLVED:
return PR_DIRECTORY_LOOKUP_ERROR;
default:
LOG(WARNING) << "MapErrorToNSS " << result
<< " mapped to PR_UNKNOWN_ERROR";
return PR_UNKNOWN_ERROR;
}
}
// The default error mapping function.
// Maps an NSS error code to a network error code.
int MapNSSError(PRErrorCode err) {
// TODO(port): fill this out as we learn what's important
switch (err) {
case PR_WOULD_BLOCK_ERROR:
return ERR_IO_PENDING;
case PR_ADDRESS_NOT_SUPPORTED_ERROR: // For connect.
case PR_NO_ACCESS_RIGHTS_ERROR:
return ERR_ACCESS_DENIED;
case PR_IO_TIMEOUT_ERROR:
return ERR_TIMED_OUT;
case PR_CONNECT_RESET_ERROR:
return ERR_CONNECTION_RESET;
case PR_CONNECT_ABORTED_ERROR:
return ERR_CONNECTION_ABORTED;
case PR_CONNECT_REFUSED_ERROR:
return ERR_CONNECTION_REFUSED;
case PR_NOT_CONNECTED_ERROR:
return ERR_SOCKET_NOT_CONNECTED;
case PR_HOST_UNREACHABLE_ERROR:
case PR_NETWORK_UNREACHABLE_ERROR:
return ERR_ADDRESS_UNREACHABLE;
case PR_ADDRESS_NOT_AVAILABLE_ERROR:
return ERR_ADDRESS_INVALID;
case PR_INVALID_ARGUMENT_ERROR:
return ERR_INVALID_ARGUMENT;
case PR_END_OF_FILE_ERROR:
return ERR_CONNECTION_CLOSED;
case PR_NOT_IMPLEMENTED_ERROR:
return ERR_NOT_IMPLEMENTED;
case SEC_ERROR_LIBRARY_FAILURE:
return ERR_UNEXPECTED;
case SEC_ERROR_INVALID_ARGS:
return ERR_INVALID_ARGUMENT;
case SEC_ERROR_NO_MEMORY:
return ERR_OUT_OF_MEMORY;
case SEC_ERROR_NO_KEY:
return ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY;
case SEC_ERROR_INVALID_KEY:
case SSL_ERROR_SIGN_HASHES_FAILURE:
return ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED;
// A handshake (initial or renegotiation) may fail because some signature
// (for example, the signature in the ServerKeyExchange message for an
// ephemeral Diffie-Hellman cipher suite) is invalid.
case SEC_ERROR_BAD_SIGNATURE:
return ERR_SSL_PROTOCOL_ERROR;
case SSL_ERROR_SSL_DISABLED:
return ERR_NO_SSL_VERSIONS_ENABLED;
case SSL_ERROR_NO_CYPHER_OVERLAP:
case SSL_ERROR_PROTOCOL_VERSION_ALERT:
case SSL_ERROR_UNSUPPORTED_VERSION:
return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
case SSL_ERROR_HANDSHAKE_FAILURE_ALERT:
case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT:
case SSL_ERROR_ILLEGAL_PARAMETER_ALERT:
return ERR_SSL_PROTOCOL_ERROR;
case SSL_ERROR_DECOMPRESSION_FAILURE_ALERT:
return ERR_SSL_DECOMPRESSION_FAILURE_ALERT;
case SSL_ERROR_BAD_MAC_ALERT:
return ERR_SSL_BAD_RECORD_MAC_ALERT;
case SSL_ERROR_UNSAFE_NEGOTIATION:
return ERR_SSL_UNSAFE_NEGOTIATION;
case SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY:
return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY;
case SSL_ERROR_HANDSHAKE_NOT_COMPLETED:
return ERR_SSL_HANDSHAKE_NOT_COMPLETED;
case SEC_ERROR_BAD_KEY:
case SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE:
// TODO(wtc): the following errors may also occur in contexts unrelated
// to the peer's public key. We should add new error codes for them, or
// map them to ERR_SSL_BAD_PEER_PUBLIC_KEY only in the right context.
// General unsupported/unknown key algorithm error.
case SEC_ERROR_UNSUPPORTED_KEYALG:
// General DER decoding errors.
case SEC_ERROR_BAD_DER:
case SEC_ERROR_EXTRA_INPUT:
return ERR_SSL_BAD_PEER_PUBLIC_KEY;
default: {
if (IS_SSL_ERROR(err)) {
LOG(WARNING) << "Unknown SSL error " << err
<< " mapped to net::ERR_SSL_PROTOCOL_ERROR";
return ERR_SSL_PROTOCOL_ERROR;
}
LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
return ERR_FAILED;
}
}
}
// Returns parameters to attach to the NetLog when we receive an error in
// response to a call to an NSS function. Used instead of
// NetLogSSLErrorCallback with events of type TYPE_SSL_NSS_ERROR.
Value* NetLogSSLFailedNSSFunctionCallback(
const char* function,
const char* param,
int ssl_lib_error,
NetLog::LogLevel /* log_level */) {
DictionaryValue* dict = new DictionaryValue();
dict->SetString("function", function);
if (param[0] != '\0')
dict->SetString("param", param);
dict->SetInteger("ssl_lib_error", ssl_lib_error);
return dict;
}
void LogFailedNSSFunction(const BoundNetLog& net_log,
const char* function,
const char* param) {
DCHECK(function);
DCHECK(param);
net_log.AddEvent(
NetLog::TYPE_SSL_NSS_ERROR,
base::Bind(&NetLogSSLFailedNSSFunctionCallback,
function, param, PR_GetError()));
}
} // namespace net
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: cmdlinehelp.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2003-05-28 13:26:13 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdlib.h>
#ifdef UNX
#include <stdio.h>
#endif
#include <sal/types.h>
#include <tools/string.hxx>
#include <vcl/msgbox.hxx>
#include <rtl/bootstrap.hxx>
#include <app.hxx>
#include "desktopresid.hxx"
#include "desktop.hrc"
#include "cmdlinehelp.hxx"
namespace desktop
{
// to be able to display the help nicely in a dialog box with propotional font,
// we need to split it in chunks...
// ___HEAD___
// LEFT RIGHT
// LEFT RIGHT
// LEFT RIGHT
// __BOTTOM__
// [OK]
const char *aCmdLineHelp_head =
"%PRODUCTNAME %PRODUCTVERSION %PRODUCTEXTENSION %BUILDID\n"\
"\n"\
"Usage: %CMDNAME [options] [documents...]\n"\
"\n"\
"Options:\n";
const char *aCmdLineHelp_left =
"-minimized \n"\
"-invisible \n"\
"-norestore \n"\
"-quickstart \n"\
"-nologo \n"\
"-nolockcheck \n"\
"-nodefault \n"\
"-headless \n"\
"-help/-h/-? \n"\
"-writer \n"\
"-calc \n"\
"-draw \n"\
"-impress \n"\
"-math \n"\
"-global \n"\
"-web \n"\
"-o \n"\
"-n \n";
const char *aCmdLineHelp_right =
"keep startup bitmap minimized.\n"\
"no startup screen, no default document and no UI.\n"\
"suppress restart/restore after fatal errors.\n"\
"starts the quickstart service\n"\
"don't show startup screen.\n"\
"don't check for remote instances using the installation\n"\
"don't start with an empty document\n"\
"like invisible but no userinteraction at all.\n"\
"show this message and exit.\n"\
"create new text document.\n"\
"create new spreadsheet document.\n"\
"create new drawing.\n"\
"create new presentation.\n"\
"create new formula.\n"\
"create new global document.\n"\
"create new HTML document.\n"\
"open documents regardless whether they are templates or not.\n"\
"always open documents as new files (use as template).\n";
const char *aCmdLineHelp_bottom =
"-display <display>\n"\
" Specify X-Display to use in Unix/X11 versions.\n"
"-p <documents...>\n"\
" print the specified documents on the default printer.\n"\
"-pt <printer> <documents...>\n"\
" print the specified documents on the specified printer.\n"\
"-view <documents...>\n"\
" open the specified documents in viewer-(readonly-)mode.\n"\
"-show <sxi-document>\n"\
" open the specified presentation and start it immediately\n"\
"-accept=<accept-string>\n"\
" Specify an UNO connect-string to create an UNO acceptor through which\n"\
" other programs can connect to access the API\n"\
"-unaccept=<accept-sring>\n"\
" Close an acceptor that was created with -accept=<accept-string>\n"\
" Use -unnaccept=all to close all open acceptors\n"\
"Remaining arguments will be treated as filenames or URLs of documents to open.\n";
void ReplaceStringHookProc( UniString& rStr );
void displayCmdlineHelp()
{
// if you put variables in other chunks don't forget to call the replace routines
// for those chunks...
String aHelpMessage_head(aCmdLineHelp_head, RTL_TEXTENCODING_ASCII_US);
String aHelpMessage_left(aCmdLineHelp_left, RTL_TEXTENCODING_ASCII_US);
String aHelpMessage_right(aCmdLineHelp_right, RTL_TEXTENCODING_ASCII_US);
String aHelpMessage_bottom(aCmdLineHelp_bottom, RTL_TEXTENCODING_ASCII_US);
ReplaceStringHookProc(aHelpMessage_head);
::rtl::OUString aDefault;
String aVerId( ::utl::Bootstrap::getBuildIdData( aDefault ));
aHelpMessage_head.SearchAndReplaceAscii( "%BUILDID", aVerId );
aHelpMessage_head.SearchAndReplaceAscii( "%CMDNAME", String( "soffice", RTL_TEXTENCODING_ASCII_US) );
#ifdef UNX
// on unix use console for output
fprintf(stderr, "%s\n", ByteString(aHelpMessage_head,
RTL_TEXTENCODING_ASCII_US).GetBuffer());
// merge left and right column
int n = aHelpMessage_left.GetTokenCount ('\n');
ByteString bsLeft(aHelpMessage_left, RTL_TEXTENCODING_ASCII_US);
ByteString bsRight(aHelpMessage_right, RTL_TEXTENCODING_ASCII_US);
for ( int i = 0; i < n; i++ )
{
fprintf(stderr, "%s", bsLeft.GetToken(i, '\n').GetBuffer());
fprintf(stderr, "%s\n", bsRight.GetToken(i, '\n').GetBuffer());
}
fprintf(stderr, "%s", ByteString(aHelpMessage_bottom,
RTL_TEXTENCODING_ASCII_US).GetBuffer());
#else
// rest gets a dialog box
CmdlineHelpDialog aDlg;
aDlg.m_ftHead.SetText(aHelpMessage_head);
aDlg.m_ftLeft.SetText(aHelpMessage_left);
aDlg.m_ftRight.SetText(aHelpMessage_right);
aDlg.m_ftBottom.SetText(aHelpMessage_bottom);
aDlg.Execute();
#endif
}
CmdlineHelpDialog::CmdlineHelpDialog (void)
: ModalDialog( NULL, DesktopResId( DLG_CMDLINEHELP ) )
, m_ftHead( this, DesktopResId( TXT_DLG_CMDLINEHELP_HEADER ) )
, m_ftLeft( this, DesktopResId( TXT_DLG_CMDLINEHELP_LEFT ) )
, m_ftRight( this, DesktopResId( TXT_DLG_CMDLINEHELP_RIGHT ) )
, m_ftBottom( this, DesktopResId( TXT_DLG_CMDLINEHELP_BOTTOM ) )
, m_btOk( this, DesktopResId( BTN_DLG_CMDLINEHELP_OK ) )
{
FreeResource();
}
}
<commit_msg>INTEGRATION: CWS insight01 (1.4.174); FILE MERGED 2004/07/09 13:01:24 oj 1.4.174.1: #i30597# add base to start up<commit_after>/*************************************************************************
*
* $RCSfile: cmdlinehelp.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2004-08-02 14:39:38 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <stdlib.h>
#ifdef UNX
#include <stdio.h>
#endif
#include <sal/types.h>
#include <tools/string.hxx>
#include <vcl/msgbox.hxx>
#include <rtl/bootstrap.hxx>
#include <app.hxx>
#include "desktopresid.hxx"
#include "desktop.hrc"
#include "cmdlinehelp.hxx"
namespace desktop
{
// to be able to display the help nicely in a dialog box with propotional font,
// we need to split it in chunks...
// ___HEAD___
// LEFT RIGHT
// LEFT RIGHT
// LEFT RIGHT
// __BOTTOM__
// [OK]
const char *aCmdLineHelp_head =
"%PRODUCTNAME %PRODUCTVERSION %PRODUCTEXTENSION %BUILDID\n"\
"\n"\
"Usage: %CMDNAME [options] [documents...]\n"\
"\n"\
"Options:\n";
const char *aCmdLineHelp_left =
"-minimized \n"\
"-invisible \n"\
"-norestore \n"\
"-quickstart \n"\
"-nologo \n"\
"-nolockcheck \n"\
"-nodefault \n"\
"-headless \n"\
"-help/-h/-? \n"\
"-writer \n"\
"-calc \n"\
"-draw \n"\
"-impress \n"\
"-base \n"\
"-math \n"\
"-global \n"\
"-web \n"\
"-o \n"\
"-n \n";
const char *aCmdLineHelp_right =
"keep startup bitmap minimized.\n"\
"no startup screen, no default document and no UI.\n"\
"suppress restart/restore after fatal errors.\n"\
"starts the quickstart service\n"\
"don't show startup screen.\n"\
"don't check for remote instances using the installation\n"\
"don't start with an empty document\n"\
"like invisible but no userinteraction at all.\n"\
"show this message and exit.\n"\
"create new text document.\n"\
"create new spreadsheet document.\n"\
"create new drawing.\n"\
"create new presentation.\n"\
"create new database.\n"\
"create new formula.\n"\
"create new global document.\n"\
"create new HTML document.\n"\
"open documents regardless whether they are templates or not.\n"\
"always open documents as new files (use as template).\n";
const char *aCmdLineHelp_bottom =
"-display <display>\n"\
" Specify X-Display to use in Unix/X11 versions.\n"
"-p <documents...>\n"\
" print the specified documents on the default printer.\n"\
"-pt <printer> <documents...>\n"\
" print the specified documents on the specified printer.\n"\
"-view <documents...>\n"\
" open the specified documents in viewer-(readonly-)mode.\n"\
"-show <sxi-document>\n"\
" open the specified presentation and start it immediately\n"\
"-accept=<accept-string>\n"\
" Specify an UNO connect-string to create an UNO acceptor through which\n"\
" other programs can connect to access the API\n"\
"-unaccept=<accept-sring>\n"\
" Close an acceptor that was created with -accept=<accept-string>\n"\
" Use -unnaccept=all to close all open acceptors\n"\
"Remaining arguments will be treated as filenames or URLs of documents to open.\n";
void ReplaceStringHookProc( UniString& rStr );
void displayCmdlineHelp()
{
// if you put variables in other chunks don't forget to call the replace routines
// for those chunks...
String aHelpMessage_head(aCmdLineHelp_head, RTL_TEXTENCODING_ASCII_US);
String aHelpMessage_left(aCmdLineHelp_left, RTL_TEXTENCODING_ASCII_US);
String aHelpMessage_right(aCmdLineHelp_right, RTL_TEXTENCODING_ASCII_US);
String aHelpMessage_bottom(aCmdLineHelp_bottom, RTL_TEXTENCODING_ASCII_US);
ReplaceStringHookProc(aHelpMessage_head);
::rtl::OUString aDefault;
String aVerId( ::utl::Bootstrap::getBuildIdData( aDefault ));
aHelpMessage_head.SearchAndReplaceAscii( "%BUILDID", aVerId );
aHelpMessage_head.SearchAndReplaceAscii( "%CMDNAME", String( "soffice", RTL_TEXTENCODING_ASCII_US) );
#ifdef UNX
// on unix use console for output
fprintf(stderr, "%s\n", ByteString(aHelpMessage_head,
RTL_TEXTENCODING_ASCII_US).GetBuffer());
// merge left and right column
int n = aHelpMessage_left.GetTokenCount ('\n');
ByteString bsLeft(aHelpMessage_left, RTL_TEXTENCODING_ASCII_US);
ByteString bsRight(aHelpMessage_right, RTL_TEXTENCODING_ASCII_US);
for ( int i = 0; i < n; i++ )
{
fprintf(stderr, "%s", bsLeft.GetToken(i, '\n').GetBuffer());
fprintf(stderr, "%s\n", bsRight.GetToken(i, '\n').GetBuffer());
}
fprintf(stderr, "%s", ByteString(aHelpMessage_bottom,
RTL_TEXTENCODING_ASCII_US).GetBuffer());
#else
// rest gets a dialog box
CmdlineHelpDialog aDlg;
aDlg.m_ftHead.SetText(aHelpMessage_head);
aDlg.m_ftLeft.SetText(aHelpMessage_left);
aDlg.m_ftRight.SetText(aHelpMessage_right);
aDlg.m_ftBottom.SetText(aHelpMessage_bottom);
aDlg.Execute();
#endif
}
CmdlineHelpDialog::CmdlineHelpDialog (void)
: ModalDialog( NULL, DesktopResId( DLG_CMDLINEHELP ) )
, m_ftHead( this, DesktopResId( TXT_DLG_CMDLINEHELP_HEADER ) )
, m_ftLeft( this, DesktopResId( TXT_DLG_CMDLINEHELP_LEFT ) )
, m_ftRight( this, DesktopResId( TXT_DLG_CMDLINEHELP_RIGHT ) )
, m_ftBottom( this, DesktopResId( TXT_DLG_CMDLINEHELP_BOTTOM ) )
, m_btOk( this, DesktopResId( BTN_DLG_CMDLINEHELP_OK ) )
{
FreeResource();
}
}
<|endoftext|>
|
<commit_before>/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Grilek
SD%Complete: 100
SDComment:
SDCategory: Zul'Gurub
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "zulgurub.h"
enum Spells
{
SPELL_AVATAR = 24646, // Enrage Spell
SPELL_GROUND_TREMOR = 6524,
SPELL_ENTANGLING_ROOTS = 24648
};
enum Events
{
EVENT_AVATAR = 1,
EVENT_GROUND_TREMOR = 2,
EVENT_START_PURSUIT = 3,
EVENT_ENTANGLING_ROOTS = 4
};
class boss_grilek : public CreatureScript // grilek
{
public:
boss_grilek() : CreatureScript("boss_grilek") { }
struct boss_grilekAI : public BossAI
{
boss_grilekAI(Creature* creature) : BossAI(creature, DATA_EDGE_OF_MADNESS)
{
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
events.ScheduleEvent(EVENT_AVATAR, 20s, 30s);
events.ScheduleEvent(EVENT_GROUND_TREMOR, 15s, 25s);
events.ScheduleEvent(EVENT_ENTANGLING_ROOTS, 5s, 15s);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_AVATAR:
DoCast(me, SPELL_AVATAR);
DoResetThreat();
me->SetReactState(REACT_PASSIVE);
events.ScheduleEvent(EVENT_START_PURSUIT, 2s);
events.ScheduleEvent(EVENT_AVATAR, 45s, 50s);
break;
case EVENT_GROUND_TREMOR:
DoCastVictim(SPELL_GROUND_TREMOR, true);
events.ScheduleEvent(EVENT_GROUND_TREMOR, 12s, 16s);
break;
case EVENT_START_PURSUIT:
me->SetReactState(REACT_AGGRESSIVE);
break;
case EVENT_ENTANGLING_ROOTS:
DoCastVictim(SPELL_ENTANGLING_ROOTS);
events.ScheduleEvent(EVENT_ENTANGLING_ROOTS, 10s, 20s);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetZulGurubAI<boss_grilekAI>(creature);
}
};
void AddSC_boss_grilek()
{
new boss_grilek();
}
<commit_msg>fix(Scripts/ZulGurub): Gri'lek should pursuit random targets. (#12194)<commit_after>/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Grilek
SD%Complete: 100
SDComment:
SDCategory: Zul'Gurub
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "zulgurub.h"
enum Spells
{
SPELL_AVATAR = 24646, // Enrage Spell
SPELL_GROUND_TREMOR = 6524,
SPELL_ENTANGLING_ROOTS = 24648
};
enum Events
{
EVENT_AVATAR = 1,
EVENT_GROUND_TREMOR = 2,
EVENT_START_PURSUIT = 3,
EVENT_STOP_PURSUIT = 4,
EVENT_ENTANGLING_ROOTS = 5
};
class boss_grilek : public CreatureScript // grilek
{
public:
boss_grilek() : CreatureScript("boss_grilek") { }
struct boss_grilekAI : public BossAI
{
boss_grilekAI(Creature* creature) : BossAI(creature, DATA_EDGE_OF_MADNESS)
{
}
void Reset() override
{
_pursuitTargetGUID.Clear();
BossAI::Reset();
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
events.ScheduleEvent(EVENT_AVATAR, 20s, 30s);
events.ScheduleEvent(EVENT_GROUND_TREMOR, 15s, 25s);
events.ScheduleEvent(EVENT_ENTANGLING_ROOTS, 5s, 15s);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_AVATAR:
if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0))
{
_pursuitTargetGUID = target->GetGUID();
}
DoCast(me, SPELL_AVATAR);
me->SetReactState(REACT_PASSIVE);
DoResetThreat();
events.ScheduleEvent(EVENT_START_PURSUIT, 2s);
events.ScheduleEvent(EVENT_STOP_PURSUIT, 15s);
events.ScheduleEvent(EVENT_AVATAR, 45s, 50s);
break;
case EVENT_GROUND_TREMOR:
DoCastVictim(SPELL_GROUND_TREMOR, true);
events.ScheduleEvent(EVENT_GROUND_TREMOR, 12s, 16s);
break;
case EVENT_START_PURSUIT:
me->SetReactState(REACT_AGGRESSIVE);
if (Unit* pursuitTarget = ObjectAccessor::GetUnit(*me, _pursuitTargetGUID))
{
me->GetThreatMgr().addThreat(pursuitTarget, 1000000.f);
}
break;
case EVENT_STOP_PURSUIT:
if (Unit* pursuitTarget = ObjectAccessor::GetUnit(*me, _pursuitTargetGUID))
{
_pursuitTargetGUID.Clear();
me->GetThreatMgr().addThreat(pursuitTarget, -1000000.f);
}
break;
case EVENT_ENTANGLING_ROOTS:
DoCastVictim(SPELL_ENTANGLING_ROOTS);
events.ScheduleEvent(EVENT_ENTANGLING_ROOTS, 10s, 20s);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
ObjectGuid _pursuitTargetGUID;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetZulGurubAI<boss_grilekAI>(creature);
}
};
void AddSC_boss_grilek()
{
new boss_grilek();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: updatesvc.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2003-03-19 16:18:49 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2002 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONFIGMGR_BACKEND_UPDATESVC_HXX
#define CONFIGMGR_BACKEND_UPDATESVC_HXX
#ifndef CONFIGMGR_SERVICEINFOHELPER_HXX_
#include "serviceinfohelper.hxx"
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#include <drafts/com/sun/star/configuration/backend/XUpdateHandler.hpp>
// -----------------------------------------------------------------------------
namespace drafts {
namespace com { namespace sun { namespace star { namespace configuration { namespace backend {
class XLayerHandler;
class XLayer;
} } } } }
}
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace backend
{
// -----------------------------------------------------------------------------
using rtl::OUString;
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
namespace backenduno = drafts::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------
class UpdateService : public ::cppu::WeakImplHelper3<
lang::XInitialization,
lang::XServiceInfo,
backenduno::XUpdateHandler
>
{
public:
typedef uno::Reference< uno::XComponentContext > const & CreationArg;
explicit
UpdateService(CreationArg _xContext);
// XInitialization
virtual void SAL_CALL
initialize( const uno::Sequence< uno::Any >& aArguments )
throw (uno::Exception, uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL
getImplementationName( )
throw (uno::RuntimeException);
virtual sal_Bool SAL_CALL
supportsService( const ::rtl::OUString& ServiceName )
throw (uno::RuntimeException);
virtual uno::Sequence< ::rtl::OUString > SAL_CALL
getSupportedServiceNames( )
throw (uno::RuntimeException);
protected:
typedef uno::Reference< lang::XMultiServiceFactory > ServiceFactory;
typedef uno::Reference< backenduno::XLayer > Layer;
ServiceFactory getServiceFactory() const
{ return m_xServiceFactory; }
void checkSourceLayer() SAL_THROW( (lang::IllegalAccessException) )
{ validateSourceLayerAndCheckNotEmpty(); }
Layer getSourceLayer() SAL_THROW( (lang::IllegalAccessException) );
void writeUpdatedLayer(Layer const & _xLayer);
virtual sal_Bool setImplementationProperty(OUString const & aName, uno::Any const & aValue);
void raiseIllegalAccessException(sal_Char const * pMsg)
SAL_THROW( (lang::IllegalAccessException) );
private:
bool validateSourceLayerAndCheckNotEmpty() SAL_THROW( (lang::IllegalAccessException) );
private:
typedef uno::Reference< backenduno::XLayerHandler > LayerWriter;
ServiceFactory m_xServiceFactory;
Layer m_xSourceLayer;
LayerWriter m_xLayerWriter;
enum { merge, truncate, protect } m_aSourceMode;
static ServiceInfoHelper getServiceInfo();
};
// -----------------------------------------------------------------------------
} // namespace xml
// -----------------------------------------------------------------------------
} // namespace configmgr
#endif
<commit_msg>INTEGRATION: CWS configapi01 (1.5.10); FILE MERGED 2003/04/10 15:47:13 jb 1.5.10.1: #1077715# Move configuration backend API out of drafts; adjust to API changes<commit_after>/*************************************************************************
*
* $RCSfile: updatesvc.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2003-04-17 13:20:45 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2002 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONFIGMGR_BACKEND_UPDATESVC_HXX
#define CONFIGMGR_BACKEND_UPDATESVC_HXX
#ifndef CONFIGMGR_SERVICEINFOHELPER_HXX_
#include "serviceinfohelper.hxx"
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XUPDATEHANDLER_HPP_
#include <com/sun/star/configuration/backend/XUpdateHandler.hpp>
#endif
// -----------------------------------------------------------------------------
namespace com { namespace sun { namespace star { namespace configuration { namespace backend {
class XLayerHandler;
class XLayer;
} } } } }
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace backend
{
// -----------------------------------------------------------------------------
using rtl::OUString;
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
namespace backenduno = ::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------
class UpdateService : public ::cppu::WeakImplHelper3<
lang::XInitialization,
lang::XServiceInfo,
backenduno::XUpdateHandler
>
{
public:
typedef uno::Reference< uno::XComponentContext > const & CreationArg;
explicit
UpdateService(CreationArg _xContext);
// XInitialization
virtual void SAL_CALL
initialize( const uno::Sequence< uno::Any >& aArguments )
throw (uno::Exception, uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL
getImplementationName( )
throw (uno::RuntimeException);
virtual sal_Bool SAL_CALL
supportsService( const ::rtl::OUString& ServiceName )
throw (uno::RuntimeException);
virtual uno::Sequence< ::rtl::OUString > SAL_CALL
getSupportedServiceNames( )
throw (uno::RuntimeException);
protected:
typedef uno::Reference< lang::XMultiServiceFactory > ServiceFactory;
typedef uno::Reference< backenduno::XLayer > Layer;
ServiceFactory getServiceFactory() const
{ return m_xServiceFactory; }
void checkSourceLayer() SAL_THROW( (lang::IllegalAccessException) )
{ validateSourceLayerAndCheckNotEmpty(); }
Layer getSourceLayer() SAL_THROW( (lang::IllegalAccessException) );
void writeUpdatedLayer(Layer const & _xLayer);
virtual sal_Bool setImplementationProperty(OUString const & aName, uno::Any const & aValue);
void raiseIllegalAccessException(sal_Char const * pMsg)
SAL_THROW( (lang::IllegalAccessException) );
private:
bool validateSourceLayerAndCheckNotEmpty() SAL_THROW( (lang::IllegalAccessException) );
private:
typedef uno::Reference< backenduno::XLayerHandler > LayerWriter;
ServiceFactory m_xServiceFactory;
Layer m_xSourceLayer;
LayerWriter m_xLayerWriter;
enum { merge, truncate, protect } m_aSourceMode;
static ServiceInfoHelper getServiceInfo();
};
// -----------------------------------------------------------------------------
} // namespace xml
// -----------------------------------------------------------------------------
} // namespace configmgr
#endif
<|endoftext|>
|
<commit_before>#include <fstream>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <stdint.h>
#include <cstring>
#include <list>
#include <cmath>
#define FILE_MARKER "\xF0\xE1"
#define FILE_VERSION "fpcl.00001" // increment this number file format change !
std::stringstream *linestream;
std::string token = "";
const char *filename;
// return float from linestream
inline float getFloat() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
return atof(token.c_str());
}
// return unsigned long from linestream
inline float getUlong() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
return strtoul(token.c_str(),NULL,0);
}
// skip value from linestream
inline float skip() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
}
int main(int argc, char **argv) {
std::string line = "";
unsigned int index;
float depth, theta, phi, mn95_x, mn95_y, mn95_z;
int lon, lat;
float r=150.0; // webgl sphere radius
float fx,fy,fz;
std::list<uint32_t> sector[360][180];
float step=M_PI/180.0;
uint32_t point_index=0;
unsigned long nb_points=0;
if (argc!=2) {
std::cerr << "usage: " << argv[0] << " <json_file>" << std::endl ;
return 1;
}
// open json
filename=argv[1];
std::ifstream fs(filename);
if (!fs.is_open()) {
std::cerr << "could not open " << filename << std::endl ;
return 1;
}
// extract "nb_points" from json
while (getline(fs, line)) {
if (const char *pos=strstr(line.c_str(),"nb_points")) {
nb_points=strtoul(strchr(pos,':')+1,NULL,0);
break;
}
}
if (!nb_points) {
std::cerr << "error: could not parse" << filename << std::endl ;
return 1;
}
// remove input filename extension
std::string fname=std::string(filename);
fname.erase(fname.find_last_of("."),std::string::npos);
// create .bin output file
std::string outfname=fname+".bin";
std::ofstream outf;
outf.open(outfname.c_str());
if (!outf.is_open()) {
std::cerr << "could not open " << outfname << std::endl ;
return 1;
}
std::cerr << filename << ": parsing " << nb_points << " points" << std::endl;
// 1. parse lines beginning with [0-9] as a csv formatted as:
// "depth, index, theta, phi, mn95-x, mn95-y, mn95-z" (floats)
// 2. store cartesian coordinates in "sector" array as:
// float x, float y, float z
float *mn95=new float[nb_points*3];
float *positions=new float[nb_points*3];
while (getline(fs, line)) {
// skip line not beginning with [0-9]
if (line[0]<'0' || line[0]>'9') continue;
if (point_index>= nb_points) {
std::cerr << filename << ": error: nb_points is invalid ! " << std::endl;
return 1;
}
// read line
linestream=new std::stringstream(line);
// extract fields
depth=getFloat();
index=getUlong();
theta=getFloat();
phi=getFloat();
mn95_x=getFloat();
mn95_y=getFloat();
mn95_z=getFloat();
// compute sector location
lon=((int)round(theta/step)+180)%360;
lat=round(phi/step);
if (lat<0) lat+=180;
lat=(180-lat)%180;
// reference particle in sector lon,lat
sector[lon][lat].push_back(point_index);
// compute cartesian webgl coordinates
phi=(phi-M_PI/2);
theta=theta-M_PI/2;
fx=depth*sin(phi)*cos(theta);
fz=depth*sin(phi)*sin(theta);
fy=-depth*cos(phi);
// store cartesian coordinates
unsigned long k=point_index*3;
positions[k]=fx;
positions[k+1]=fy;
positions[k+2]=fz;
// store mn95 coordinates
mn95[k]=mn95_x;
mn95[k+1]=mn95_y;
mn95[k+2]=mn95_z;
++point_index;
}
if (point_index!=nb_points) {
std::cerr << filename << ": error: nb_points is invalid !" << std::endl;
return 1;
}
// output file marker and version number
outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
outf.write((char*)FILE_VERSION,strlen(FILE_VERSION));
std::cerr << filename << ": converting to file version " << FILE_VERSION << std::endl;
long int data_offset=outf.tellp();
// output positions formatted as list of x,y,z for each [lon][lat] pair
// and prepare a 360x180 array index formatted as offset,count
std::list<uint32_t> array_index;
for (lat=0; lat<180; ++lat) {
for (lon=0; lon<360; ++lon) {
std::list<uint32_t> *_sector=§or[lon][lat];
// update array index
uint32_t particle_count=_sector->size();
if (particle_count) {
// particles in this sector: store offset and particle count
array_index.push_back((outf.tellp()-data_offset)/sizeof(fx));
array_index.push_back(particle_count);
} else {
// no particles here
array_index.push_back(0);
array_index.push_back(0);
continue;
}
// output particle positions for sector[lon][lat]
for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
uint32_t index=*it;
outf.write((char*)&positions[index],sizeof(*positions)*3);
}
}
}
// check integrity
unsigned long positions_byteCount=outf.tellp()-data_offset;
int failure=(positions_byteCount/nb_points!=sizeof(*positions)*3);
std::cerr << filename << ": positions -> " << positions_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
if (failure) {
return 1;
}
// output mn95 coordinates
for (lat=0; lat<180; ++lat) {
for (lon=0; lon<360; ++lon) {
std::list<uint32_t> *_sector=§or[lon][lat];
if (!_sector->size()) {
continue;
}
// output mn95 positions for sector[lon][lat]
for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
uint32_t index=*it;
outf.write((char*)&mn95[index],sizeof(*mn95)*3);
}
}
}
// check integrity
long unsigned int mn95_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount;
failure=(mn95_byteCount!=positions_byteCount);
std::cerr << filename << ": mn95 -> " << mn95_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
if (failure) {
return 1;
}
// output index formatted as:
// offset, particle_count
for (std::list<uint32_t>::iterator it=array_index.begin(); it!=array_index.end(); ++it) {
uint32_t value=*it;
outf.write((char*)&value,sizeof(value));
}
// check integrity
flush(outf);
long unsigned int index_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount-mn95_byteCount;
failure=(index_byteCount%4);
std::cerr << filename << ": index -> " << index_byteCount << " bytes" << ((index_byteCount%4)?" -> not a multiple of 4 !":"") << std::endl;
if (failure) {
return 1;
}
outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
outf.close();
if (mn95_byteCount!=positions_byteCount) {
std::cerr << "error: mn95_byteCount != positions_byteCount ! " << std::endl;
return 1;
}
return 0;
}
<commit_msg>json2bin.cpp: fix index<commit_after>#include <fstream>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <stdint.h>
#include <cstring>
#include <list>
#include <cmath>
#define FILE_MARKER "\xF0\xE1"
#define FILE_VERSION "fpcl.00001" // increment this number file format change !
std::stringstream *linestream;
std::string token = "";
const char *filename;
// return float from linestream
inline float getFloat() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
return atof(token.c_str());
}
// return unsigned long from linestream
inline float getUlong() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
return strtoul(token.c_str(),NULL,0);
}
// skip value from linestream
inline float skip() {
if (!getline(*linestream, token, ',')) {
std::cerr << "error: could not parse " << filename << std::endl ;
exit(1);
}
}
int main(int argc, char **argv) {
std::string line = "";
unsigned int index;
float depth, theta, phi, mn95_x, mn95_y, mn95_z;
int lon, lat;
float r=150.0; // webgl sphere radius
float fx,fy,fz;
std::list<uint32_t> sector[360][180];
float step=M_PI/180.0;
uint32_t point_index=0;
unsigned long nb_points=0;
if (argc!=2) {
std::cerr << "usage: " << argv[0] << " <json_file>" << std::endl ;
return 1;
}
// open json
filename=argv[1];
std::ifstream fs(filename);
if (!fs.is_open()) {
std::cerr << "could not open " << filename << std::endl ;
return 1;
}
// extract "nb_points" from json
while (getline(fs, line)) {
if (const char *pos=strstr(line.c_str(),"nb_points")) {
nb_points=strtoul(strchr(pos,':')+1,NULL,0);
break;
}
}
if (!nb_points) {
std::cerr << "error: could not parse" << filename << std::endl ;
return 1;
}
// remove input filename extension
std::string fname=std::string(filename);
fname.erase(fname.find_last_of("."),std::string::npos);
// create .bin output file
std::string outfname=fname+".bin";
std::ofstream outf;
outf.open(outfname.c_str());
if (!outf.is_open()) {
std::cerr << "could not open " << outfname << std::endl ;
return 1;
}
std::cerr << filename << ": parsing " << nb_points << " points" << std::endl;
// 1. parse lines beginning with [0-9] as a csv formatted as:
// "depth, index, theta, phi, mn95-x, mn95-y, mn95-z" (floats)
// 2. store cartesian coordinates in "sector" array as:
// float x, float y, float z
float *mn95=new float[nb_points*3];
float *positions=new float[nb_points*3];
while (getline(fs, line)) {
// skip line not beginning with [0-9]
if (line[0]<'0' || line[0]>'9') continue;
if (point_index>= nb_points) {
std::cerr << filename << ": error: nb_points is invalid ! " << std::endl;
return 1;
}
// read line
linestream=new std::stringstream(line);
// extract fields
depth=getFloat();
index=getUlong();
theta=getFloat();
phi=getFloat();
mn95_x=getFloat();
mn95_y=getFloat();
mn95_z=getFloat();
// compute sector location
lon=((int)round(theta/step)+180)%360;
lat=round(phi/step);
if (lat<0) lat+=180;
lat=(180-lat)%180;
// reference particle in sector lon,lat
unsigned long k=point_index*3;
sector[lon][lat].push_back(k);
// compute cartesian webgl coordinates
phi=(phi-M_PI/2);
theta=theta-M_PI/2;
fx=depth*sin(phi)*cos(theta);
fz=depth*sin(phi)*sin(theta);
fy=-depth*cos(phi);
// store cartesian coordinates
positions[k]=fx;
positions[k+1]=fy;
positions[k+2]=fz;
// store mn95 coordinates
mn95[k]=mn95_x;
mn95[k+1]=mn95_y;
mn95[k+2]=mn95_z;
++point_index;
}
if (point_index!=nb_points) {
std::cerr << filename << ": error: nb_points is invalid !" << std::endl;
return 1;
}
// output file marker and version number
outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
outf.write((char*)FILE_VERSION,strlen(FILE_VERSION));
std::cerr << filename << ": converting to file version " << FILE_VERSION << std::endl;
long int data_offset=outf.tellp();
// output positions formatted as list of x,y,z for each [lon][lat] pair
// and prepare a 360x180 array index formatted as offset,count
std::list<uint32_t> array_index;
for (lat=0; lat<180; ++lat) {
for (lon=0; lon<360; ++lon) {
std::list<uint32_t> *_sector=§or[lon][lat];
// update array index
uint32_t particle_count=_sector->size();
if (particle_count) {
// particles in this sector: store offset and particle count
array_index.push_back((outf.tellp()-data_offset)/sizeof(fx));
array_index.push_back(particle_count);
} else {
// no particles here
array_index.push_back(0);
array_index.push_back(0);
continue;
}
// output particle positions for sector[lon][lat]
for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
uint32_t index=*it;
outf.write((char*)&positions[index],sizeof(*positions)*3);
}
}
}
// check integrity
unsigned long positions_byteCount=outf.tellp()-data_offset;
int failure=(positions_byteCount/nb_points!=sizeof(*positions)*3);
std::cerr << filename << ": positions -> " << positions_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
if (failure) {
return 1;
}
// output mn95 coordinates
for (lat=0; lat<180; ++lat) {
for (lon=0; lon<360; ++lon) {
std::list<uint32_t> *_sector=§or[lon][lat];
if (!_sector->size()) {
continue;
}
// output mn95 positions for sector[lon][lat]
for (std::list<uint32_t>::iterator it=_sector->begin(); it!=_sector->end(); ++it) {
uint32_t index=*it;
outf.write((char*)&mn95[index],sizeof(*mn95)*3);
}
}
}
// check integrity
long unsigned int mn95_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount;
failure=(mn95_byteCount!=positions_byteCount);
std::cerr << filename << ": mn95 -> " << mn95_byteCount << " bytes" << (failure?" -> Invalid count !":"") << std::endl;
if (failure) {
return 1;
}
// output index formatted as:
// offset, particle_count
for (std::list<uint32_t>::iterator it=array_index.begin(); it!=array_index.end(); ++it) {
uint32_t value=*it;
outf.write((char*)&value,sizeof(value));
}
// check integrity
flush(outf);
long unsigned int index_byteCount=(unsigned long)outf.tellp()-data_offset-positions_byteCount-mn95_byteCount;
failure=(index_byteCount%4);
std::cerr << filename << ": index -> " << index_byteCount << " bytes" << ((index_byteCount%4)?" -> not a multiple of 4 !":"") << std::endl;
if (failure) {
return 1;
}
outf.write((char*)FILE_MARKER,strlen(FILE_MARKER));
outf.close();
if (mn95_byteCount!=positions_byteCount) {
std::cerr << "error: mn95_byteCount != positions_byteCount ! " << std::endl;
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <cybozu/test.hpp>
#include <cybozu/zlib.hpp>
#include <cybozu/file.hpp>
#include <cybozu/stream.hpp>
#include <cybozu/serializer.hpp>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
CYBOZU_TEST_AUTO(test1_deflate)
{
typedef cybozu::ZlibCompressorT<std::stringstream> Compressor;
typedef cybozu::ZlibDecompressorT<std::stringstream> Decompressor;
const std::string in = "this is a pen";
std::stringstream os;
{
Compressor comp(os);
comp.write(in.c_str(), in.size());
comp.flush();
}
const std::string enc = os.str();
const char encTbl[] = "\x78\x9c\x2b\xc9\xc8\x2c\x56\x00\xa2\x44\x85\x82\xd4\x3c\x00\x21\x0c\x04\x99";
const std::string encOk(encTbl, encTbl + sizeof(encTbl) - 1);
CYBOZU_TEST_EQUAL(enc, encOk);
std::stringstream is;
is << encOk;
{
Decompressor dec(is);
char buf[2048];
std::string out;
for (;;) {
size_t size = dec.read(buf, sizeof(buf));
if (size == 0) break;
out.append(buf, buf + size);
}
CYBOZU_TEST_EQUAL(in, out);
}
}
CYBOZU_TEST_AUTO(test2_deflate)
{
typedef cybozu::ZlibCompressorT<std::stringstream, 1> Compressor;
typedef cybozu::ZlibDecompressorT<std::stringstream, 1> Decompressor;
const std::string in = "this is a pen";
std::stringstream os;
{
Compressor comp(os);
for (size_t i = 0; i < in.size(); i++) {
comp.write(&in[i], 1);
}
comp.flush();
}
const std::string enc = os.str();
const char encTbl[] = "\x78\x9c\x2b\xc9\xc8\x2c\x56\x00\xa2\x44\x85\x82\xd4\x3c\x00\x21\x0c\x04\x99";
const std::string encOk(encTbl, encTbl + sizeof(encTbl) - 1);
CYBOZU_TEST_EQUAL(enc, encOk);
std::stringstream is;
is << encOk;
{
Decompressor dec(is);
char buf[2048];
std::string out;
for (;;) {
size_t size = dec.read(buf, sizeof(buf));
if (size == 0) break;
out.append(buf, buf + size);
}
CYBOZU_TEST_EQUAL(in, out);
}
}
CYBOZU_TEST_AUTO(enc_and_dec)
{
std::string body = "From: cybozu\r\n"
"To: cybozu\r\n"
"\r\n"
"hello with zlib compressed\r\n"
".\r\n";
std::stringstream ss;
cybozu::ZlibCompressorT<std::stringstream> comp(ss);
comp.write(&body[0], body.size());
comp.flush();
std::string enc = ss.str();
cybozu::StringInputStream ims(enc);
cybozu::ZlibDecompressorT<cybozu::StringInputStream> dec(ims);
char buf[4096];
size_t size = dec.read(buf, sizeof(buf));
std::string decStr(buf, buf + size);
CYBOZU_TEST_EQUAL(body, decStr);
}
CYBOZU_TEST_AUTO(output_gzip1)
{
std::string str = "Only a test, test, test, test, test, test, test, test!\n";
std::stringstream ss;
cybozu::ZlibCompressorT<std::stringstream> comp(ss, true);
comp.write(&str[0], str.size());
comp.flush();
std::string enc = ss.str();
{
cybozu::ZlibDecompressorT<std::stringstream> dec(ss, true);
char buf[4096];
size_t size = dec.read(buf, sizeof(buf));
std::string decStr(buf, buf + size);
CYBOZU_TEST_EQUAL(decStr, str);
}
{
cybozu::StringInputStream is(enc);
cybozu::ZlibDecompressorT<cybozu::StringInputStream> dec(is, true);
char buf[4096];
size_t size = dec.read(buf, sizeof(buf));
std::string decStr(buf, buf + size);
CYBOZU_TEST_EQUAL(decStr, str);
}
}
#ifdef _MSC_VER
#pragma warning(disable : 4309)
#endif
CYBOZU_TEST_AUTO(output_gzip2)
{
const uint8_t textBufTbl[] = {
0x23, 0x69, 0x6E, 0x63, 0x6C, 0x75, 0x64, 0x65, 0x20, 0x3C, 0x73, 0x74, 0x64, 0x69, 0x6F, 0x2E,
0x68, 0x3E, 0x0A, 0x0A, 0x69, 0x6E, 0x74, 0x20, 0x6D, 0x61, 0x69, 0x6E, 0x28, 0x29, 0x0A, 0x7B,
0x0A, 0x09, 0x70, 0x75, 0x74, 0x73, 0x28, 0x22, 0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x22, 0x29, 0x3B,
0x0A, 0x09, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x20, 0x30, 0x3B, 0x0A, 0x7D, 0x0A, 0x0A,
};
const uint8_t encBufTbl[] = {
0x1F, 0x8B, 0x08, 0x08, 0xA4, 0x7E, 0x20, 0x4B, 0x00, 0x03, 0x74, 0x2E, 0x63, 0x70, 0x70, 0x00,
0x53, 0xCE, 0xCC, 0x4B, 0xCE, 0x29, 0x4D, 0x49, 0x55, 0xB0, 0x29, 0x2E, 0x49, 0xC9, 0xCC, 0xD7,
0xCB, 0xB0, 0xE3, 0xE2, 0xCA, 0xCC, 0x2B, 0x51, 0xC8, 0x4D, 0xCC, 0xCC, 0xD3, 0xD0, 0xE4, 0xAA,
0xE6, 0xE2, 0x2C, 0x28, 0x2D, 0x29, 0xD6, 0x50, 0xCA, 0x48, 0xCD, 0xC9, 0xC9, 0x57, 0xD2, 0xB4,
0xE6, 0xE2, 0x2C, 0x4A, 0x2D, 0x29, 0x2D, 0xCA, 0x53, 0x30, 0xB0, 0xE6, 0xAA, 0xE5, 0xE2, 0x02,
0x00, 0x48, 0xAB, 0x48, 0x61, 0x3F, 0x00, 0x00, 0x00,
};
const char *const textBuf = cybozu::cast<const char*>(textBufTbl);
const char *const encBuf = cybozu::cast<const char*>(encBufTbl);
const std::string text(textBuf, textBuf + sizeof(textBufTbl));
{
std::stringstream ss;
ss.write(encBuf, sizeof(encBufTbl));
cybozu::ZlibDecompressorT<std::stringstream> dec(ss, true);
char buf[4096];
size_t size = dec.read(buf, sizeof(buf));
std::string decStr(buf, buf + size);
CYBOZU_TEST_EQUAL(decStr, text);
}
}
CYBOZU_TEST_AUTO(serializer)
{
typedef std::map<int, double> Map;
Map m, mm;
for (int i = 0; i < 100; i++) {
m[i * i] = (i + i * i) / 3.42;
}
std::stringstream ss;
{
cybozu::ZlibCompressorT<std::stringstream> enc(ss);
cybozu::save(ss, m);
}
{
cybozu::ZlibDecompressorT<std::stringstream> dec(ss);
cybozu::load(mm, ss);
}
CYBOZU_TEST_EQUAL(m.size(), mm.size());
for (Map::const_iterator i = m.begin(), ie = m.end(), j = mm.begin(); i != ie; ++i, ++j) {
CYBOZU_TEST_EQUAL(i->first, j->first);
CYBOZU_TEST_EQUAL(i->second, j->second);
}
}<commit_msg>fix to use zlib<commit_after>#include <cybozu/test.hpp>
#include <cybozu/zlib.hpp>
#include <cybozu/file.hpp>
#include <cybozu/stream.hpp>
#include <cybozu/serializer.hpp>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
CYBOZU_TEST_AUTO(test1_deflate)
{
typedef cybozu::ZlibCompressorT<std::stringstream> Compressor;
typedef cybozu::ZlibDecompressorT<std::stringstream> Decompressor;
const std::string in = "this is a pen";
std::stringstream os;
{
Compressor comp(os);
comp.write(in.c_str(), in.size());
comp.flush();
}
const std::string enc = os.str();
const char encTbl[] = "\x78\x9c\x2b\xc9\xc8\x2c\x56\x00\xa2\x44\x85\x82\xd4\x3c\x00\x21\x0c\x04\x99";
const std::string encOk(encTbl, encTbl + sizeof(encTbl) - 1);
CYBOZU_TEST_EQUAL(enc, encOk);
std::stringstream is;
is << encOk;
{
Decompressor dec(is);
char buf[2048];
std::string out;
for (;;) {
size_t size = dec.read(buf, sizeof(buf));
if (size == 0) break;
out.append(buf, buf + size);
}
CYBOZU_TEST_EQUAL(in, out);
}
}
CYBOZU_TEST_AUTO(test2_deflate)
{
typedef cybozu::ZlibCompressorT<std::stringstream, 1> Compressor;
typedef cybozu::ZlibDecompressorT<std::stringstream, 1> Decompressor;
const std::string in = "this is a pen";
std::stringstream os;
{
Compressor comp(os);
for (size_t i = 0; i < in.size(); i++) {
comp.write(&in[i], 1);
}
comp.flush();
}
const std::string enc = os.str();
const char encTbl[] = "\x78\x9c\x2b\xc9\xc8\x2c\x56\x00\xa2\x44\x85\x82\xd4\x3c\x00\x21\x0c\x04\x99";
const std::string encOk(encTbl, encTbl + sizeof(encTbl) - 1);
CYBOZU_TEST_EQUAL(enc, encOk);
std::stringstream is;
is << encOk;
{
Decompressor dec(is);
char buf[2048];
std::string out;
for (;;) {
size_t size = dec.read(buf, sizeof(buf));
if (size == 0) break;
out.append(buf, buf + size);
}
CYBOZU_TEST_EQUAL(in, out);
}
}
CYBOZU_TEST_AUTO(enc_and_dec)
{
std::string body = "From: cybozu\r\n"
"To: cybozu\r\n"
"\r\n"
"hello with zlib compressed\r\n"
".\r\n";
std::stringstream ss;
cybozu::ZlibCompressorT<std::stringstream> comp(ss);
comp.write(&body[0], body.size());
comp.flush();
std::string enc = ss.str();
cybozu::StringInputStream ims(enc);
cybozu::ZlibDecompressorT<cybozu::StringInputStream> dec(ims);
char buf[4096];
size_t size = dec.read(buf, sizeof(buf));
std::string decStr(buf, buf + size);
CYBOZU_TEST_EQUAL(body, decStr);
}
CYBOZU_TEST_AUTO(output_gzip1)
{
std::string str = "Only a test, test, test, test, test, test, test, test!\n";
std::stringstream ss;
cybozu::ZlibCompressorT<std::stringstream> comp(ss, true);
comp.write(&str[0], str.size());
comp.flush();
std::string enc = ss.str();
{
cybozu::ZlibDecompressorT<std::stringstream> dec(ss, true);
char buf[4096];
size_t size = dec.read(buf, sizeof(buf));
std::string decStr(buf, buf + size);
CYBOZU_TEST_EQUAL(decStr, str);
}
{
cybozu::StringInputStream is(enc);
cybozu::ZlibDecompressorT<cybozu::StringInputStream> dec(is, true);
char buf[4096];
size_t size = dec.read(buf, sizeof(buf));
std::string decStr(buf, buf + size);
CYBOZU_TEST_EQUAL(decStr, str);
}
}
#ifdef _MSC_VER
#pragma warning(disable : 4309)
#endif
CYBOZU_TEST_AUTO(output_gzip2)
{
const uint8_t textBufTbl[] = {
0x23, 0x69, 0x6E, 0x63, 0x6C, 0x75, 0x64, 0x65, 0x20, 0x3C, 0x73, 0x74, 0x64, 0x69, 0x6F, 0x2E,
0x68, 0x3E, 0x0A, 0x0A, 0x69, 0x6E, 0x74, 0x20, 0x6D, 0x61, 0x69, 0x6E, 0x28, 0x29, 0x0A, 0x7B,
0x0A, 0x09, 0x70, 0x75, 0x74, 0x73, 0x28, 0x22, 0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x22, 0x29, 0x3B,
0x0A, 0x09, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x20, 0x30, 0x3B, 0x0A, 0x7D, 0x0A, 0x0A,
};
const uint8_t encBufTbl[] = {
0x1F, 0x8B, 0x08, 0x08, 0xA4, 0x7E, 0x20, 0x4B, 0x00, 0x03, 0x74, 0x2E, 0x63, 0x70, 0x70, 0x00,
0x53, 0xCE, 0xCC, 0x4B, 0xCE, 0x29, 0x4D, 0x49, 0x55, 0xB0, 0x29, 0x2E, 0x49, 0xC9, 0xCC, 0xD7,
0xCB, 0xB0, 0xE3, 0xE2, 0xCA, 0xCC, 0x2B, 0x51, 0xC8, 0x4D, 0xCC, 0xCC, 0xD3, 0xD0, 0xE4, 0xAA,
0xE6, 0xE2, 0x2C, 0x28, 0x2D, 0x29, 0xD6, 0x50, 0xCA, 0x48, 0xCD, 0xC9, 0xC9, 0x57, 0xD2, 0xB4,
0xE6, 0xE2, 0x2C, 0x4A, 0x2D, 0x29, 0x2D, 0xCA, 0x53, 0x30, 0xB0, 0xE6, 0xAA, 0xE5, 0xE2, 0x02,
0x00, 0x48, 0xAB, 0x48, 0x61, 0x3F, 0x00, 0x00, 0x00,
};
const char *const textBuf = cybozu::cast<const char*>(textBufTbl);
const char *const encBuf = cybozu::cast<const char*>(encBufTbl);
const std::string text(textBuf, textBuf + sizeof(textBufTbl));
{
std::stringstream ss;
ss.write(encBuf, sizeof(encBufTbl));
cybozu::ZlibDecompressorT<std::stringstream> dec(ss, true);
char buf[4096];
size_t size = dec.read(buf, sizeof(buf));
std::string decStr(buf, buf + size);
CYBOZU_TEST_EQUAL(decStr, text);
}
}
CYBOZU_TEST_AUTO(serializer)
{
typedef std::map<int, double> Map;
Map m, mm;
for (int i = 0; i < 100; i++) {
m[i * i] = (i + i * i) / 3.42;
}
std::stringstream ss;
{
cybozu::ZlibCompressorT<std::stringstream> enc(ss);
cybozu::save(enc, m);
}
{
cybozu::ZlibDecompressorT<std::stringstream> dec(ss);
cybozu::load(mm, dec);
}
CYBOZU_TEST_EQUAL(m.size(), mm.size());
for (Map::const_iterator i = m.begin(), ie = m.end(), j = mm.begin(); i != ie; ++i, ++j) {
CYBOZU_TEST_EQUAL(i->first, j->first);
CYBOZU_TEST_EQUAL(i->second, j->second);
}
}<|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/child/npapi/np_channel_base.h"
#include "base/auto_reset.h"
#include "base/containers/hash_tables.h"
#include "base/lazy_instance.h"
#include "base/strings/string_number_conversions.h"
#include "base/threading/thread_local.h"
#include "ipc/ipc_sync_message.h"
#if defined(OS_POSIX)
#include "ipc/ipc_channel_posix.h"
#endif
namespace content {
namespace {
typedef base::hash_map<std::string, scoped_refptr<NPChannelBase> > ChannelMap;
struct ChannelGlobals {
ChannelMap channel_map;
scoped_refptr<NPChannelBase> current_channel;
};
#if defined(OS_ANDROID)
// Workaround for http://crbug.com/298179 - NPChannelBase is only intended
// for use on one thread per process. Using TLS to store the globals removes the
// worst thread hostility in this class, especially needed for webview which
// runs in single-process mode. TODO(joth): Make a complete fix, most likely
// as part of addressing http://crbug.com/258510.
base::LazyInstance<base::ThreadLocalPointer<ChannelGlobals> >::Leaky
g_channels_tls_ptr = LAZY_INSTANCE_INITIALIZER;
ChannelGlobals* GetChannelGlobals() {
ChannelGlobals* globals = g_channels_tls_ptr.Get().Get();
if (!globals) {
globals = new ChannelGlobals;
g_channels_tls_ptr.Get().Set(globals);
}
return globals;
}
#else
base::LazyInstance<ChannelGlobals>::Leaky g_channels_globals =
LAZY_INSTANCE_INITIALIZER;
ChannelGlobals* GetChannelGlobals() { return g_channels_globals.Pointer(); }
#endif // OS_ANDROID
ChannelMap* GetChannelMap() {
return &GetChannelGlobals()->channel_map;
}
} // namespace
NPChannelBase* NPChannelBase::GetChannel(
const IPC::ChannelHandle& channel_handle, IPC::Channel::Mode mode,
ChannelFactory factory, base::MessageLoopProxy* ipc_message_loop,
bool create_pipe_now, base::WaitableEvent* shutdown_event) {
scoped_refptr<NPChannelBase> channel;
std::string channel_key = channel_handle.name;
ChannelMap::const_iterator iter = GetChannelMap()->find(channel_key);
if (iter == GetChannelMap()->end()) {
channel = factory();
} else {
channel = iter->second;
}
DCHECK(channel.get() != NULL);
if (!channel->channel_valid()) {
channel->channel_handle_ = channel_handle;
if (mode & IPC::Channel::MODE_SERVER_FLAG) {
channel->channel_handle_.name =
IPC::Channel::GenerateVerifiedChannelID(channel_key);
}
channel->mode_ = mode;
if (channel->Init(ipc_message_loop, create_pipe_now, shutdown_event)) {
(*GetChannelMap())[channel_key] = channel;
} else {
channel = NULL;
}
}
return channel.get();
}
void NPChannelBase::Broadcast(IPC::Message* message) {
for (ChannelMap::iterator iter = GetChannelMap()->begin();
iter != GetChannelMap()->end();
++iter) {
iter->second->Send(new IPC::Message(*message));
}
delete message;
}
NPChannelBase::NPChannelBase()
: mode_(IPC::Channel::MODE_NONE),
non_npobject_count_(0),
peer_pid_(0),
in_remove_route_(false),
default_owner_(NULL),
channel_valid_(false),
in_unblock_dispatch_(0),
send_unblocking_only_during_unblock_dispatch_(false) {
}
NPChannelBase::~NPChannelBase() {
// TODO(wez): Establish why these would ever be non-empty at teardown.
//DCHECK(npobject_listeners_.empty());
//DCHECK(proxy_map_.empty());
//DCHECK(stub_map_.empty());
DCHECK(owner_to_route_.empty());
DCHECK(route_to_owner_.empty());
}
NPChannelBase* NPChannelBase::GetCurrentChannel() {
return GetChannelGlobals()->current_channel.get();
}
void NPChannelBase::CleanupChannels() {
// Make a copy of the references as we can't iterate the map since items will
// be removed from it as we clean them up.
std::vector<scoped_refptr<NPChannelBase> > channels;
for (ChannelMap::const_iterator iter = GetChannelMap()->begin();
iter != GetChannelMap()->end();
++iter) {
channels.push_back(iter->second);
}
for (size_t i = 0; i < channels.size(); ++i)
channels[i]->CleanUp();
// This will clean up channels added to the map for which subsequent
// AddRoute wasn't called
GetChannelMap()->clear();
}
NPObjectBase* NPChannelBase::GetNPObjectListenerForRoute(int route_id) {
ListenerMap::iterator iter = npobject_listeners_.find(route_id);
if (iter == npobject_listeners_.end()) {
DLOG(WARNING) << "Invalid route id passed in:" << route_id;
return NULL;
}
return iter->second;
}
base::WaitableEvent* NPChannelBase::GetModalDialogEvent(int render_view_id) {
return NULL;
}
bool NPChannelBase::Init(base::MessageLoopProxy* ipc_message_loop,
bool create_pipe_now,
base::WaitableEvent* shutdown_event) {
#if defined(OS_POSIX)
// Attempting to initialize with an invalid channel handle.
// See http://crbug.com/97285 for details.
if (mode_ == IPC::Channel::MODE_CLIENT && -1 == channel_handle_.socket.fd)
return false;
#endif
channel_.reset(new IPC::SyncChannel(
channel_handle_, mode_, this, ipc_message_loop, create_pipe_now,
shutdown_event));
#if defined(OS_POSIX)
// Check the validity of fd for bug investigation. Remove after fixed.
// See crbug.com/97285 for details.
if (mode_ == IPC::Channel::MODE_SERVER)
CHECK_NE(-1, channel_->GetClientFileDescriptor());
#endif
channel_valid_ = true;
return true;
}
bool NPChannelBase::Send(IPC::Message* message) {
if (!channel_) {
VLOG(1) << "Channel is NULL; dropping message";
delete message;
return false;
}
if (send_unblocking_only_during_unblock_dispatch_ &&
in_unblock_dispatch_ == 0 &&
message->is_sync()) {
message->set_unblock(false);
}
return channel_->Send(message);
}
int NPChannelBase::Count() {
return static_cast<int>(GetChannelMap()->size());
}
bool NPChannelBase::OnMessageReceived(const IPC::Message& message) {
// Push this channel as the current channel being processed. This also forms
// a stack of scoped_refptr avoiding ourselves (or any instance higher
// up the callstack) from being deleted while processing a message.
base::AutoReset<scoped_refptr<NPChannelBase> > keep_alive(
&GetChannelGlobals()->current_channel, this);
bool handled;
if (message.should_unblock())
in_unblock_dispatch_++;
if (message.routing_id() == MSG_ROUTING_CONTROL) {
handled = OnControlMessageReceived(message);
} else {
handled = router_.RouteMessage(message);
if (!handled && message.is_sync()) {
// The listener has gone away, so we must respond or else the caller will
// hang waiting for a reply.
IPC::Message* reply = IPC::SyncMessage::GenerateReply(&message);
reply->set_reply_error();
Send(reply);
}
}
if (message.should_unblock())
in_unblock_dispatch_--;
return handled;
}
void NPChannelBase::OnChannelConnected(int32 peer_pid) {
peer_pid_ = peer_pid;
}
void NPChannelBase::AddRoute(int route_id,
IPC::Listener* listener,
NPObjectBase* npobject) {
if (npobject) {
npobject_listeners_[route_id] = npobject;
} else {
non_npobject_count_++;
}
router_.AddRoute(route_id, listener);
}
void NPChannelBase::RemoveRoute(int route_id) {
router_.RemoveRoute(route_id);
ListenerMap::iterator iter = npobject_listeners_.find(route_id);
if (iter != npobject_listeners_.end()) {
// This was an NPObject proxy or stub, it's not involved in the refcounting.
// If this RemoveRoute call from the NPObject is a result of us calling
// OnChannelError below, don't call erase() here because that'll corrupt
// the iterator below.
if (in_remove_route_) {
iter->second = NULL;
} else {
npobject_listeners_.erase(iter);
}
return;
}
non_npobject_count_--;
DCHECK(non_npobject_count_ >= 0);
if (!non_npobject_count_) {
base::AutoReset<bool> auto_reset_in_remove_route(&in_remove_route_, true);
for (ListenerMap::iterator npobj_iter = npobject_listeners_.begin();
npobj_iter != npobject_listeners_.end(); ++npobj_iter) {
if (npobj_iter->second) {
npobj_iter->second->GetChannelListener()->OnChannelError();
}
}
for (ChannelMap::iterator iter = GetChannelMap()->begin();
iter != GetChannelMap()->end(); ++iter) {
if (iter->second.get() == this) {
GetChannelMap()->erase(iter);
return;
}
}
NOTREACHED();
}
}
bool NPChannelBase::OnControlMessageReceived(const IPC::Message& msg) {
NOTREACHED() <<
"should override in subclass if you care about control messages";
return false;
}
void NPChannelBase::OnChannelError() {
channel_valid_ = false;
// TODO(shess): http://crbug.com/97285
// Once an error is seen on a channel, remap the channel to prevent
// it from being vended again. Keep the channel in the map so
// RemoveRoute() can clean things up correctly.
for (ChannelMap::iterator iter = GetChannelMap()->begin();
iter != GetChannelMap()->end(); ++iter) {
if (iter->second.get() == this) {
// Insert new element before invalidating |iter|.
(*GetChannelMap())[iter->first + "-error"] = iter->second;
GetChannelMap()->erase(iter);
break;
}
}
}
void NPChannelBase::AddMappingForNPObjectProxy(int route_id,
NPObject* object) {
proxy_map_[route_id] = object;
}
void NPChannelBase::RemoveMappingForNPObjectProxy(int route_id) {
proxy_map_.erase(route_id);
}
void NPChannelBase::AddMappingForNPObjectStub(int route_id,
NPObject* object) {
DCHECK(object != NULL);
stub_map_[object] = route_id;
}
void NPChannelBase::RemoveMappingForNPObjectStub(int route_id,
NPObject* object) {
DCHECK(object != NULL);
stub_map_.erase(object);
}
void NPChannelBase::AddMappingForNPObjectOwner(int route_id,
struct _NPP* owner) {
DCHECK(owner != NULL);
route_to_owner_[route_id] = owner;
owner_to_route_[owner] = route_id;
}
void NPChannelBase::SetDefaultNPObjectOwner(struct _NPP* owner) {
DCHECK(owner != NULL);
default_owner_ = owner;
}
void NPChannelBase::RemoveMappingForNPObjectOwner(int route_id) {
DCHECK(route_to_owner_.find(route_id) != route_to_owner_.end());
owner_to_route_.erase(route_to_owner_[route_id]);
route_to_owner_.erase(route_id);
}
NPObject* NPChannelBase::GetExistingNPObjectProxy(int route_id) {
ProxyMap::iterator iter = proxy_map_.find(route_id);
return iter != proxy_map_.end() ? iter->second : NULL;
}
int NPChannelBase::GetExistingRouteForNPObjectStub(NPObject* npobject) {
StubMap::iterator iter = stub_map_.find(npobject);
return iter != stub_map_.end() ? iter->second : MSG_ROUTING_NONE;
}
NPP NPChannelBase::GetExistingNPObjectOwner(int route_id) {
RouteToOwnerMap::iterator iter = route_to_owner_.find(route_id);
return iter != route_to_owner_.end() ? iter->second : default_owner_;
}
int NPChannelBase::GetExistingRouteForNPObjectOwner(NPP owner) {
OwnerToRouteMap::iterator iter = owner_to_route_.find(owner);
return iter != owner_to_route_.end() ? iter->second : MSG_ROUTING_NONE;
}
} // namespace content
<commit_msg>Fix a fd leak in NPChannelBase on Posix<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/child/npapi/np_channel_base.h"
#include "base/auto_reset.h"
#include "base/containers/hash_tables.h"
#include "base/lazy_instance.h"
#include "base/strings/string_number_conversions.h"
#include "base/threading/thread_local.h"
#include "ipc/ipc_sync_message.h"
#if defined(OS_POSIX)
#include "base/file_util.h"
#include "ipc/ipc_channel_posix.h"
#endif
namespace content {
namespace {
typedef base::hash_map<std::string, scoped_refptr<NPChannelBase> > ChannelMap;
struct ChannelGlobals {
ChannelMap channel_map;
scoped_refptr<NPChannelBase> current_channel;
};
#if defined(OS_ANDROID)
// Workaround for http://crbug.com/298179 - NPChannelBase is only intended
// for use on one thread per process. Using TLS to store the globals removes the
// worst thread hostility in this class, especially needed for webview which
// runs in single-process mode. TODO(joth): Make a complete fix, most likely
// as part of addressing http://crbug.com/258510.
base::LazyInstance<base::ThreadLocalPointer<ChannelGlobals> >::Leaky
g_channels_tls_ptr = LAZY_INSTANCE_INITIALIZER;
ChannelGlobals* GetChannelGlobals() {
ChannelGlobals* globals = g_channels_tls_ptr.Get().Get();
if (!globals) {
globals = new ChannelGlobals;
g_channels_tls_ptr.Get().Set(globals);
}
return globals;
}
#else
base::LazyInstance<ChannelGlobals>::Leaky g_channels_globals =
LAZY_INSTANCE_INITIALIZER;
ChannelGlobals* GetChannelGlobals() { return g_channels_globals.Pointer(); }
#endif // OS_ANDROID
ChannelMap* GetChannelMap() {
return &GetChannelGlobals()->channel_map;
}
} // namespace
NPChannelBase* NPChannelBase::GetChannel(
const IPC::ChannelHandle& channel_handle, IPC::Channel::Mode mode,
ChannelFactory factory, base::MessageLoopProxy* ipc_message_loop,
bool create_pipe_now, base::WaitableEvent* shutdown_event) {
#if defined(OS_POSIX)
// On POSIX the channel_handle conveys an FD (socket) which is duped by the
// kernel during the IPC message exchange (via the SCM_RIGHTS mechanism).
// Ensure we do not leak this FD.
int fd = channel_handle.socket.auto_close ? channel_handle.socket.fd : -1;
file_util::ScopedFD auto_close_fd(&fd);
#endif
scoped_refptr<NPChannelBase> channel;
std::string channel_key = channel_handle.name;
ChannelMap::const_iterator iter = GetChannelMap()->find(channel_key);
if (iter == GetChannelMap()->end()) {
channel = factory();
} else {
channel = iter->second;
}
DCHECK(channel.get() != NULL);
if (!channel->channel_valid()) {
channel->channel_handle_ = channel_handle;
#if defined(OS_POSIX)
ignore_result(auto_close_fd.release());
#endif
if (mode & IPC::Channel::MODE_SERVER_FLAG) {
channel->channel_handle_.name =
IPC::Channel::GenerateVerifiedChannelID(channel_key);
}
channel->mode_ = mode;
if (channel->Init(ipc_message_loop, create_pipe_now, shutdown_event)) {
(*GetChannelMap())[channel_key] = channel;
} else {
channel = NULL;
}
}
return channel.get();
}
void NPChannelBase::Broadcast(IPC::Message* message) {
for (ChannelMap::iterator iter = GetChannelMap()->begin();
iter != GetChannelMap()->end();
++iter) {
iter->second->Send(new IPC::Message(*message));
}
delete message;
}
NPChannelBase::NPChannelBase()
: mode_(IPC::Channel::MODE_NONE),
non_npobject_count_(0),
peer_pid_(0),
in_remove_route_(false),
default_owner_(NULL),
channel_valid_(false),
in_unblock_dispatch_(0),
send_unblocking_only_during_unblock_dispatch_(false) {
}
NPChannelBase::~NPChannelBase() {
// TODO(wez): Establish why these would ever be non-empty at teardown.
//DCHECK(npobject_listeners_.empty());
//DCHECK(proxy_map_.empty());
//DCHECK(stub_map_.empty());
DCHECK(owner_to_route_.empty());
DCHECK(route_to_owner_.empty());
}
NPChannelBase* NPChannelBase::GetCurrentChannel() {
return GetChannelGlobals()->current_channel.get();
}
void NPChannelBase::CleanupChannels() {
// Make a copy of the references as we can't iterate the map since items will
// be removed from it as we clean them up.
std::vector<scoped_refptr<NPChannelBase> > channels;
for (ChannelMap::const_iterator iter = GetChannelMap()->begin();
iter != GetChannelMap()->end();
++iter) {
channels.push_back(iter->second);
}
for (size_t i = 0; i < channels.size(); ++i)
channels[i]->CleanUp();
// This will clean up channels added to the map for which subsequent
// AddRoute wasn't called
GetChannelMap()->clear();
}
NPObjectBase* NPChannelBase::GetNPObjectListenerForRoute(int route_id) {
ListenerMap::iterator iter = npobject_listeners_.find(route_id);
if (iter == npobject_listeners_.end()) {
DLOG(WARNING) << "Invalid route id passed in:" << route_id;
return NULL;
}
return iter->second;
}
base::WaitableEvent* NPChannelBase::GetModalDialogEvent(int render_view_id) {
return NULL;
}
bool NPChannelBase::Init(base::MessageLoopProxy* ipc_message_loop,
bool create_pipe_now,
base::WaitableEvent* shutdown_event) {
#if defined(OS_POSIX)
// Attempting to initialize with an invalid channel handle.
// See http://crbug.com/97285 for details.
if (mode_ == IPC::Channel::MODE_CLIENT && -1 == channel_handle_.socket.fd)
return false;
#endif
channel_.reset(new IPC::SyncChannel(
channel_handle_, mode_, this, ipc_message_loop, create_pipe_now,
shutdown_event));
#if defined(OS_POSIX)
// Check the validity of fd for bug investigation. Remove after fixed.
// See crbug.com/97285 for details.
if (mode_ == IPC::Channel::MODE_SERVER)
CHECK_NE(-1, channel_->GetClientFileDescriptor());
#endif
channel_valid_ = true;
return true;
}
bool NPChannelBase::Send(IPC::Message* message) {
if (!channel_) {
VLOG(1) << "Channel is NULL; dropping message";
delete message;
return false;
}
if (send_unblocking_only_during_unblock_dispatch_ &&
in_unblock_dispatch_ == 0 &&
message->is_sync()) {
message->set_unblock(false);
}
return channel_->Send(message);
}
int NPChannelBase::Count() {
return static_cast<int>(GetChannelMap()->size());
}
bool NPChannelBase::OnMessageReceived(const IPC::Message& message) {
// Push this channel as the current channel being processed. This also forms
// a stack of scoped_refptr avoiding ourselves (or any instance higher
// up the callstack) from being deleted while processing a message.
base::AutoReset<scoped_refptr<NPChannelBase> > keep_alive(
&GetChannelGlobals()->current_channel, this);
bool handled;
if (message.should_unblock())
in_unblock_dispatch_++;
if (message.routing_id() == MSG_ROUTING_CONTROL) {
handled = OnControlMessageReceived(message);
} else {
handled = router_.RouteMessage(message);
if (!handled && message.is_sync()) {
// The listener has gone away, so we must respond or else the caller will
// hang waiting for a reply.
IPC::Message* reply = IPC::SyncMessage::GenerateReply(&message);
reply->set_reply_error();
Send(reply);
}
}
if (message.should_unblock())
in_unblock_dispatch_--;
return handled;
}
void NPChannelBase::OnChannelConnected(int32 peer_pid) {
peer_pid_ = peer_pid;
}
void NPChannelBase::AddRoute(int route_id,
IPC::Listener* listener,
NPObjectBase* npobject) {
if (npobject) {
npobject_listeners_[route_id] = npobject;
} else {
non_npobject_count_++;
}
router_.AddRoute(route_id, listener);
}
void NPChannelBase::RemoveRoute(int route_id) {
router_.RemoveRoute(route_id);
ListenerMap::iterator iter = npobject_listeners_.find(route_id);
if (iter != npobject_listeners_.end()) {
// This was an NPObject proxy or stub, it's not involved in the refcounting.
// If this RemoveRoute call from the NPObject is a result of us calling
// OnChannelError below, don't call erase() here because that'll corrupt
// the iterator below.
if (in_remove_route_) {
iter->second = NULL;
} else {
npobject_listeners_.erase(iter);
}
return;
}
non_npobject_count_--;
DCHECK(non_npobject_count_ >= 0);
if (!non_npobject_count_) {
base::AutoReset<bool> auto_reset_in_remove_route(&in_remove_route_, true);
for (ListenerMap::iterator npobj_iter = npobject_listeners_.begin();
npobj_iter != npobject_listeners_.end(); ++npobj_iter) {
if (npobj_iter->second) {
npobj_iter->second->GetChannelListener()->OnChannelError();
}
}
for (ChannelMap::iterator iter = GetChannelMap()->begin();
iter != GetChannelMap()->end(); ++iter) {
if (iter->second.get() == this) {
GetChannelMap()->erase(iter);
return;
}
}
NOTREACHED();
}
}
bool NPChannelBase::OnControlMessageReceived(const IPC::Message& msg) {
NOTREACHED() <<
"should override in subclass if you care about control messages";
return false;
}
void NPChannelBase::OnChannelError() {
channel_valid_ = false;
// TODO(shess): http://crbug.com/97285
// Once an error is seen on a channel, remap the channel to prevent
// it from being vended again. Keep the channel in the map so
// RemoveRoute() can clean things up correctly.
for (ChannelMap::iterator iter = GetChannelMap()->begin();
iter != GetChannelMap()->end(); ++iter) {
if (iter->second.get() == this) {
// Insert new element before invalidating |iter|.
(*GetChannelMap())[iter->first + "-error"] = iter->second;
GetChannelMap()->erase(iter);
break;
}
}
}
void NPChannelBase::AddMappingForNPObjectProxy(int route_id,
NPObject* object) {
proxy_map_[route_id] = object;
}
void NPChannelBase::RemoveMappingForNPObjectProxy(int route_id) {
proxy_map_.erase(route_id);
}
void NPChannelBase::AddMappingForNPObjectStub(int route_id,
NPObject* object) {
DCHECK(object != NULL);
stub_map_[object] = route_id;
}
void NPChannelBase::RemoveMappingForNPObjectStub(int route_id,
NPObject* object) {
DCHECK(object != NULL);
stub_map_.erase(object);
}
void NPChannelBase::AddMappingForNPObjectOwner(int route_id,
struct _NPP* owner) {
DCHECK(owner != NULL);
route_to_owner_[route_id] = owner;
owner_to_route_[owner] = route_id;
}
void NPChannelBase::SetDefaultNPObjectOwner(struct _NPP* owner) {
DCHECK(owner != NULL);
default_owner_ = owner;
}
void NPChannelBase::RemoveMappingForNPObjectOwner(int route_id) {
DCHECK(route_to_owner_.find(route_id) != route_to_owner_.end());
owner_to_route_.erase(route_to_owner_[route_id]);
route_to_owner_.erase(route_id);
}
NPObject* NPChannelBase::GetExistingNPObjectProxy(int route_id) {
ProxyMap::iterator iter = proxy_map_.find(route_id);
return iter != proxy_map_.end() ? iter->second : NULL;
}
int NPChannelBase::GetExistingRouteForNPObjectStub(NPObject* npobject) {
StubMap::iterator iter = stub_map_.find(npobject);
return iter != stub_map_.end() ? iter->second : MSG_ROUTING_NONE;
}
NPP NPChannelBase::GetExistingNPObjectOwner(int route_id) {
RouteToOwnerMap::iterator iter = route_to_owner_.find(route_id);
return iter != route_to_owner_.end() ? iter->second : default_owner_;
}
int NPChannelBase::GetExistingRouteForNPObjectOwner(NPP owner) {
OwnerToRouteMap::iterator iter = owner_to_route_.find(owner);
return iter != owner_to_route_.end() ? iter->second : MSG_ROUTING_NONE;
}
} // namespace content
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/swapped_out_messages.h"
#include "content/common/content_client.h"
#include "content/common/view_messages.h"
namespace content {
bool SwappedOutMessages::CanSendWhileSwappedOut(const IPC::Message* msg) {
// We filter out most IPC messages when swapped out. However, some are
// important (e.g., ACKs) for keeping the browser and renderer state
// consistent in case we later return to the same renderer.
switch (msg->type()) {
// Handled by RenderWidget.
case ViewHostMsg_HandleInputEvent_ACK::ID:
case ViewHostMsg_PaintAtSize_ACK::ID:
case ViewHostMsg_UpdateRect::ID:
// Handled by RenderView.
case ViewHostMsg_RenderViewGone::ID:
case ViewHostMsg_ShouldClose_ACK::ID:
case ViewHostMsg_SwapOut_ACK::ID:
case ViewHostMsg_ClosePage_ACK::ID:
return true;
default:
break;
}
// Check with the embedder as well.
ContentClient* client = GetContentClient();
return client->CanSendWhileSwappedOut(msg);
}
bool SwappedOutMessages::CanHandleWhileSwappedOut(
const IPC::Message& msg) {
// Any message the renderer is allowed to send while swapped out should
// be handled by the browser.
if (CanSendWhileSwappedOut(&msg))
return true;
// We drop most other messages that arrive from a swapped out renderer.
// However, some are important (e.g., ACKs) for keeping the browser and
// renderer state consistent in case we later return to the renderer.
switch (msg.type()) {
// Sends an ACK.
case ViewHostMsg_ShowView::ID:
// Sends an ACK.
case ViewHostMsg_ShowWidget::ID:
// Sends an ACK.
case ViewHostMsg_ShowFullscreenWidget::ID:
// Updates browser state.
case ViewHostMsg_RenderViewReady::ID:
// Updates the previous navigation entry.
case ViewHostMsg_UpdateState::ID:
// Sends an ACK.
case ViewHostMsg_UpdateTargetURL::ID:
// We allow closing even if we are in the process of swapping out.
case ViewHostMsg_Close::ID:
// Sends an ACK.
case ViewHostMsg_RequestMove::ID:
// Suppresses dialog and sends an ACK.
case ViewHostMsg_RunJavaScriptMessage::ID:
// Suppresses dialog and sends an ACK.
case ViewHostMsg_RunBeforeUnloadConfirm::ID:
// Sends an ACK.
case ViewHostMsg_AccessibilityNotifications::ID:
return true;
default:
break;
}
// Check with the embedder as well.
ContentClient* client = GetContentClient();
return client->CanHandleWhileSwappedOut(msg);
}
} // namespace content
<commit_msg>Ensure that plugins can be destroyed in swapped out RenderViews.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/swapped_out_messages.h"
#include "content/common/content_client.h"
#include "content/common/view_messages.h"
namespace content {
bool SwappedOutMessages::CanSendWhileSwappedOut(const IPC::Message* msg) {
// We filter out most IPC messages when swapped out. However, some are
// important (e.g., ACKs) for keeping the browser and renderer state
// consistent in case we later return to the same renderer.
switch (msg->type()) {
// Handled by RenderWidget.
case ViewHostMsg_HandleInputEvent_ACK::ID:
case ViewHostMsg_PaintAtSize_ACK::ID:
case ViewHostMsg_UpdateRect::ID:
// Handled by RenderView.
case ViewHostMsg_RenderViewGone::ID:
case ViewHostMsg_ShouldClose_ACK::ID:
case ViewHostMsg_SwapOut_ACK::ID:
case ViewHostMsg_ClosePage_ACK::ID:
return true;
default:
break;
}
// Check with the embedder as well.
ContentClient* client = GetContentClient();
return client->CanSendWhileSwappedOut(msg);
}
bool SwappedOutMessages::CanHandleWhileSwappedOut(
const IPC::Message& msg) {
// Any message the renderer is allowed to send while swapped out should
// be handled by the browser.
if (CanSendWhileSwappedOut(&msg))
return true;
// We drop most other messages that arrive from a swapped out renderer.
// However, some are important (e.g., ACKs) for keeping the browser and
// renderer state consistent in case we later return to the renderer.
switch (msg.type()) {
// Sends an ACK.
case ViewHostMsg_ShowView::ID:
// Sends an ACK.
case ViewHostMsg_ShowWidget::ID:
// Sends an ACK.
case ViewHostMsg_ShowFullscreenWidget::ID:
// Updates browser state.
case ViewHostMsg_RenderViewReady::ID:
// Updates the previous navigation entry.
case ViewHostMsg_UpdateState::ID:
// Sends an ACK.
case ViewHostMsg_UpdateTargetURL::ID:
// We allow closing even if we are in the process of swapping out.
case ViewHostMsg_Close::ID:
// Sends an ACK.
case ViewHostMsg_RequestMove::ID:
// Suppresses dialog and sends an ACK.
case ViewHostMsg_RunJavaScriptMessage::ID:
// Suppresses dialog and sends an ACK.
case ViewHostMsg_RunBeforeUnloadConfirm::ID:
// Sends an ACK.
case ViewHostMsg_AccessibilityNotifications::ID:
#if defined(USE_X11)
// Synchronous message when leaving a page with plugin.
case ViewHostMsg_DestroyPluginContainer::ID:
#endif
return true;
default:
break;
}
// Check with the embedder as well.
ContentClient* client = GetContentClient();
return client->CanHandleWhileSwappedOut(msg);
}
} // namespace content
<|endoftext|>
|
<commit_before>#include "kernel.h"
#include "ilwisdata.h"
#include "domain.h"
#include "range.h"
#include "datadefinition.h"
#include "columndefinition.h"
#include "connectorinterface.h"
#include "table.h"
#include "basetable.h"
using namespace Ilwis;
BaseTable::BaseTable() : Table(), _rows(0), _columns(0), _dataloaded(false)
{
}
BaseTable::BaseTable(const Resource& resource) : Table(resource), _rows(0), _columns(0),_dataloaded(false) {
}
BaseTable::~BaseTable()
{
}
quint32 BaseTable::records() const
{
return _rows;
}
quint32 BaseTable::columns() const
{
return _columns;
}
void BaseTable::records(quint32 r)
{
_rows = r;
}
bool BaseTable::createTable()
{
if (!isValid()) {
kernel()->issues()->log(TR("Not created, Table %1 already exists").arg(name()), IssueObject::itWarning);
return false;
}
if ( _columnDefinitionsByName.size() == 0) {
kernel()->issues()->log(TR("Trying to create table %1 with zero columns").arg(name()));
return false;
}
return true;
}
bool BaseTable::addColumn(const ColumnDefinition& def){
if ( _columnDefinitionsByName.contains(def.name())) {
kernel()->issues()->log(TR("Adding duplicate column %1").arg(name()),IssueObject::itWarning);
return false;
}
_columnDefinitionsByName[def.name()] = def;
_columnDefinitionsByIndex[def.id()] = _columnDefinitionsByName[def.name()];
_columns = _columnDefinitionsByName.size();
return true;
}
bool BaseTable::addColumn(const QString &name, const IDomain& domain)
{
if ( _columnDefinitionsByName.contains(name)) {
kernel()->issues()->log(TR("Adding duplicate column %1").arg(name),IssueObject::itWarning);
return false;
}
_columnDefinitionsByName[name] = ColumnDefinition(name, domain,_columnDefinitionsByName.size());
_columnDefinitionsByIndex[_columnDefinitionsByName[name].id()] = _columnDefinitionsByName[name];
_columns = _columnDefinitionsByName.size();
return true;
}
bool BaseTable::addColumn(const QString &name, const QString &domainname)
{
IDomain dom;
if(!dom.prepare(domainname))
return false;
return addColumn(name, dom);
}
IlwisTypes BaseTable::ilwisType() const
{
return itTABLE;
}
ColumnDefinition BaseTable::columndefinition(const QString &nme) const
{
auto iter = _columnDefinitionsByName.find(nme);
if ( iter != _columnDefinitionsByName.end())
return iter.value();
return ColumnDefinition();
}
ColumnDefinition BaseTable::columndefinition(quint32 index) const
{
auto iter = _columnDefinitionsByIndex.find(index);
if ( iter != _columnDefinitionsByIndex.end())
return iter.value();
return ColumnDefinition();
}
bool BaseTable::prepare()
{
if (!IlwisObject::prepare())
return false;
return true;
}
bool BaseTable::isValid() const
{
return _rows != 0 && _columns != 0;
}
ColumnDefinition &BaseTable::columndefinition(quint32 index)
{
return _columnDefinitionsByIndex[index] ;
}
bool BaseTable::initLoad() {
if ( !this->isValid()) {
kernel()->issues()->log(TR(ERR_NO_INITIALIZED_1).arg("table"));
return false;
}
if (!_dataloaded) {
_dataloaded = true; // to prevent other inits to pass through here
if (! connector()->loadBinaryData(this)) {
kernel()->issues()->log(TR(ERR_COULD_NOT_LOAD_2).arg("table", name()));
_dataloaded = false;
return false;
}
}
return true;
}
quint32 BaseTable::columnIndex(const QString &nme) const
{
auto iter = _columnDefinitionsByName.find(nme);
if ( iter == _columnDefinitionsByName.end()) {
//kernel()->issues()->log(TR(ERR_COLUMN_MISSING_2).arg(nme).arg(name()),IssueObject::itWarning);
return iUNDEF;
}
return iter.value().id();
}
<commit_msg>added guard<commit_after>#include "kernel.h"
#include "ilwisdata.h"
#include "domain.h"
#include "range.h"
#include "datadefinition.h"
#include "columndefinition.h"
#include "connectorinterface.h"
#include "table.h"
#include "basetable.h"
using namespace Ilwis;
BaseTable::BaseTable() : Table(), _rows(0), _columns(0), _dataloaded(false)
{
}
BaseTable::BaseTable(const Resource& resource) : Table(resource), _rows(0), _columns(0),_dataloaded(false) {
}
BaseTable::~BaseTable()
{
}
quint32 BaseTable::records() const
{
return _rows;
}
quint32 BaseTable::columns() const
{
return _columns;
}
void BaseTable::records(quint32 r)
{
_rows = r;
}
bool BaseTable::createTable()
{
if (!isValid()) {
kernel()->issues()->log(TR("Not created, Table %1 already exists").arg(name()), IssueObject::itWarning);
return false;
}
if ( _columnDefinitionsByName.size() == 0) {
kernel()->issues()->log(TR("Trying to create table %1 with zero columns").arg(name()));
return false;
}
return true;
}
bool BaseTable::addColumn(const ColumnDefinition& def){
if ( _columnDefinitionsByName.contains(def.name())) {
kernel()->issues()->log(TR("Adding duplicate column %1").arg(name()),IssueObject::itWarning);
return false;
}
_columnDefinitionsByName[def.name()] = def;
_columnDefinitionsByIndex[def.id()] = _columnDefinitionsByName[def.name()];
_columns = _columnDefinitionsByName.size();
return true;
}
bool BaseTable::addColumn(const QString &name, const IDomain& domain)
{
if ( _columnDefinitionsByName.contains(name)) {
kernel()->issues()->log(TR("Adding duplicate column %1").arg(name),IssueObject::itWarning);
return false;
}
_columnDefinitionsByName[name] = ColumnDefinition(name, domain,_columnDefinitionsByName.size());
_columnDefinitionsByIndex[_columnDefinitionsByName[name].id()] = _columnDefinitionsByName[name];
_columns = _columnDefinitionsByName.size();
return true;
}
bool BaseTable::addColumn(const QString &name, const QString &domainname)
{
IDomain dom;
if(!dom.prepare(domainname))
return false;
return addColumn(name, dom);
}
IlwisTypes BaseTable::ilwisType() const
{
return itTABLE;
}
ColumnDefinition BaseTable::columndefinition(const QString &nme) const
{
auto iter = _columnDefinitionsByName.find(nme);
if ( iter != _columnDefinitionsByName.end())
return iter.value();
return ColumnDefinition();
}
ColumnDefinition BaseTable::columndefinition(quint32 index) const
{
auto iter = _columnDefinitionsByIndex.find(index);
if ( iter != _columnDefinitionsByIndex.end())
return iter.value();
return ColumnDefinition();
}
bool BaseTable::prepare()
{
if (!IlwisObject::prepare())
return false;
return true;
}
bool BaseTable::isValid() const
{
return _rows != 0 && _columns != 0;
}
ColumnDefinition &BaseTable::columndefinition(quint32 index)
{
return _columnDefinitionsByIndex[index] ;
}
bool BaseTable::initLoad() {
if ( !this->isValid()) {
kernel()->issues()->log(TR(ERR_NO_INITIALIZED_1).arg("table"));
return false;
}
if (!_dataloaded) {
_dataloaded = true; // to prevent other inits to pass through here
if (!connector().isNull() && ! connector()->loadBinaryData(this)) {
kernel()->issues()->log(TR(ERR_COULD_NOT_LOAD_2).arg("table", name()));
_dataloaded = false;
return false;
}
}
return true;
}
quint32 BaseTable::columnIndex(const QString &nme) const
{
auto iter = _columnDefinitionsByName.find(nme);
if ( iter == _columnDefinitionsByName.end()) {
//kernel()->issues()->log(TR(ERR_COLUMN_MISSING_2).arg(nme).arg(name()),IssueObject::itWarning);
return iUNDEF;
}
return iter.value().id();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/p2p/port_allocator.h"
#include "base/bind.h"
#include "base/string_number_conversions.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "content/renderer/p2p/host_address_request.h"
#include "jingle/glue/utils.h"
#include "net/base/ip_endpoint.h"
#include "ppapi/c/dev/ppb_transport_dev.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLError.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLLoader.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLLoaderOptions.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLRequest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLResponse.h"
using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebURLLoader;
using WebKit::WebURLLoaderOptions;
using WebKit::WebURLRequest;
using WebKit::WebURLResponse;
namespace content {
namespace {
// URL used to create a relay session.
const char kCreateRelaySessionURL[] = "/create_session";
// Number of times we will try to request relay session.
const int kRelaySessionRetries = 3;
// Manimum relay server size we would try to parse.
const int kMaximumRelayResponseSize = 102400;
bool ParsePortNumber(
const std::string& string, int* value) {
if (!base::StringToInt(string, value) || *value <= 0 || *value >= 65536) {
LOG(ERROR) << "Received invalid port number from relay server: " << string;
return false;
}
return true;
}
} // namespace
P2PPortAllocator::P2PPortAllocator(
WebKit::WebFrame* web_frame,
P2PSocketDispatcher* socket_dispatcher,
talk_base::NetworkManager* network_manager,
talk_base::PacketSocketFactory* socket_factory,
const webkit_glue::P2PTransport::Config& config)
: cricket::BasicPortAllocator(network_manager, socket_factory),
web_frame_(web_frame),
socket_dispatcher_(socket_dispatcher),
config_(config) {
uint32 flags = 0;
if (config_.disable_tcp_transport)
flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
set_flags(flags);
}
P2PPortAllocator::~P2PPortAllocator() {
}
cricket::PortAllocatorSession* P2PPortAllocator::CreateSession(
const std::string& name,
const std::string& session_type) {
return new P2PPortAllocatorSession(this, name, session_type);
}
P2PPortAllocatorSession::P2PPortAllocatorSession(
P2PPortAllocator* allocator,
const std::string& name,
const std::string& session_type)
: cricket::BasicPortAllocatorSession(allocator, name, session_type),
allocator_(allocator),
relay_session_attempts_(0),
relay_udp_port_(0),
relay_tcp_port_(0),
relay_ssltcp_port_(0) {
}
P2PPortAllocatorSession::~P2PPortAllocatorSession() {
if (stun_address_request_)
stun_address_request_->Cancel();
}
void P2PPortAllocatorSession::didReceiveData(
WebURLLoader* loader, const char* data,
int data_length, int encoded_data_length) {
DCHECK_EQ(loader, relay_session_request_.get());
if (static_cast<int>(relay_session_response_.size()) + data_length >
kMaximumRelayResponseSize) {
LOG(ERROR) << "Response received from the server is too big.";
loader->cancel();
return;
}
relay_session_response_.append(data, data + data_length);
}
void P2PPortAllocatorSession::didFinishLoading(WebURLLoader* loader,
double finish_time) {
ParseRelayResponse();
}
void P2PPortAllocatorSession::didFail(WebKit::WebURLLoader* loader,
const WebKit::WebURLError& error) {
DCHECK_EQ(loader, relay_session_request_.get());
DCHECK_NE(error.reason, 0);
LOG(ERROR) << "Relay session request failed.";
// Retry the request.
AllocateRelaySession();
}
void P2PPortAllocatorSession::GetPortConfigurations() {
// Add an empty configuration synchronously, so a local connection
// can be started immediately.
ConfigReady(new cricket::PortConfiguration(
talk_base::SocketAddress(), "", "", ""));
ResolveStunServerAddress();
AllocateRelaySession();
}
void P2PPortAllocatorSession::ResolveStunServerAddress() {
if (allocator_->config_.stun_server.empty())
return;
DCHECK(!stun_address_request_);
stun_address_request_ =
new P2PHostAddressRequest(allocator_->socket_dispatcher_);
stun_address_request_->Request(allocator_->config_.stun_server, base::Bind(
&P2PPortAllocatorSession::OnStunServerAddress,
base::Unretained(this)));
}
void P2PPortAllocatorSession::OnStunServerAddress(
const net::IPAddressNumber& address) {
if (address.empty()) {
LOG(ERROR) << "Failed to resolve STUN server address "
<< allocator_->config_.stun_server;
return;
}
if (!jingle_glue::IPEndPointToSocketAddress(
net::IPEndPoint(address, allocator_->config_.stun_server_port),
&stun_server_address_)) {
return;
}
AddConfig();
}
void P2PPortAllocatorSession::AllocateRelaySession() {
if (allocator_->config_.relay_server.empty())
return;
if (!allocator_->config_.legacy_relay) {
NOTIMPLEMENTED() << " TURN support is not implemented yet.";
return;
}
if (relay_session_attempts_ > kRelaySessionRetries)
return;
relay_session_attempts_++;
relay_session_response_.clear();
WebURLLoaderOptions options;
options.allowCredentials = false;
options.crossOriginRequestPolicy =
WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
relay_session_request_.reset(
allocator_->web_frame_->createAssociatedURLLoader(options));
if (!relay_session_request_.get()) {
LOG(ERROR) << "Failed to create URL loader.";
return;
}
WebURLRequest request;
request.initialize();
request.setURL(WebURL(GURL(
"https://" + allocator_->config_.relay_server + kCreateRelaySessionURL)));
request.setAllowStoredCredentials(false);
request.setCachePolicy(WebURLRequest::ReloadIgnoringCacheData);
request.setHTTPMethod("GET");
request.addHTTPHeaderField(
WebString::fromUTF8("X-Talk-Google-Relay-Auth"),
WebString::fromUTF8(allocator_->config_.relay_password));
request.addHTTPHeaderField(
WebString::fromUTF8("X-Google-Relay-Auth"),
WebString::fromUTF8(allocator_->config_.relay_password));
request.addHTTPHeaderField(WebString::fromUTF8("X-Session-Type"),
WebString::fromUTF8(session_type()));
request.addHTTPHeaderField(WebString::fromUTF8("X-Stream-Type"),
WebString::fromUTF8(name()));
relay_session_request_->loadAsynchronously(request, this);
}
void P2PPortAllocatorSession::ParseRelayResponse() {
std::vector<std::pair<std::string, std::string> > value_pairs;
if (!base::SplitStringIntoKeyValuePairs(relay_session_response_, '=', '\n',
&value_pairs)) {
LOG(ERROR) << "Received invalid response from relay server";
return;
}
relay_username_.clear();
relay_password_.clear();
relay_ip_.Clear();
relay_udp_port_ = 0;
relay_tcp_port_ = 0;
relay_ssltcp_port_ = 0;
for (std::vector<std::pair<std::string, std::string> >::iterator
it = value_pairs.begin();
it != value_pairs.end(); ++it) {
std::string key;
std::string value;
TrimWhitespaceASCII(it->first, TRIM_ALL, &key);
TrimWhitespaceASCII(it->second, TRIM_ALL, &value);
if (key == "username") {
relay_username_ = value;
} else if (key == "password") {
relay_password_ = value;
} else if (key == "relay.ip") {
relay_ip_.SetIP(value);
if (relay_ip_.ip() == 0) {
LOG(ERROR) << "Received unresolved relay server address: " << value;
return;
}
} else if (key == "relay.udp_port") {
if (!ParsePortNumber(value, &relay_udp_port_))
return;
} else if (key == "relay.tcp_port") {
if (!ParsePortNumber(value, &relay_tcp_port_))
return;
} else if (key == "relay.ssltcp_port") {
if (!ParsePortNumber(value, &relay_ssltcp_port_))
return;
}
}
AddConfig();
}
void P2PPortAllocatorSession::AddConfig() {
cricket::PortConfiguration* config =
new cricket::PortConfiguration(stun_server_address_,
relay_username_, relay_password_, "");
cricket::PortConfiguration::PortList ports;
if (relay_ip_.ip() != 0) {
if (relay_udp_port_ > 0) {
talk_base::SocketAddress address(relay_ip_.ip(), relay_udp_port_);
ports.push_back(cricket::ProtocolAddress(address, cricket::PROTO_UDP));
}
if (relay_tcp_port_ > 0 && !allocator_->config_.disable_tcp_transport) {
talk_base::SocketAddress address(relay_ip_.ip(), relay_tcp_port_);
ports.push_back(cricket::ProtocolAddress(address, cricket::PROTO_TCP));
}
if (relay_ssltcp_port_ > 0 && !allocator_->config_.disable_tcp_transport) {
talk_base::SocketAddress address(relay_ip_.ip(), relay_ssltcp_port_);
ports.push_back(cricket::ProtocolAddress(address, cricket::PROTO_SSLTCP));
}
}
config->AddRelay(ports, 0.0f);
ConfigReady(config);
}
} // namespace content
<commit_msg>Allow cross-origin requests for relay http requests made in Transport API.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/p2p/port_allocator.h"
#include "base/bind.h"
#include "base/string_number_conversions.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "content/renderer/p2p/host_address_request.h"
#include "jingle/glue/utils.h"
#include "net/base/ip_endpoint.h"
#include "ppapi/c/dev/ppb_transport_dev.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLError.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLLoader.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLLoaderOptions.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLRequest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLResponse.h"
using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebURLLoader;
using WebKit::WebURLLoaderOptions;
using WebKit::WebURLRequest;
using WebKit::WebURLResponse;
namespace content {
namespace {
// URL used to create a relay session.
const char kCreateRelaySessionURL[] = "/create_session";
// Number of times we will try to request relay session.
const int kRelaySessionRetries = 3;
// Manimum relay server size we would try to parse.
const int kMaximumRelayResponseSize = 102400;
bool ParsePortNumber(
const std::string& string, int* value) {
if (!base::StringToInt(string, value) || *value <= 0 || *value >= 65536) {
LOG(ERROR) << "Received invalid port number from relay server: " << string;
return false;
}
return true;
}
} // namespace
P2PPortAllocator::P2PPortAllocator(
WebKit::WebFrame* web_frame,
P2PSocketDispatcher* socket_dispatcher,
talk_base::NetworkManager* network_manager,
talk_base::PacketSocketFactory* socket_factory,
const webkit_glue::P2PTransport::Config& config)
: cricket::BasicPortAllocator(network_manager, socket_factory),
web_frame_(web_frame),
socket_dispatcher_(socket_dispatcher),
config_(config) {
uint32 flags = 0;
if (config_.disable_tcp_transport)
flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
set_flags(flags);
}
P2PPortAllocator::~P2PPortAllocator() {
}
cricket::PortAllocatorSession* P2PPortAllocator::CreateSession(
const std::string& name,
const std::string& session_type) {
return new P2PPortAllocatorSession(this, name, session_type);
}
P2PPortAllocatorSession::P2PPortAllocatorSession(
P2PPortAllocator* allocator,
const std::string& name,
const std::string& session_type)
: cricket::BasicPortAllocatorSession(allocator, name, session_type),
allocator_(allocator),
relay_session_attempts_(0),
relay_udp_port_(0),
relay_tcp_port_(0),
relay_ssltcp_port_(0) {
}
P2PPortAllocatorSession::~P2PPortAllocatorSession() {
if (stun_address_request_)
stun_address_request_->Cancel();
}
void P2PPortAllocatorSession::didReceiveData(
WebURLLoader* loader, const char* data,
int data_length, int encoded_data_length) {
DCHECK_EQ(loader, relay_session_request_.get());
if (static_cast<int>(relay_session_response_.size()) + data_length >
kMaximumRelayResponseSize) {
LOG(ERROR) << "Response received from the server is too big.";
loader->cancel();
return;
}
relay_session_response_.append(data, data + data_length);
}
void P2PPortAllocatorSession::didFinishLoading(WebURLLoader* loader,
double finish_time) {
ParseRelayResponse();
}
void P2PPortAllocatorSession::didFail(WebKit::WebURLLoader* loader,
const WebKit::WebURLError& error) {
DCHECK_EQ(loader, relay_session_request_.get());
DCHECK_NE(error.reason, 0);
LOG(ERROR) << "Relay session request failed.";
// Retry the request.
AllocateRelaySession();
}
void P2PPortAllocatorSession::GetPortConfigurations() {
// Add an empty configuration synchronously, so a local connection
// can be started immediately.
ConfigReady(new cricket::PortConfiguration(
talk_base::SocketAddress(), "", "", ""));
ResolveStunServerAddress();
AllocateRelaySession();
}
void P2PPortAllocatorSession::ResolveStunServerAddress() {
if (allocator_->config_.stun_server.empty())
return;
DCHECK(!stun_address_request_);
stun_address_request_ =
new P2PHostAddressRequest(allocator_->socket_dispatcher_);
stun_address_request_->Request(allocator_->config_.stun_server, base::Bind(
&P2PPortAllocatorSession::OnStunServerAddress,
base::Unretained(this)));
}
void P2PPortAllocatorSession::OnStunServerAddress(
const net::IPAddressNumber& address) {
if (address.empty()) {
LOG(ERROR) << "Failed to resolve STUN server address "
<< allocator_->config_.stun_server;
return;
}
if (!jingle_glue::IPEndPointToSocketAddress(
net::IPEndPoint(address, allocator_->config_.stun_server_port),
&stun_server_address_)) {
return;
}
AddConfig();
}
void P2PPortAllocatorSession::AllocateRelaySession() {
if (allocator_->config_.relay_server.empty())
return;
if (!allocator_->config_.legacy_relay) {
NOTIMPLEMENTED() << " TURN support is not implemented yet.";
return;
}
if (relay_session_attempts_ > kRelaySessionRetries)
return;
relay_session_attempts_++;
relay_session_response_.clear();
WebURLLoaderOptions options;
options.allowCredentials = false;
// TODO(sergeyu): Set to CrossOriginRequestPolicyUseAccessControl
// when this code can be used by untrusted plugins.
// See http://crbug.com/104195 .
options.crossOriginRequestPolicy =
WebURLLoaderOptions::CrossOriginRequestPolicyAllow;
relay_session_request_.reset(
allocator_->web_frame_->createAssociatedURLLoader(options));
if (!relay_session_request_.get()) {
LOG(ERROR) << "Failed to create URL loader.";
return;
}
WebURLRequest request;
request.initialize();
request.setURL(WebURL(GURL(
"https://" + allocator_->config_.relay_server + kCreateRelaySessionURL)));
request.setAllowStoredCredentials(false);
request.setCachePolicy(WebURLRequest::ReloadIgnoringCacheData);
request.setHTTPMethod("GET");
request.addHTTPHeaderField(
WebString::fromUTF8("X-Talk-Google-Relay-Auth"),
WebString::fromUTF8(allocator_->config_.relay_password));
request.addHTTPHeaderField(
WebString::fromUTF8("X-Google-Relay-Auth"),
WebString::fromUTF8(allocator_->config_.relay_password));
request.addHTTPHeaderField(WebString::fromUTF8("X-Session-Type"),
WebString::fromUTF8(session_type()));
request.addHTTPHeaderField(WebString::fromUTF8("X-Stream-Type"),
WebString::fromUTF8(name()));
relay_session_request_->loadAsynchronously(request, this);
}
void P2PPortAllocatorSession::ParseRelayResponse() {
std::vector<std::pair<std::string, std::string> > value_pairs;
if (!base::SplitStringIntoKeyValuePairs(relay_session_response_, '=', '\n',
&value_pairs)) {
LOG(ERROR) << "Received invalid response from relay server";
return;
}
relay_username_.clear();
relay_password_.clear();
relay_ip_.Clear();
relay_udp_port_ = 0;
relay_tcp_port_ = 0;
relay_ssltcp_port_ = 0;
for (std::vector<std::pair<std::string, std::string> >::iterator
it = value_pairs.begin();
it != value_pairs.end(); ++it) {
std::string key;
std::string value;
TrimWhitespaceASCII(it->first, TRIM_ALL, &key);
TrimWhitespaceASCII(it->second, TRIM_ALL, &value);
if (key == "username") {
relay_username_ = value;
} else if (key == "password") {
relay_password_ = value;
} else if (key == "relay.ip") {
relay_ip_.SetIP(value);
if (relay_ip_.ip() == 0) {
LOG(ERROR) << "Received unresolved relay server address: " << value;
return;
}
} else if (key == "relay.udp_port") {
if (!ParsePortNumber(value, &relay_udp_port_))
return;
} else if (key == "relay.tcp_port") {
if (!ParsePortNumber(value, &relay_tcp_port_))
return;
} else if (key == "relay.ssltcp_port") {
if (!ParsePortNumber(value, &relay_ssltcp_port_))
return;
}
}
AddConfig();
}
void P2PPortAllocatorSession::AddConfig() {
cricket::PortConfiguration* config =
new cricket::PortConfiguration(stun_server_address_,
relay_username_, relay_password_, "");
cricket::PortConfiguration::PortList ports;
if (relay_ip_.ip() != 0) {
if (relay_udp_port_ > 0) {
talk_base::SocketAddress address(relay_ip_.ip(), relay_udp_port_);
ports.push_back(cricket::ProtocolAddress(address, cricket::PROTO_UDP));
}
if (relay_tcp_port_ > 0 && !allocator_->config_.disable_tcp_transport) {
talk_base::SocketAddress address(relay_ip_.ip(), relay_tcp_port_);
ports.push_back(cricket::ProtocolAddress(address, cricket::PROTO_TCP));
}
if (relay_ssltcp_port_ > 0 && !allocator_->config_.disable_tcp_transport) {
talk_base::SocketAddress address(relay_ip_.ip(), relay_ssltcp_port_);
ports.push_back(cricket::ProtocolAddress(address, cricket::PROTO_SSLTCP));
}
}
config->AddRelay(ports, 0.0f);
ConfigReady(config);
}
} // namespace content
<|endoftext|>
|
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen
// =============================================================================
//
// Irrlicht-based GUI driver for the HMMWV9 model. This class implements the
// functionality required by its base ChDriver class using keyboard inputs.
// As an Irrlicht event receiver, its OnEvent() callback is used to keep track
// and update the current driver inputs. As such it does not need to override
// the default no-op Update() virtual method.
//
// In addition, this class provides additional Irrlicht support for the HMMWV9
// model:
// - implements a custom camera (which follows the vehicle)
// - provides support for rendering links, force elements, displaying stats,
// etc. Its DrawAll() method must be invoked every time the Irrlicht scene
// is redrawn, after the call to ChIrrAppInterface::DrawAll().
//
// =============================================================================
#include "HMMWV9_IrrGuiDriver.h"
using namespace chrono;
using namespace irr;
namespace hmmwv9 {
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
HMMWV9_IrrGuiDriver::HMMWV9_IrrGuiDriver(ChIrrApp& app,
const HMMWV9_Vehicle& car,
int tlc_X,
int tlc_Y)
: m_app(app),
m_car(car),
m_terrainHeight(0)
{
app.SetUserEventReceiver(this);
gui::IGUIStaticText* text_inputs = app.GetIGUIEnvironment()->addStaticText(
L"", core::rect<s32>(tlc_X, tlc_Y, tlc_X + 200, tlc_Y + 75), true, false, 0, -1, true);
text_inputs->setBackgroundColor(video::SColor(255, 200, 200, 200));
m_text_throttle = app.GetIGUIEnvironment()->addStaticText(
L"Throttle: 0",
core::rect<s32>(10, 10, 150, 25), false, false, text_inputs);
m_text_steering = app.GetIGUIEnvironment()->addStaticText(
L"Steering: 0",
core::rect<s32>(10, 30, 150, 45), false, false, text_inputs);
m_text_speed = app.GetIGUIEnvironment()->addStaticText(
L"Speed: 0",
core::rect<s32>(10, 50, 150, 65), false, false, text_inputs);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
bool HMMWV9_IrrGuiDriver::OnEvent(const SEvent& event)
{
// user hit a key, while not holding it down
if (event.EventType == EET_KEY_INPUT_EVENT && !event.KeyInput.PressedDown)
{
char msg[100];
switch (event.KeyInput.Key) {
case KEY_KEY_A:
setSteering(m_steering - 0.1);
sprintf(msg, "Steering: %+.2f", m_steering);
m_text_steering->setText(core::stringw(msg).c_str());
return true;
case KEY_KEY_D:
setSteering(m_steering + 0.1);
sprintf(msg, "Steering: %+.2f", m_steering);
m_text_steering->setText(core::stringw(msg).c_str());
return true;
case KEY_KEY_W:
setThrottle(m_throttle + 0.1);
sprintf(msg, "Throttle: %+.2f", m_throttle*100.);
m_text_throttle->setText(core::stringw(msg).c_str());
return true;
case KEY_KEY_S:
setThrottle(m_throttle - 0.1);
sprintf(msg, "Throttle: %+.2f", m_throttle*100.);
m_text_throttle->setText(core::stringw(msg).c_str());
return true;
case KEY_DOWN:
m_cam_multiplier *= 1.01;
return true;
case KEY_UP:
m_cam_multiplier /= 1.01;
}
}
return false;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void HMMWV9_IrrGuiDriver::CreateCamera(const chrono::ChVector<>& cam_offset)
{
m_cam_multiplier = 1;
m_cam_offset = cam_offset;
m_app.GetSceneManager()->addCameraSceneNode(
m_app.GetSceneManager()->getRootSceneNode(),
core::vector3df(0, 0, 0), core::vector3df(0, 0, 0));
m_app.GetSceneManager()->getActiveCamera()->setUpVector(core::vector3df(0, 0, 1));
updateCamera();
}
void HMMWV9_IrrGuiDriver::updateCamera()
{
const ChVector<>& car_pos = m_car.GetChassisPos();
ChVector<> cam_pos = m_car.GetChassis()->GetCoord().TrasformLocalToParent(m_cam_multiplier * m_cam_offset);
scene::ICameraSceneNode *camera = m_app.GetSceneManager()->getActiveCamera();
camera->setPosition(core::vector3df((f32)cam_pos.x, (f32)cam_pos.y, (f32)cam_pos.z));
camera->setTarget(core::vector3df((f32)car_pos.x, (f32)car_pos.y, (f32)car_pos.z));
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void HMMWV9_IrrGuiDriver::DrawAll()
{
updateCamera();
renderGrid();
m_app.DrawAll();
renderSprings();
renderLinks();
renderStats();
}
void HMMWV9_IrrGuiDriver::renderSprings()
{
std::list<chrono::ChLink*>::iterator ilink = m_app.GetSystem()->Get_linklist()->begin();
for (; ilink != m_app.GetSystem()->Get_linklist()->end(); ++ilink) {
if (ChLinkSpring* link = dynamic_cast<ChLinkSpring*>(*ilink)) {
ChIrrTools::drawSpring(m_app.GetVideoDriver(), 0.05,
link->GetEndPoint1Abs(),
link->GetEndPoint2Abs(),
video::SColor(255, 150, 20, 20), 80, 15, true);
}
}
}
void HMMWV9_IrrGuiDriver::renderLinks()
{
std::list<chrono::ChLink*>::iterator ilink = m_app.GetSystem()->Get_linklist()->begin();
for (; ilink != m_app.GetSystem()->Get_linklist()->end(); ++ilink) {
if (ChLinkDistance* link = dynamic_cast<ChLinkDistance*>(*ilink)) {
ChIrrTools::drawSegment(m_app.GetVideoDriver(),
link->GetEndPoint1Abs(),
link->GetEndPoint2Abs(),
video::SColor(255, 0, 20, 0), true);
}
}
}
void HMMWV9_IrrGuiDriver::renderGrid()
{
ChCoordsys<> gridCsys(ChVector<>(0, 0, m_terrainHeight + 0.02),
chrono::Q_from_AngAxis(-CH_C_PI_2, VECT_Z));
ChIrrTools::drawGrid(m_app.GetVideoDriver(),
0.5, 0.5, 100, 100,
gridCsys,
video::SColor(255, 80, 130, 255),
true);
}
void HMMWV9_IrrGuiDriver::renderStats()
{
char msg[100];
sprintf(msg, "Speed: %+.2f", m_car.GetVehicleSpeed());
m_text_speed->setText(core::stringw(msg).c_str());
}
} // end namespace hmmwv9
<commit_msg>Fix comment.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen
// =============================================================================
//
// Irrlicht-based GUI driver for the HMMWV9 model. This class implements the
// functionality required by its base ChDriver class using keyboard inputs.
// As an Irrlicht event receiver, its OnEvent() callback is used to keep track
// and update the current driver inputs. As such it does not need to override
// the default no-op Update() virtual method.
//
// In addition, this class provides additional Irrlicht support for the HMMWV9
// model:
// - implements a custom camera (which follows the vehicle)
// - provides support for rendering links, force elements, displaying stats,
// etc. In order to render these elements, call the its DrawAll() method
// instead of ChIrrAppInterface::DrawAll().
//
// =============================================================================
#include "HMMWV9_IrrGuiDriver.h"
using namespace chrono;
using namespace irr;
namespace hmmwv9 {
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
HMMWV9_IrrGuiDriver::HMMWV9_IrrGuiDriver(ChIrrApp& app,
const HMMWV9_Vehicle& car,
int tlc_X,
int tlc_Y)
: m_app(app),
m_car(car),
m_terrainHeight(0)
{
app.SetUserEventReceiver(this);
gui::IGUIStaticText* text_inputs = app.GetIGUIEnvironment()->addStaticText(
L"", core::rect<s32>(tlc_X, tlc_Y, tlc_X + 200, tlc_Y + 75), true, false, 0, -1, true);
text_inputs->setBackgroundColor(video::SColor(255, 200, 200, 200));
m_text_throttle = app.GetIGUIEnvironment()->addStaticText(
L"Throttle: 0",
core::rect<s32>(10, 10, 150, 25), false, false, text_inputs);
m_text_steering = app.GetIGUIEnvironment()->addStaticText(
L"Steering: 0",
core::rect<s32>(10, 30, 150, 45), false, false, text_inputs);
m_text_speed = app.GetIGUIEnvironment()->addStaticText(
L"Speed: 0",
core::rect<s32>(10, 50, 150, 65), false, false, text_inputs);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
bool HMMWV9_IrrGuiDriver::OnEvent(const SEvent& event)
{
// user hit a key, while not holding it down
if (event.EventType == EET_KEY_INPUT_EVENT && !event.KeyInput.PressedDown)
{
char msg[100];
switch (event.KeyInput.Key) {
case KEY_KEY_A:
setSteering(m_steering - 0.1);
sprintf(msg, "Steering: %+.2f", m_steering);
m_text_steering->setText(core::stringw(msg).c_str());
return true;
case KEY_KEY_D:
setSteering(m_steering + 0.1);
sprintf(msg, "Steering: %+.2f", m_steering);
m_text_steering->setText(core::stringw(msg).c_str());
return true;
case KEY_KEY_W:
setThrottle(m_throttle + 0.1);
sprintf(msg, "Throttle: %+.2f", m_throttle*100.);
m_text_throttle->setText(core::stringw(msg).c_str());
return true;
case KEY_KEY_S:
setThrottle(m_throttle - 0.1);
sprintf(msg, "Throttle: %+.2f", m_throttle*100.);
m_text_throttle->setText(core::stringw(msg).c_str());
return true;
case KEY_DOWN:
m_cam_multiplier *= 1.01;
return true;
case KEY_UP:
m_cam_multiplier /= 1.01;
}
}
return false;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void HMMWV9_IrrGuiDriver::CreateCamera(const chrono::ChVector<>& cam_offset)
{
m_cam_multiplier = 1;
m_cam_offset = cam_offset;
m_app.GetSceneManager()->addCameraSceneNode(
m_app.GetSceneManager()->getRootSceneNode(),
core::vector3df(0, 0, 0), core::vector3df(0, 0, 0));
m_app.GetSceneManager()->getActiveCamera()->setUpVector(core::vector3df(0, 0, 1));
updateCamera();
}
void HMMWV9_IrrGuiDriver::updateCamera()
{
const ChVector<>& car_pos = m_car.GetChassisPos();
ChVector<> cam_pos = m_car.GetChassis()->GetCoord().TrasformLocalToParent(m_cam_multiplier * m_cam_offset);
scene::ICameraSceneNode *camera = m_app.GetSceneManager()->getActiveCamera();
camera->setPosition(core::vector3df((f32)cam_pos.x, (f32)cam_pos.y, (f32)cam_pos.z));
camera->setTarget(core::vector3df((f32)car_pos.x, (f32)car_pos.y, (f32)car_pos.z));
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void HMMWV9_IrrGuiDriver::DrawAll()
{
updateCamera();
renderGrid();
m_app.DrawAll();
renderSprings();
renderLinks();
renderStats();
}
void HMMWV9_IrrGuiDriver::renderSprings()
{
std::list<chrono::ChLink*>::iterator ilink = m_app.GetSystem()->Get_linklist()->begin();
for (; ilink != m_app.GetSystem()->Get_linklist()->end(); ++ilink) {
if (ChLinkSpring* link = dynamic_cast<ChLinkSpring*>(*ilink)) {
ChIrrTools::drawSpring(m_app.GetVideoDriver(), 0.05,
link->GetEndPoint1Abs(),
link->GetEndPoint2Abs(),
video::SColor(255, 150, 20, 20), 80, 15, true);
}
}
}
void HMMWV9_IrrGuiDriver::renderLinks()
{
std::list<chrono::ChLink*>::iterator ilink = m_app.GetSystem()->Get_linklist()->begin();
for (; ilink != m_app.GetSystem()->Get_linklist()->end(); ++ilink) {
if (ChLinkDistance* link = dynamic_cast<ChLinkDistance*>(*ilink)) {
ChIrrTools::drawSegment(m_app.GetVideoDriver(),
link->GetEndPoint1Abs(),
link->GetEndPoint2Abs(),
video::SColor(255, 0, 20, 0), true);
}
}
}
void HMMWV9_IrrGuiDriver::renderGrid()
{
ChCoordsys<> gridCsys(ChVector<>(0, 0, m_terrainHeight + 0.02),
chrono::Q_from_AngAxis(-CH_C_PI_2, VECT_Z));
ChIrrTools::drawGrid(m_app.GetVideoDriver(),
0.5, 0.5, 100, 100,
gridCsys,
video::SColor(255, 80, 130, 255),
true);
}
void HMMWV9_IrrGuiDriver::renderStats()
{
char msg[100];
sprintf(msg, "Speed: %+.2f", m_car.GetVehicleSpeed());
m_text_speed->setText(core::stringw(msg).c_str());
}
} // end namespace hmmwv9
<|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>/** \file augment_time_aspects.cc
* \brief A tool for adding normalised time references to MARC-21 datasets.
* \author Dr. Johannes Ruscheinski
*/
/*
Copyright (C) 2019-2021, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unordered_map>
#include <cstdlib>
#include "Compiler.h"
#include "MARC.h"
#include "RangeUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "util.h"
namespace {
static const std::vector<std::string> TIME_ASPECT_GND_LINKING_TAGS{ "689" };
static const std::vector<std::string> KEYWORD_PREFIXES{ "Geschichte ", "Geistesgeschichte ", "Ideengeschichte ", "Kirchengeschichte ",
"Sozialgeschichte ", "Vor- und Frühgeschichte ", "Weltgeschichte ", "Prognose " };
inline std::vector<std::string>::const_iterator FindFirstPrefixMatch(const std::string &s, const std::vector<std::string> &prefixes) {
for (auto prefix(prefixes.cbegin()); prefix != prefixes.cend(); ++prefix) {
if (StringUtil::StartsWith(s, *prefix))
return prefix;
}
return prefixes.cend();
}
void LoadAuthorityData(MARC::Reader * const reader,
std::unordered_map<std::string, std::string> * const authority_ppns_to_time_codes_map,
std::unordered_map<std::string, std::string> * const authority_ppns_to_time_categories_map)
{
unsigned total_count(0);
while (auto record = reader->read()) {
++total_count;
bool found_548(false);
auto _548_field(record.findTag("548"));
while (_548_field != record.end()) {
if (_548_field->hasSubfieldWithValue('i', "Zeitraum")) {
const std::string free_form_range_candidate(_548_field->getFirstSubfieldWithCode('a'));
std::string range;
if (RangeUtil::ConvertTextToTimeRange(free_form_range_candidate, &range, /* special_case_centuries = */ true)) {
(*authority_ppns_to_time_codes_map)[record.getControlNumber()] = range;
found_548 = true;
const auto _150_field(record.findTag("150"));
if (_150_field != record.end() and _150_field->hasSubfield('a')) {
std::string _150a_subfield = _150_field->getFirstSubfieldWithCode('a');
_150a_subfield = _150a_subfield + " " + free_form_range_candidate;
(*authority_ppns_to_time_categories_map)[record.getControlNumber()] = _150a_subfield;
}
break;
} else
LOG_WARNING("can't convert \"" + free_form_range_candidate + "\" to a time range!");
}
_548_field++;
}
if (found_548 == false) {
auto _450_field(record.findTag("450"));
while (_450_field != record.end()) {
if (_450_field->hasSubfield('a')) {
std::string _450a_subfield = _450_field->getFirstSubfieldWithCode('a');
const auto matched_prefix(FindFirstPrefixMatch(_450a_subfield, KEYWORD_PREFIXES));
if (matched_prefix != KEYWORD_PREFIXES.cend()) {
std::string range;
if (RangeUtil::ConvertTextToTimeRange(_450a_subfield.substr(matched_prefix->length()), &range)) {
(*authority_ppns_to_time_codes_map)[record.getControlNumber()] = range;
(*authority_ppns_to_time_categories_map)[record.getControlNumber()] = _450a_subfield;
break;
}
}
}
_450_field++;
}
}
}
LOG_INFO("found " + std::to_string(authority_ppns_to_time_codes_map->size()) + " time aspect records among "
+ std::to_string(total_count) + " authority records.");
}
void CollectAuthorityPPNs(const MARC::Record &record, const MARC::Tag &linking_field,
std::vector<std::string> * const authority_ppns)
{
for (const auto &field : record.getTagRange(linking_field)) {
const MARC::Subfields subfields(field.getSubfields());
for (const auto &subfield : subfields) {
if (subfield.code_ == '0' and StringUtil::StartsWith(subfield.value_, "(DE-627)"))
authority_ppns->emplace_back(subfield.value_.substr(__builtin_strlen("(DE-627)")));
}
}
}
void ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer,
const std::unordered_map<std::string, std::string> &authority_ppns_to_time_codes_map,
const std::unordered_map<std::string, std::string> &authority_ppns_to_time_categories_map)
{
unsigned total_count(0), augmented_count(0);
while (auto record = reader->read()) {
++total_count;
std::string range;
std::string category;
for (const std::string &tag : TIME_ASPECT_GND_LINKING_TAGS) {
for (const auto &time_aspect_field : record.getTagRange(tag)) {
auto a_subfield(time_aspect_field.getFirstSubfieldWithCode('a'));
const auto matched_prefix(FindFirstPrefixMatch(a_subfield, KEYWORD_PREFIXES));
if (matched_prefix == KEYWORD_PREFIXES.cend())
continue;
// Special handling of ranges like "Kirchengeschichte Anfänge-1600":
if (StringUtil::StartsWith(a_subfield, "Kirchengeschichte Anfänge-"))
a_subfield = "Kirchengeschichte 30" + a_subfield.substr(__builtin_strlen("Kirchengeschichte Anfänge"));
if (RangeUtil::ConvertTextToTimeRange(a_subfield.substr(matched_prefix->length()), &range)) {
category = a_subfield;
goto augment_record;
}
}
std::vector<std::string> authority_ppns;
CollectAuthorityPPNs(record, tag, &authority_ppns);
for (const auto &authority_ppn : authority_ppns) {
const auto authority_ppn_and_time_code(authority_ppns_to_time_codes_map.find(authority_ppn));
if (authority_ppn_and_time_code != authority_ppns_to_time_codes_map.cend()) {
range = authority_ppn_and_time_code->second;
const auto authority_ppn_and_category_code(authority_ppns_to_time_categories_map.find(authority_ppn));
if (authority_ppn_and_category_code != authority_ppns_to_time_categories_map.cend()) {
category = authority_ppn_and_category_code->second;
}
goto augment_record;
}
}
}
augment_record:
if (not range.empty()) {
record.insertField("TIM", { { 'a', range }, {'b', category.length() == 0 ? RangeUtil::ConvertTimeRangeToText(range) : category} });
++augmented_count;
}
writer->write(record);
}
LOG_INFO("augmented " + std::to_string(augmented_count) + " of " + std::to_string(total_count) + " records.");
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc != 4)
::Usage("ixtheo_titles authority_records augmented_ixtheo_titles");
const std::string title_input_filename(argv[1]);
const std::string authority_filename(argv[2]);
const std::string title_output_filename(argv[3]);
if (unlikely(title_input_filename == title_output_filename))
LOG_ERROR("Title input file name equals title output file name!");
if (unlikely(title_input_filename == authority_filename))
LOG_ERROR("Title input file name equals authority file name!");
if (unlikely(title_output_filename == authority_filename))
LOG_ERROR("Title output file name equals authority file name!");
auto authority_reader(MARC::Reader::Factory(authority_filename));
std::unordered_map<std::string, std::string> authority_ppns_to_time_codes_map;
std::unordered_map<std::string, std::string> authority_ppns_to_time_categories_map;
LoadAuthorityData(authority_reader.get(), &authority_ppns_to_time_codes_map, &authority_ppns_to_time_categories_map);
auto title_reader(MARC::Reader::Factory(title_input_filename));
auto title_writer(MARC::Writer::Factory(title_output_filename));
ProcessRecords(title_reader.get(), title_writer.get(), authority_ppns_to_time_codes_map, authority_ppns_to_time_categories_map);
return EXIT_SUCCESS;
}
<commit_msg>Improved logging.<commit_after>/** \file augment_time_aspects.cc
* \brief A tool for adding normalised time references to MARC-21 datasets.
* \author Dr. Johannes Ruscheinski
*/
/*
Copyright (C) 2019-2021, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unordered_map>
#include <cstdlib>
#include "Compiler.h"
#include "MARC.h"
#include "RangeUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "util.h"
namespace {
static const std::vector<std::string> TIME_ASPECT_GND_LINKING_TAGS{ "689" };
static const std::vector<std::string> KEYWORD_PREFIXES{ "Geschichte ", "Geistesgeschichte ", "Ideengeschichte ", "Kirchengeschichte ",
"Sozialgeschichte ", "Vor- und Frühgeschichte ", "Weltgeschichte ", "Prognose " };
inline std::vector<std::string>::const_iterator FindFirstPrefixMatch(const std::string &s, const std::vector<std::string> &prefixes) {
for (auto prefix(prefixes.cbegin()); prefix != prefixes.cend(); ++prefix) {
if (StringUtil::StartsWith(s, *prefix))
return prefix;
}
return prefixes.cend();
}
void LoadAuthorityData(MARC::Reader * const reader,
std::unordered_map<std::string, std::string> * const authority_ppns_to_time_codes_map,
std::unordered_map<std::string, std::string> * const authority_ppns_to_time_categories_map)
{
unsigned total_count(0);
while (auto record = reader->read()) {
++total_count;
bool found_548(false);
auto _548_field(record.findTag("548"));
while (_548_field != record.end()) {
if (_548_field->hasSubfieldWithValue('i', "Zeitraum")) {
const std::string free_form_range_candidate(_548_field->getFirstSubfieldWithCode('a'));
std::string range;
if (RangeUtil::ConvertTextToTimeRange(free_form_range_candidate, &range, /* special_case_centuries = */ true)) {
(*authority_ppns_to_time_codes_map)[record.getControlNumber()] = range;
found_548 = true;
const auto _150_field(record.findTag("150"));
if (_150_field != record.end() and _150_field->hasSubfield('a')) {
std::string _150a_subfield = _150_field->getFirstSubfieldWithCode('a');
_150a_subfield = _150a_subfield + " " + free_form_range_candidate;
(*authority_ppns_to_time_categories_map)[record.getControlNumber()] = _150a_subfield;
}
break;
} else
LOG_WARNING("can't convert \"" + free_form_range_candidate + "\" to a time range! (PPN: "
+ record.getControlNumber() + ")");
}
_548_field++;
}
if (found_548 == false) {
auto _450_field(record.findTag("450"));
while (_450_field != record.end()) {
if (_450_field->hasSubfield('a')) {
std::string _450a_subfield = _450_field->getFirstSubfieldWithCode('a');
const auto matched_prefix(FindFirstPrefixMatch(_450a_subfield, KEYWORD_PREFIXES));
if (matched_prefix != KEYWORD_PREFIXES.cend()) {
std::string range;
if (RangeUtil::ConvertTextToTimeRange(_450a_subfield.substr(matched_prefix->length()), &range)) {
(*authority_ppns_to_time_codes_map)[record.getControlNumber()] = range;
(*authority_ppns_to_time_categories_map)[record.getControlNumber()] = _450a_subfield;
break;
}
}
}
_450_field++;
}
}
}
LOG_INFO("found " + std::to_string(authority_ppns_to_time_codes_map->size()) + " time aspect records among "
+ std::to_string(total_count) + " authority records.");
}
void CollectAuthorityPPNs(const MARC::Record &record, const MARC::Tag &linking_field,
std::vector<std::string> * const authority_ppns)
{
for (const auto &field : record.getTagRange(linking_field)) {
const MARC::Subfields subfields(field.getSubfields());
for (const auto &subfield : subfields) {
if (subfield.code_ == '0' and StringUtil::StartsWith(subfield.value_, "(DE-627)"))
authority_ppns->emplace_back(subfield.value_.substr(__builtin_strlen("(DE-627)")));
}
}
}
void ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer,
const std::unordered_map<std::string, std::string> &authority_ppns_to_time_codes_map,
const std::unordered_map<std::string, std::string> &authority_ppns_to_time_categories_map)
{
unsigned total_count(0), augmented_count(0);
while (auto record = reader->read()) {
++total_count;
std::string range;
std::string category;
for (const std::string &tag : TIME_ASPECT_GND_LINKING_TAGS) {
for (const auto &time_aspect_field : record.getTagRange(tag)) {
auto a_subfield(time_aspect_field.getFirstSubfieldWithCode('a'));
const auto matched_prefix(FindFirstPrefixMatch(a_subfield, KEYWORD_PREFIXES));
if (matched_prefix == KEYWORD_PREFIXES.cend())
continue;
// Special handling of ranges like "Kirchengeschichte Anfänge-1600":
if (StringUtil::StartsWith(a_subfield, "Kirchengeschichte Anfänge-"))
a_subfield = "Kirchengeschichte 30" + a_subfield.substr(__builtin_strlen("Kirchengeschichte Anfänge"));
if (RangeUtil::ConvertTextToTimeRange(a_subfield.substr(matched_prefix->length()), &range)) {
category = a_subfield;
goto augment_record;
}
}
std::vector<std::string> authority_ppns;
CollectAuthorityPPNs(record, tag, &authority_ppns);
for (const auto &authority_ppn : authority_ppns) {
const auto authority_ppn_and_time_code(authority_ppns_to_time_codes_map.find(authority_ppn));
if (authority_ppn_and_time_code != authority_ppns_to_time_codes_map.cend()) {
range = authority_ppn_and_time_code->second;
const auto authority_ppn_and_category_code(authority_ppns_to_time_categories_map.find(authority_ppn));
if (authority_ppn_and_category_code != authority_ppns_to_time_categories_map.cend()) {
category = authority_ppn_and_category_code->second;
}
goto augment_record;
}
}
}
augment_record:
if (not range.empty()) {
record.insertField("TIM", { { 'a', range }, {'b', category.length() == 0 ? RangeUtil::ConvertTimeRangeToText(range) : category} });
++augmented_count;
}
writer->write(record);
}
LOG_INFO("augmented " + std::to_string(augmented_count) + " of " + std::to_string(total_count) + " records.");
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc != 4)
::Usage("ixtheo_titles authority_records augmented_ixtheo_titles");
const std::string title_input_filename(argv[1]);
const std::string authority_filename(argv[2]);
const std::string title_output_filename(argv[3]);
if (unlikely(title_input_filename == title_output_filename))
LOG_ERROR("Title input file name equals title output file name!");
if (unlikely(title_input_filename == authority_filename))
LOG_ERROR("Title input file name equals authority file name!");
if (unlikely(title_output_filename == authority_filename))
LOG_ERROR("Title output file name equals authority file name!");
auto authority_reader(MARC::Reader::Factory(authority_filename));
std::unordered_map<std::string, std::string> authority_ppns_to_time_codes_map;
std::unordered_map<std::string, std::string> authority_ppns_to_time_categories_map;
LoadAuthorityData(authority_reader.get(), &authority_ppns_to_time_codes_map, &authority_ppns_to_time_categories_map);
auto title_reader(MARC::Reader::Factory(title_input_filename));
auto title_writer(MARC::Writer::Factory(title_output_filename));
ProcessRecords(title_reader.get(), title_writer.get(), authority_ppns_to_time_codes_map, authority_ppns_to_time_categories_map);
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/flex/allowlisted_flex_ops.h"
#include <set>
#include <gtest/gtest.h>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/lite/delegates/flex/allowlisted_flex_ops_internal.h"
namespace tflite {
namespace flex {
// Get all cpu kernels registered in Tensorflow.
std::set<string> GetAllCpuKernels() {
auto is_cpu_kernel = [](const tensorflow::KernelDef& def) {
return (def.device_type() == "CPU" || def.device_type() == "DEFAULT");
};
tensorflow::KernelList kernel_list =
tensorflow::GetFilteredRegisteredKernels(is_cpu_kernel);
std::set<string> result;
for (int i = 0; i < kernel_list.kernel_size(); ++i) {
tensorflow::KernelDef kernel_def = kernel_list.kernel(i);
result.insert(kernel_def.op());
}
return result;
}
// Test if every flex op has their kernel included in the flex delegate library.
// This test must be run on both Linux and Android.
TEST(AllowlistedFlexOpsTest, EveryOpHasKernel) {
const std::set<std::string>& allowlist = GetFlexAllowlist();
std::set<string> all_kernels = GetAllCpuKernels();
for (const std::string& op_name : allowlist) {
EXPECT_EQ(all_kernels.count(op_name), 1)
<< op_name << " op is added to flex allowlist "
<< "but its kernel is not found.";
}
}
} // namespace flex
} // namespace tflite
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Use `std::string` instead of `string`<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/flex/allowlisted_flex_ops.h"
#include <set>
#include <gtest/gtest.h>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/lite/delegates/flex/allowlisted_flex_ops_internal.h"
namespace tflite {
namespace flex {
// Get all cpu kernels registered in Tensorflow.
std::set<std::string> GetAllCpuKernels() {
auto is_cpu_kernel = [](const tensorflow::KernelDef& def) {
return (def.device_type() == "CPU" || def.device_type() == "DEFAULT");
};
tensorflow::KernelList kernel_list =
tensorflow::GetFilteredRegisteredKernels(is_cpu_kernel);
std::set<std::string> result;
for (int i = 0; i < kernel_list.kernel_size(); ++i) {
tensorflow::KernelDef kernel_def = kernel_list.kernel(i);
result.insert(kernel_def.op());
}
return result;
}
// Test if every flex op has their kernel included in the flex delegate library.
// This test must be run on both Linux and Android.
TEST(AllowlistedFlexOpsTest, EveryOpHasKernel) {
const std::set<std::string>& allowlist = GetFlexAllowlist();
std::set<std::string> all_kernels = GetAllCpuKernels();
for (const std::string& op_name : allowlist) {
EXPECT_EQ(all_kernels.count(op_name), 1)
<< op_name << " op is added to flex allowlist "
<< "but its kernel is not found.";
}
}
} // namespace flex
} // namespace tflite
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>/**
* \file
* \brief FpuSignalTestCase class implementation for ARMv7-M
*
* \author Copyright (C) 2015-2019 Kamil Szczygiel https://distortec.com https://freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#include "ARMv7-M-FpuSignalTestCase.hpp"
#include "distortos/chip/CMSIS-proxy.h"
/// configuration required by FpuSignalTestCase
#define ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED __FPU_PRESENT == 1 && __FPU_USED == 1 && DISTORTOS_SIGNALS_ENABLE == 1 && \
DISTORTOS_MAIN_THREAD_SIGNAL_ACTIONS > 0 && DISTORTOS_MAIN_THREAD_QUEUED_SIGNALS > 0
#if ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
#include "ARMv7-M-checkFpuRegisters.hpp"
#include "ARMv7-M-setFpuRegisters.hpp"
#include "distortos/DynamicThread.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread.hpp"
#include "distortos/ThisThread-Signals.hpp"
#include "estd/ScopeGuard.hpp"
#include <cerrno>
#endif // ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
namespace distortos
{
namespace test
{
#if ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// values used in single test stage
struct Stage
{
/// value written to all FPU registers in main thread, don't use FPU in main thread if 0
uint32_t threadValue;
/// value written to "lower" FPU registers in "sender" before queuing of signal, skip this step if 0
uint32_t senderValueBefore;
/// value written to "lower" FPU registers in "sender" after queuing of signal, skip this step if 0
uint32_t senderValueAfter;
/// signal value, written to "lower" FPU registers in handler, don't use FPU in handler if 0
int signalValue;
};
/// description of single test phase
struct Phase
{
/// type of "sender" function
using Sender = int(Thread&, const Stage&);
/// reference to "sender" function
Sender& sender;
/// expected number of context switches for single stage executed in this phase
decltype(statistics::getContextSwitchCount()) contextSwitchCount;
};
/// context shared with interrupt
struct Context
{
/// shared return value
int sharedRet;
/// pointer to test stage
const Stage* stage;
/// pointer to thread to which the signal will be queued
Thread* thread;
};
/*---------------------------------------------------------------------------------------------------------------------+
| local objects
+---------------------------------------------------------------------------------------------------------------------*/
/// tested signal number
constexpr uint8_t testSignalNumber {16};
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {512};
/// pointer to context shared with interrupt
Context* volatile context;
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Disables FPU context for current thread by clearing FPCA bit in CONTROL register.
*/
void disableFpuContext()
{
const auto control = __get_CONTROL();
__set_CONTROL(control & ~CONTROL_FPCA_Msk);
}
/**
* \brief Signal handler
*
* Sets "lower" FPU registers (s0-s15 and fpscr) using the value queued with signal, unless this value is 0.
*
* \param [in] signalInformation is a reference to received SignalInformation object
*/
void handler(const SignalInformation& signalInformation)
{
const auto value = signalInformation.getValue().sival_int;
if (value == 0)
return;
setFpuRegisters(value, false);
}
/**
* \brief Tests whether FPU context is active for current thread.
*
* \return true if FPU context is active for current thread (FPCA bit in CONTROL register is set), false otherwise
*/
bool isFpuContextActive()
{
const auto control = __get_CONTROL();
return (control & CONTROL_FPCA_Msk) != 0;
}
/**
* \brief Test wrapper for Thread::queueSignal() that also modifies FPU registers.
*
* \param [in] thread is a reference to thread to which the signal will be queued
* \param [in] stage is a reference to test stage
* \param [in] full is the \a full argument passed to setFpuRegisters()
* \param [in] sharedRet is a reference to int variable which will be written with 0 on success, error code otherwise
*/
void queueSignalWrapper(Thread& thread, const Stage& stage, const bool full, int& sharedRet)
{
if (stage.senderValueBefore != 0) // should FPU be used at the beginning of "sender"?
setFpuRegisters(stage.senderValueBefore, full);
sharedRet = thread.queueSignal(testSignalNumber, sigval{stage.signalValue});
if (stage.senderValueAfter != 0) // should FPU be used at th"sender""sender"?
setFpuRegisters(stage.senderValueAfter, full);
}
/**
* \brief Queues signal from interrupt (via manually triggered UsageFault) to current thread.
*
* \param [in] thread is a reference to thread to which the signal will be queued
* \param [in] stage is a reference to test stage
*
* \return 0 on success, error code otherwise:
* - error codes returned by Thread::queueSignal();
*/
int queueSignalFromInterrupt(Thread& thread, const Stage& stage)
{
Context localContext {};
context = &localContext;
const auto contextScopeGuard = estd::makeScopeGuard(
[]()
{
context = {};
});
context->thread = &thread;
context->stage = &stage;
SCB->CCR |= SCB_CCR_DIV_0_TRP_Msk; // enable trapping of "divide by 0" by UsageFault
SCB->SHCSR |= SCB_SHCSR_USGFAULTENA_Msk; // enable UsageFault
volatile int a {};
volatile int b {};
a /= b; // trigger UsageFault via "divide by 0"
return context->sharedRet;
}
/**
* \brief Queues signal from thread to non-current thread.
*
* \param [in] thread is a reference to thread to which the signal will be queued
* \param [in] stage is a reference to test stage
*
* \return 0 on success, error code otherwise:
* - error codes returned by Thread::queueSignal();
*/
int queueSignalFromThread(Thread& thread, const Stage& stage)
{
constexpr decltype(FpuSignalTestCase::getTestCasePriority()) highPriority
{
FpuSignalTestCase::getTestCasePriority() + 1
};
int sharedRet {EINVAL};
auto testThread = makeAndStartDynamicThread({testThreadStackSize, highPriority}, queueSignalWrapper,
std::ref(thread), std::ref(stage), true, std::ref(sharedRet));
testThread.join();
return sharedRet;
}
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// test phases
const Phase phases[]
{
{queueSignalFromInterrupt, 0},
{queueSignalFromThread, 2},
};
/// test stages
const Stage stages[]
{
{0, 0, 0, 0}, // don't use FPU in all contexts
{0, 0, 0, 0x0b39fa96}, // in handler
{0, 0, 0x8606151d, 0}, // in "sender" (at the end)
{0, 0, 0x8bdd3b5e, 0x7d21d1c6}, // in "sender" (at the end) and in handler
{0, 0x2f884196, 0, 0}, // in "sender" (at the beginning)
{0, 0x0b0bbc86, 0, 0x0e43811b}, // in "sender" (at the beginning) and in handler
{0, 0xb72b2917, 0x8c27baa7, 0}, // in "sender"
{0, 0xa83b80c2, 0xd2b7dd4d, 0x626ca399}, // in "sender" and in handler
{0xb4e40525, 0, 0, 0}, // in main thread
{0x772bdf91, 0, 0, 0x0bb325b7}, // in main thread and in handler
{0x8a19625e, 0, 0x32378f7b, 0}, // in main thread and in "sender" (at the end)
{0xd17a21db, 0, 0xaa807a91, 0x03caf264}, // in main thread, in "sender" (at the end) and in handler
{0xe4b44073, 0xa88c0cf5, 0, 0}, // in main thread and in "sender" (at the beginning)
{0xb94c722b, 0x5f8ca773, 0, 0x288301cf}, // in main thread, in "sender" (at the beginning) and in handler
{0x347ecfc5, 0xcb4a3584, 0x5a8bf219, 0}, // in main thread and in "sender"
{0x788ed92e, 0x4b0ddff9, 0x73776a21, 0x48fb1969}, // in all contexts
};
} // namespace
#endif // ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
/*---------------------------------------------------------------------------------------------------------------------+
| protected functions
+---------------------------------------------------------------------------------------------------------------------*/
bool FpuSignalTestCase::finalize() const
{
#if ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
disableFpuContext();
#endif // ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
return SignalsTestCaseCommon::finalize();
}
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool FpuSignalTestCase::run_() const
{
#if ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
const auto contextSwitchCount = statistics::getContextSwitchCount();
auto expectedContextSwitchCount = decltype(contextSwitchCount){};
{
int ret;
std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber,
SignalAction{handler, SignalSet{SignalSet::empty}});
if (ret != 0)
return false;
}
auto& currentThread = ThisThread::get();
for (auto& phase : phases)
for (auto& stage : stages)
{
disableFpuContext();
decltype(setFpuRegisters({}, {})) fpscr {};
if (stage.threadValue != 0) // should FPU be used in main thread?
fpscr = setFpuRegisters(stage.threadValue, true);
if (phase.sender(currentThread, stage) != 0)
return false;
// FPU context may be active only if FPU was used in main thread
if (isFpuContextActive() != (stage.threadValue != 0))
return false;
if (stage.threadValue != 0) // was FPU used in main thread?
if (checkFpuRegisters(stage.threadValue, fpscr) == false)
return false;
expectedContextSwitchCount += phase.contextSwitchCount;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
return false;
}
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
return false;
#endif // ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
return true;
}
} // namespace test
} // namespace distortos
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief UsageFault_Handler() for ARMv7-M
*/
extern "C" void UsageFault_Handler()
{
SCB->CFSR = SCB_CFSR_DIVBYZERO_Msk; // clear "divide by 0" flag
SCB->CCR &= ~SCB_CCR_DIV_0_TRP_Msk; // disable trapping of "divide by 0" by UsageFault
SCB->SHCSR &= ~SCB_SHCSR_USGFAULTENA_Msk; // disable UsageFault
using namespace distortos::test;
queueSignalWrapper(*context->thread, *context->stage, false, context->sharedRet);
}
<commit_msg>Fix build test of ARMv7-M-FpuSignalTestCase<commit_after>/**
* \file
* \brief FpuSignalTestCase class implementation for ARMv7-M
*
* \author Copyright (C) 2015-2021 Kamil Szczygiel https://distortec.com https://freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#include "ARMv7-M-FpuSignalTestCase.hpp"
#include "distortos/chip/CMSIS-proxy.h"
/// configuration required by FpuSignalTestCase
#define ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED __FPU_PRESENT == 1 && __FPU_USED == 1 && DISTORTOS_SIGNALS_ENABLE == 1 && \
DISTORTOS_MAIN_THREAD_SIGNAL_ACTIONS > 0 && DISTORTOS_MAIN_THREAD_QUEUED_SIGNALS > 0
#if ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
#include "ARMv7-M-checkFpuRegisters.hpp"
#include "ARMv7-M-setFpuRegisters.hpp"
#include "distortos/DynamicThread.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread.hpp"
#include "distortos/ThisThread-Signals.hpp"
#include "estd/ScopeGuard.hpp"
#include <cerrno>
#endif // ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
namespace distortos
{
namespace test
{
#if ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// values used in single test stage
struct Stage
{
/// value written to all FPU registers in main thread, don't use FPU in main thread if 0
uint32_t threadValue;
/// value written to "lower" FPU registers in "sender" before queuing of signal, skip this step if 0
uint32_t senderValueBefore;
/// value written to "lower" FPU registers in "sender" after queuing of signal, skip this step if 0
uint32_t senderValueAfter;
/// signal value, written to "lower" FPU registers in handler, don't use FPU in handler if 0
int signalValue;
};
/// description of single test phase
struct Phase
{
/// type of "sender" function
using Sender = int(Thread&, const Stage&);
/// reference to "sender" function
Sender& sender;
/// expected number of context switches for single stage executed in this phase
decltype(statistics::getContextSwitchCount()) contextSwitchCount;
};
/// context shared with interrupt
struct Context
{
/// shared return value
int sharedRet;
/// pointer to test stage
const Stage* stage;
/// pointer to thread to which the signal will be queued
Thread* thread;
};
/*---------------------------------------------------------------------------------------------------------------------+
| local objects
+---------------------------------------------------------------------------------------------------------------------*/
/// tested signal number
constexpr uint8_t testSignalNumber {16};
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {512};
/// pointer to context shared with interrupt
Context* volatile context;
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Disables FPU context for current thread by clearing FPCA bit in CONTROL register.
*/
void disableFpuContext()
{
const auto control = __get_CONTROL();
__set_CONTROL(control & ~CONTROL_FPCA_Msk);
}
/**
* \brief Signal handler
*
* Sets "lower" FPU registers (s0-s15 and fpscr) using the value queued with signal, unless this value is 0.
*
* \param [in] signalInformation is a reference to received SignalInformation object
*/
void handler(const SignalInformation& signalInformation)
{
const auto value = signalInformation.getValue().sival_int;
if (value == 0)
return;
setFpuRegisters(value, false);
}
/**
* \brief Tests whether FPU context is active for current thread.
*
* \return true if FPU context is active for current thread (FPCA bit in CONTROL register is set), false otherwise
*/
bool isFpuContextActive()
{
const auto control = __get_CONTROL();
return (control & CONTROL_FPCA_Msk) != 0;
}
/**
* \brief Test wrapper for Thread::queueSignal() that also modifies FPU registers.
*
* \param [in] thread is a reference to thread to which the signal will be queued
* \param [in] stage is a reference to test stage
* \param [in] full is the \a full argument passed to setFpuRegisters()
* \param [in] sharedRet is a reference to int variable which will be written with 0 on success, error code otherwise
*/
void queueSignalWrapper(Thread& thread, const Stage& stage, const bool full, int& sharedRet)
{
if (stage.senderValueBefore != 0) // should FPU be used at the beginning of "sender"?
setFpuRegisters(stage.senderValueBefore, full);
sharedRet = thread.queueSignal(testSignalNumber, sigval{stage.signalValue});
if (stage.senderValueAfter != 0) // should FPU be used at th"sender""sender"?
setFpuRegisters(stage.senderValueAfter, full);
}
/**
* \brief Queues signal from interrupt (via manually triggered UsageFault) to current thread.
*
* \param [in] thread is a reference to thread to which the signal will be queued
* \param [in] stage is a reference to test stage
*
* \return 0 on success, error code otherwise:
* - error codes returned by Thread::queueSignal();
*/
int queueSignalFromInterrupt(Thread& thread, const Stage& stage)
{
Context localContext {};
context = &localContext;
const auto contextScopeGuard = estd::makeScopeGuard(
[]()
{
context = {};
});
context->thread = &thread;
context->stage = &stage;
SCB->CCR |= SCB_CCR_DIV_0_TRP_Msk; // enable trapping of "divide by 0" by UsageFault
SCB->SHCSR |= SCB_SHCSR_USGFAULTENA_Msk; // enable UsageFault
volatile int a {};
volatile int b {};
a /= b; // trigger UsageFault via "divide by 0"
return context->sharedRet;
}
/**
* \brief Queues signal from thread to non-current thread.
*
* \param [in] thread is a reference to thread to which the signal will be queued
* \param [in] stage is a reference to test stage
*
* \return 0 on success, error code otherwise:
* - error codes returned by Thread::queueSignal();
*/
int queueSignalFromThread(Thread& thread, const Stage& stage)
{
constexpr decltype(FpuSignalTestCase::getTestCasePriority()) highPriority
{
FpuSignalTestCase::getTestCasePriority() + 1
};
int sharedRet {EINVAL};
auto testThread = makeAndStartDynamicThread({testThreadStackSize, highPriority}, queueSignalWrapper,
std::ref(thread), std::ref(stage), true, std::ref(sharedRet));
testThread.join();
return sharedRet;
}
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// test phases
const Phase phases[]
{
{queueSignalFromInterrupt, 0},
{queueSignalFromThread, 2},
};
/// test stages
const Stage stages[]
{
{0, 0, 0, 0}, // don't use FPU in all contexts
{0, 0, 0, 0x0b39fa96}, // in handler
{0, 0, 0x8606151d, 0}, // in "sender" (at the end)
{0, 0, 0x8bdd3b5e, 0x7d21d1c6}, // in "sender" (at the end) and in handler
{0, 0x2f884196, 0, 0}, // in "sender" (at the beginning)
{0, 0x0b0bbc86, 0, 0x0e43811b}, // in "sender" (at the beginning) and in handler
{0, 0xb72b2917, 0x8c27baa7, 0}, // in "sender"
{0, 0xa83b80c2, 0xd2b7dd4d, 0x626ca399}, // in "sender" and in handler
{0xb4e40525, 0, 0, 0}, // in main thread
{0x772bdf91, 0, 0, 0x0bb325b7}, // in main thread and in handler
{0x8a19625e, 0, 0x32378f7b, 0}, // in main thread and in "sender" (at the end)
{0xd17a21db, 0, 0xaa807a91, 0x03caf264}, // in main thread, in "sender" (at the end) and in handler
{0xe4b44073, 0xa88c0cf5, 0, 0}, // in main thread and in "sender" (at the beginning)
{0xb94c722b, 0x5f8ca773, 0, 0x288301cf}, // in main thread, in "sender" (at the beginning) and in handler
{0x347ecfc5, 0xcb4a3584, 0x5a8bf219, 0}, // in main thread and in "sender"
{0x788ed92e, 0x4b0ddff9, 0x73776a21, 0x48fb1969}, // in all contexts
};
} // namespace
#endif // ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
/*---------------------------------------------------------------------------------------------------------------------+
| protected functions
+---------------------------------------------------------------------------------------------------------------------*/
bool FpuSignalTestCase::finalize() const
{
#if ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
disableFpuContext();
#endif // ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
return SignalsTestCaseCommon::finalize();
}
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool FpuSignalTestCase::run_() const
{
#if ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
const auto contextSwitchCount = statistics::getContextSwitchCount();
auto expectedContextSwitchCount = decltype(contextSwitchCount){};
{
int ret;
std::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber,
SignalAction{handler, SignalSet{SignalSet::empty}});
if (ret != 0)
return false;
}
auto& currentThread = ThisThread::get();
for (auto& phase : phases)
for (auto& stage : stages)
{
disableFpuContext();
decltype(setFpuRegisters({}, {})) fpscr {};
if (stage.threadValue != 0) // should FPU be used in main thread?
fpscr = setFpuRegisters(stage.threadValue, true);
if (phase.sender(currentThread, stage) != 0)
return false;
// FPU context may be active only if FPU was used in main thread
if (isFpuContextActive() != (stage.threadValue != 0))
return false;
if (stage.threadValue != 0) // was FPU used in main thread?
if (checkFpuRegisters(stage.threadValue, fpscr) == false)
return false;
expectedContextSwitchCount += phase.contextSwitchCount;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
return false;
}
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
return false;
#endif // ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
return true;
}
} // namespace test
} // namespace distortos
#if ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief UsageFault_Handler() for ARMv7-M
*/
extern "C" void UsageFault_Handler()
{
SCB->CFSR = SCB_CFSR_DIVBYZERO_Msk; // clear "divide by 0" flag
SCB->CCR &= ~SCB_CCR_DIV_0_TRP_Msk; // disable trapping of "divide by 0" by UsageFault
SCB->SHCSR &= ~SCB_SHCSR_USGFAULTENA_Msk; // disable UsageFault
using namespace distortos::test;
queueSignalWrapper(*context->thread, *context->stage, false, context->sharedRet);
}
#endif // ARMV7_M_FPU_SIGNAL_TEST_CASE_ENABLED == 1
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
#ifndef _Stroika_Foundation_Configuration_Version_inl_
#define _Stroika_Foundation_Configuration_Version_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#if defined(__cplusplus)
namespace Stroika::Foundation::Configuration {
#endif
/*
********************************************************************************
*********************************** Version ************************************
********************************************************************************
*/
constexpr Version::Version ()
: fMajorVer{0}
, fMinorVer{0}
, fVerStage{VersionStage::eSTART}
, fVerSubStage{0}
, fFinalBuild{0}
{
}
constexpr Version::Version (Binary32BitFullVersionType fullVersionNumber)
: fMajorVer{static_cast<uint8_t> ((fullVersionNumber >> 24) & 0x8f)}
, fMinorVer{static_cast<uint8_t> ((fullVersionNumber >> 16) & 0xff)}
, fVerStage{static_cast<VersionStage> ((fullVersionNumber >> 13) & 0x07)}
, fVerSubStage{static_cast<uint16_t> ((fullVersionNumber >> 1) & 0xfff)}
, fFinalBuild{static_cast<bool> (fullVersionNumber & 1)}
{
Assert (fVerSubStage < kMaxVersionSubStage); // we got shift/mask right above
}
constexpr Version::Version (uint8_t majorVer, uint8_t minorVer, VersionStage verStage, uint16_t verSubStage, bool finalBuild)
: fMajorVer{majorVer}
, fMinorVer{minorVer}
, fVerStage{verStage}
, fVerSubStage{verSubStage}
, fFinalBuild{finalBuild}
{
// @todo validate arg verSubStage < kMaxVersionSubStage
}
constexpr Binary32BitFullVersionType Version::AsFullVersionNum () const
{
// @todo validate arg verSubStage < kMaxVersionSubStage
return Stroika_Make_FULL_VERSION (fMajorVer, fMinorVer, ((uint8_t)fVerStage), fVerSubStage, static_cast<int> (fFinalBuild));
}
inline Characters::String Version::ToString () const
{
return AsPrettyVersionString ();
}
#if __cpp_impl_three_way_comparison >= 201907
constexpr strong_ordering Version::operator<=> (const Version& rhs) const
{
return make_signed_t<Binary32BitFullVersionType> (AsFullVersionNum ()) <=> make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
}
constexpr bool Version::operator== (const Version& rhs) const
{
return make_signed_t<Binary32BitFullVersionType> (AsFullVersionNum ()) == make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
}
#endif
/*
********************************************************************************
***************************** Version operators ********************************
********************************************************************************
*/
#if __cpp_impl_three_way_comparison < 201907
constexpr bool operator< (const Version& lhs, const Version& rhs)
{
return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) < make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ()));
}
constexpr bool operator<= (const Version& lhs, const Version& rhs)
{
return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) <= make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ()));
}
constexpr bool operator== (const Version& lhs, const Version& rhs)
{
return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) == make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ()));
}
constexpr bool operator!= (const Version& lhs, const Version& rhs)
{
return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) != make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ()));
}
constexpr bool operator>= (const Version& lhs, const Version& rhs)
{
return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) >= make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ()));
}
constexpr bool operator> (const Version& lhs, const Version& rhs)
{
return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) > make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ()));
}
#endif
#if defined(__cplusplus)
}
#endif
#endif /*_Stroika_Foundation_Configuration_Version_inl_*/
<commit_msg>fixed typo<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
#ifndef _Stroika_Foundation_Configuration_Version_inl_
#define _Stroika_Foundation_Configuration_Version_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#if defined(__cplusplus)
namespace Stroika::Foundation::Configuration {
#endif
/*
********************************************************************************
*********************************** Version ************************************
********************************************************************************
*/
constexpr Version::Version ()
: fMajorVer{0}
, fMinorVer{0}
, fVerStage{VersionStage::eSTART}
, fVerSubStage{0}
, fFinalBuild{0}
{
}
constexpr Version::Version (Binary32BitFullVersionType fullVersionNumber)
: fMajorVer{static_cast<uint8_t> ((fullVersionNumber >> 24) & 0x8f)}
, fMinorVer{static_cast<uint8_t> ((fullVersionNumber >> 16) & 0xff)}
, fVerStage{static_cast<VersionStage> ((fullVersionNumber >> 13) & 0x07)}
, fVerSubStage{static_cast<uint16_t> ((fullVersionNumber >> 1) & 0xfff)}
, fFinalBuild{static_cast<bool> (fullVersionNumber & 1)}
{
Assert (fVerSubStage < kMaxVersionSubStage); // we got shift/mask right above
}
constexpr Version::Version (uint8_t majorVer, uint8_t minorVer, VersionStage verStage, uint16_t verSubStage, bool finalBuild)
: fMajorVer{majorVer}
, fMinorVer{minorVer}
, fVerStage{verStage}
, fVerSubStage{verSubStage}
, fFinalBuild{finalBuild}
{
// @todo validate arg verSubStage < kMaxVersionSubStage
}
constexpr Binary32BitFullVersionType Version::AsFullVersionNum () const
{
// @todo validate arg verSubStage < kMaxVersionSubStage
return Stroika_Make_FULL_VERSION (fMajorVer, fMinorVer, ((uint8_t)fVerStage), fVerSubStage, static_cast<int> (fFinalBuild));
}
inline Characters::String Version::ToString () const
{
return AsPrettyVersionString ();
}
#if __cpp_impl_three_way_comparison >= 201907
constexpr strong_ordering Version::operator<=> (const Version& rhs) const
{
return make_signed_t<Binary32BitFullVersionType> (AsFullVersionNum ()) <=> make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
}
constexpr bool Version::operator== (const Version& rhs) const
{
return make_signed_t<Binary32BitFullVersionType> (AsFullVersionNum ()) == make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
}
#endif
/*
********************************************************************************
***************************** Version operators ********************************
********************************************************************************
*/
#if __cpp_impl_three_way_comparison < 201907
constexpr bool operator< (const Version& lhs, const Version& rhs)
{
return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) < make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
}
constexpr bool operator<= (const Version& lhs, const Version& rhs)
{
return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) <= make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
}
constexpr bool operator== (const Version& lhs, const Version& rhs)
{
return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) == make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
}
constexpr bool operator!= (const Version& lhs, const Version& rhs)
{
return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) != make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
}
constexpr bool operator>= (const Version& lhs, const Version& rhs)
{
return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) >= make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
}
constexpr bool operator> (const Version& lhs, const Version& rhs)
{
return make_signed_t<Binary32BitFullVersionType> (lhs.AsFullVersionNum ()) > make_signed_t<Binary32BitFullVersionType> (rhs.AsFullVersionNum ());
}
#endif
#if defined(__cplusplus)
}
#endif
#endif /*_Stroika_Foundation_Configuration_Version_inl_*/
<|endoftext|>
|
<commit_before>// $Id$
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2010 Hieu Hoang
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include "ChartTrellisNode.h"
#include "ChartHypothesis.h"
#include "ScoreComponentCollection.h"
using namespace std;
namespace Moses
{
ChartTrellisNode::ChartTrellisNode(const ChartHypothesis *hypo)
:m_hypo(hypo)
{
const std::vector<const ChartHypothesis*> &prevHypos = hypo->GetPrevHypos();
m_edge.reserve(prevHypos.size());
for (size_t ind = 0; ind < prevHypos.size(); ++ind) {
const ChartHypothesis *prevHypo = prevHypos[ind];
ChartTrellisNode *child = new ChartTrellisNode(prevHypo);
m_edge.push_back(child);
}
assert(m_hypo);
}
ChartTrellisNode::ChartTrellisNode(const ChartTrellisNode &origNode
, const ChartTrellisNode &soughtNode
, const ChartHypothesis &replacementHypo
, ScoreComponentCollection &scoreChange
, const ChartTrellisNode *&nodeChanged)
{
if (&origNode.GetHypothesis() == &soughtNode.GetHypothesis()) {
// this node should be replaced
m_hypo = &replacementHypo;
nodeChanged = this;
// scores
assert(scoreChange.GetWeightedScore() == 0); // should only be changing 1 node
scoreChange = replacementHypo.GetScoreBreakdown();
scoreChange.MinusEquals(origNode.GetHypothesis().GetScoreBreakdown());
float deltaScore = scoreChange.GetWeightedScore();
assert(deltaScore <= 0.0005);
// follow prev hypos back to beginning
const std::vector<const ChartHypothesis*> &prevHypos = replacementHypo.GetPrevHypos();
vector<const ChartHypothesis*>::const_iterator iter;
assert(m_edge.empty());
m_edge.reserve(prevHypos.size());
for (iter = prevHypos.begin(); iter != prevHypos.end(); ++iter) {
const ChartHypothesis *prevHypo = *iter;
ChartTrellisNode *prevNode = new ChartTrellisNode(prevHypo);
m_edge.push_back(prevNode);
}
} else {
// not the node we're looking for. Copy as-is and continue finding node
m_hypo = &origNode.GetHypothesis();
NodeChildren::const_iterator iter;
assert(m_edge.empty());
m_edge.reserve(origNode.m_edge.size());
for (iter = origNode.m_edge.begin(); iter != origNode.m_edge.end(); ++iter) {
const ChartTrellisNode &prevNode = **iter;
ChartTrellisNode *newPrevNode = new ChartTrellisNode(prevNode, soughtNode, replacementHypo, scoreChange, nodeChanged);
m_edge.push_back(newPrevNode);
}
}
assert(m_hypo);
}
ChartTrellisNode::~ChartTrellisNode()
{
RemoveAllInColl(m_edge);
}
Phrase ChartTrellisNode::GetOutputPhrase() const
{
// exactly like same fn in hypothesis, but use trellis nodes instead of prevHypos pointer
Phrase ret(Output, ARRAY_SIZE_INCR);
const Phrase &currTargetPhrase = m_hypo->GetCurrTargetPhrase();
for (size_t pos = 0; pos < currTargetPhrase.GetSize(); ++pos) {
const Word &word = currTargetPhrase.GetWord(pos);
if (word.IsNonTerminal()) {
// non-term. fill out with prev hypo
size_t nonTermInd = m_hypo->GetCoveredChartSpanTargetOrder(pos);
const ChartTrellisNode &childNode = GetChild(nonTermInd);
Phrase childPhrase = childNode.GetOutputPhrase();
ret.Append(childPhrase);
} else {
ret.AddWord(word);
}
}
return ret;
}
std::ostream& operator<<(std::ostream &out, const ChartTrellisNode &node)
{
out << "* " << node.GetHypothesis() << endl;
ChartTrellisNode::NodeChildren::const_iterator iter;
for (iter = node.GetChildren().begin(); iter != node.GetChildren().end(); ++iter) {
out << **iter;
}
return out;
}
}
<commit_msg>derivation of n-best list output<commit_after>// $Id$
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2010 Hieu Hoang
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include "ChartTrellisNode.h"
#include "ChartHypothesis.h"
#include "ScoreComponentCollection.h"
#include "StaticData.h"
using namespace std;
namespace Moses
{
ChartTrellisNode::ChartTrellisNode(const ChartHypothesis *hypo)
:m_hypo(hypo)
{
const std::vector<const ChartHypothesis*> &prevHypos = hypo->GetPrevHypos();
m_edge.reserve(prevHypos.size());
for (size_t ind = 0; ind < prevHypos.size(); ++ind) {
const ChartHypothesis *prevHypo = prevHypos[ind];
ChartTrellisNode *child = new ChartTrellisNode(prevHypo);
m_edge.push_back(child);
}
assert(m_hypo);
}
ChartTrellisNode::ChartTrellisNode(const ChartTrellisNode &origNode
, const ChartTrellisNode &soughtNode
, const ChartHypothesis &replacementHypo
, ScoreComponentCollection &scoreChange
, const ChartTrellisNode *&nodeChanged)
{
if (&origNode.GetHypothesis() == &soughtNode.GetHypothesis()) {
// this node should be replaced
m_hypo = &replacementHypo;
nodeChanged = this;
// scores
assert(scoreChange.GetWeightedScore() == 0); // should only be changing 1 node
scoreChange = replacementHypo.GetScoreBreakdown();
scoreChange.MinusEquals(origNode.GetHypothesis().GetScoreBreakdown());
float deltaScore = scoreChange.GetWeightedScore();
assert(deltaScore <= 0.0005);
// follow prev hypos back to beginning
const std::vector<const ChartHypothesis*> &prevHypos = replacementHypo.GetPrevHypos();
vector<const ChartHypothesis*>::const_iterator iter;
assert(m_edge.empty());
m_edge.reserve(prevHypos.size());
for (iter = prevHypos.begin(); iter != prevHypos.end(); ++iter) {
const ChartHypothesis *prevHypo = *iter;
ChartTrellisNode *prevNode = new ChartTrellisNode(prevHypo);
m_edge.push_back(prevNode);
}
} else {
// not the node we're looking for. Copy as-is and continue finding node
m_hypo = &origNode.GetHypothesis();
NodeChildren::const_iterator iter;
assert(m_edge.empty());
m_edge.reserve(origNode.m_edge.size());
for (iter = origNode.m_edge.begin(); iter != origNode.m_edge.end(); ++iter) {
const ChartTrellisNode &prevNode = **iter;
ChartTrellisNode *newPrevNode = new ChartTrellisNode(prevNode, soughtNode, replacementHypo, scoreChange, nodeChanged);
m_edge.push_back(newPrevNode);
}
}
assert(m_hypo);
}
ChartTrellisNode::~ChartTrellisNode()
{
RemoveAllInColl(m_edge);
}
Phrase ChartTrellisNode::GetOutputPhrase() const
{
// exactly like same fn in hypothesis, but use trellis nodes instead of prevHypos pointer
Phrase ret(Output, ARRAY_SIZE_INCR);
const ChartTranslationOption &transOpt = m_hypo->GetTranslationOption();
VERBOSE(3, "Trans Opt:" << transOpt << std::endl);
const Phrase &currTargetPhrase = m_hypo->GetCurrTargetPhrase();
for (size_t pos = 0; pos < currTargetPhrase.GetSize(); ++pos) {
const Word &word = currTargetPhrase.GetWord(pos);
if (word.IsNonTerminal()) {
// non-term. fill out with prev hypo
size_t nonTermInd = m_hypo->GetCoveredChartSpanTargetOrder(pos);
const ChartTrellisNode &childNode = GetChild(nonTermInd);
Phrase childPhrase = childNode.GetOutputPhrase();
ret.Append(childPhrase);
} else {
ret.AddWord(word);
}
}
return ret;
}
std::ostream& operator<<(std::ostream &out, const ChartTrellisNode &node)
{
out << "* " << node.GetHypothesis() << endl;
ChartTrellisNode::NodeChildren::const_iterator iter;
for (iter = node.GetChildren().begin(); iter != node.GetChildren().end(); ++iter) {
out << **iter;
}
return out;
}
}
<|endoftext|>
|
<commit_before>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <cassert>
#include <cstring>
#include <iostream>
#include <stdlib.h>
#include "lm/binary_format.hh"
#include "lm/enumerate_vocab.hh"
#include "lm/model.hh"
#include "LanguageModelKen.h"
#include "FFState.h"
#include "TypeDef.h"
#include "Util.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "InputFileStream.h"
#include "StaticData.h"
#include "ChartHypothesis.h"
using namespace std;
namespace Moses
{
LanguageModelKenBase::~LanguageModelKenBase() {}
namespace
{
class LanguageModelChartStateKenLM : public FFState
{
private:
lm::ngram::ChartState m_state;
const ChartHypothesis *m_hypo;
public:
explicit LanguageModelChartStateKenLM(const ChartHypothesis &hypo)
:m_hypo(&hypo)
{}
const ChartHypothesis* GetHypothesis() const { return m_hypo; }
const lm::ngram::ChartState &GetChartState() const { return m_state; }
lm::ngram::ChartState &GetChartState() { return m_state; }
int Compare(const FFState& o) const
{
const LanguageModelChartStateKenLM &other = static_cast<const LanguageModelChartStateKenLM&>(o);
int ret = m_state.Compare(other.m_state);
return ret;
}
};
class MappingBuilder : public lm::ngram::EnumerateVocab
{
public:
MappingBuilder(FactorCollection &factorCollection, std::vector<lm::WordIndex> &mapping)
: m_factorCollection(factorCollection), m_mapping(mapping) {}
void Add(lm::WordIndex index, const StringPiece &str) {
std::size_t factorId = m_factorCollection.AddFactor(str)->GetId();
if (m_mapping.size() <= factorId) {
// 0 is <unk> :-)
m_mapping.resize(factorId + 1);
}
m_mapping[factorId] = index;
}
private:
FactorCollection &m_factorCollection;
std::vector<lm::WordIndex> &m_mapping;
};
struct KenLMState : public FFState {
lm::ngram::State state;
int Compare(const FFState &o) const {
const KenLMState &other = static_cast<const KenLMState &>(o);
if (state.length < other.state.length) return -1;
if (state.length > other.state.length) return 1;
return std::memcmp(state.words, other.state.words, sizeof(lm::WordIndex) * state.length);
}
};
/*
* An implementation of single factor LM using Ken's code.
*/
template <class Model> class LanguageModelKen : public LanguageModelKenBase
{
private:
Model *m_ngram;
std::vector<lm::WordIndex> m_lmIdLookup;
bool m_lazy;
KenLMState m_nullContextState;
KenLMState m_beginSentenceState;
void TranslateIDs(const std::vector<const Word*> &contextFactor, lm::WordIndex *indices) const;
public:
LanguageModelKen(bool lazy);
~LanguageModelKen();
bool Load(const std::string &filePath
, FactorType factorType
, size_t nGramOrder);
LMResult GetValueGivenState(const std::vector<const Word*> &contextFactor, FFState &state) const {
return GetKenFullScoreGivenState(contextFactor, state);
}
LMKenResult GetKenFullScoreGivenState(const std::vector<const Word*> &contextFactor, FFState &state) const;
LMResult GetValueForgotState(const std::vector<const Word*> &contextFactor, FFState &outState) const {
return GetKenFullScoreForgotState(contextFactor, outState);
}
LMKenResult GetKenFullScoreForgotState(const std::vector<const Word*> &contextFactor, FFState &outState) const;
void GetState(const std::vector<const Word*> &contextFactor, FFState &outState) const;
const FFState *GetNullContextState() const;
const FFState *GetBeginSentenceState() const;
FFState *NewState(const FFState *from = NULL) const;
lm::WordIndex GetLmID(const std::string &str) const;
void CleanUpAfterSentenceProcessing() {}
void InitializeBeforeSentenceProcessing() {}
FFState *EvaluateChart(const ChartHypothesis& cur_hypo,
int featureID,
ScoreComponentCollection *accumulator,
const LanguageModel *feature) const;
};
template <class Model>
FFState *LanguageModelKen<Model>::EvaluateChart(
const ChartHypothesis& hypo,
int featureID,
ScoreComponentCollection *accumulator,
const LanguageModel *feature) const
{
LanguageModelChartStateKenLM *newState = new LanguageModelChartStateKenLM(hypo);
lm::ngram::RuleScore<Model> ruleScore(*m_ngram, newState->GetChartState());
const AlignmentInfo::NonTermIndexMap &nonTermIndexMap = hypo.GetCurrTargetPhrase().GetAlignmentInfo().GetNonTermIndexMap();
const size_t size = hypo.GetCurrTargetPhrase().GetSize();
size_t phrasePos = 0;
// Special cases for first word.
if (size) {
const Word &word = hypo.GetCurrTargetPhrase().GetWord(0);
if (word == GetSentenceStartArray()) {
// Begin of sentence
ruleScore.BeginSentence();
phrasePos++;
} else if (word.IsNonTerminal()) {
// Non-terminal is first so we can copy instead of rescoring.
const ChartHypothesis *prevHypo = hypo.GetPrevHypo(nonTermIndexMap[phrasePos]);
const lm::ngram::ChartState &prevState = static_cast<const LanguageModelChartStateKenLM*>(prevHypo->GetFFState(featureID))->GetChartState();
ruleScore.BeginNonTerminal(prevState, prevHypo->GetScoreBreakdown().GetScoresForProducer(feature)[0]);
phrasePos++;
}
}
for (; phrasePos < size; phrasePos++) {
const Word &word = hypo.GetCurrTargetPhrase().GetWord(phrasePos);
if (word.IsNonTerminal()) {
const ChartHypothesis *prevHypo = hypo.GetPrevHypo(nonTermIndexMap[phrasePos]);
const lm::ngram::ChartState &prevState = static_cast<const LanguageModelChartStateKenLM*>(prevHypo->GetFFState(featureID))->GetChartState();
ruleScore.NonTerminal(prevState, prevHypo->GetScoreBreakdown().GetScoresForProducer(feature)[0]);
} else {
std::size_t factor = word.GetFactor(GetFactorType())->GetId();
lm::WordIndex new_word = (factor >= m_lmIdLookup.size() ? 0 : m_lmIdLookup[factor]);
ruleScore.Terminal(new_word);
}
}
accumulator->Assign(feature, ruleScore.Finish());
return newState;
}
template <class Model> void LanguageModelKen<Model>::TranslateIDs(const std::vector<const Word*> &contextFactor, lm::WordIndex *indices) const
{
FactorType factorType = GetFactorType();
// set up context
for (size_t i = 0 ; i < contextFactor.size(); i++) {
std::size_t factor = contextFactor[i]->GetFactor(factorType)->GetId();
lm::WordIndex new_word = (factor >= m_lmIdLookup.size() ? 0 : m_lmIdLookup[factor]);
indices[contextFactor.size() - 1 - i] = new_word;
}
}
template <class Model> LanguageModelKen<Model>::LanguageModelKen(bool lazy)
:m_ngram(NULL), m_lazy(lazy)
{
}
template <class Model> LanguageModelKen<Model>::~LanguageModelKen()
{
delete m_ngram;
}
template <class Model> bool LanguageModelKen<Model>::Load(const std::string &filePath,
FactorType factorType,
size_t /*nGramOrder*/)
{
m_factorType = factorType;
m_filePath = filePath;
FactorCollection &factorCollection = FactorCollection::Instance();
m_sentenceStart = factorCollection.AddFactor(BOS_);
m_sentenceStartArray[m_factorType] = m_sentenceStart;
m_sentenceEnd = factorCollection.AddFactor(EOS_);
m_sentenceEndArray[m_factorType] = m_sentenceEnd;
MappingBuilder builder(factorCollection, m_lmIdLookup);
lm::ngram::Config config;
IFVERBOSE(1) {
config.messages = &std::cerr;
}
else {
config.messages = NULL;
}
config.enumerate_vocab = &builder;
config.load_method = m_lazy ? util::LAZY : util::POPULATE_OR_READ;
try {
m_ngram = new Model(filePath.c_str(), config);
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
abort();
}
m_nGramOrder = m_ngram->Order();
m_nullContextState.state = m_ngram->NullContextState();
m_beginSentenceState.state = m_ngram->BeginSentenceState();
return true;
}
template <class Model> LMKenResult LanguageModelKen<Model>::GetKenFullScoreGivenState(const std::vector<const Word*> &contextFactor, FFState &state) const
{
LMKenResult result;
if (contextFactor.empty()) {
result.score = 0.0;
result.unknown = false;
result.ngram_length = 0;
return result;
}
lm::ngram::State &realState = static_cast<KenLMState&>(state).state;
std::size_t factor = contextFactor.back()->GetFactor(GetFactorType())->GetId();
lm::WordIndex new_word = (factor >= m_lmIdLookup.size() ? 0 : m_lmIdLookup[factor]);
lm::ngram::State copied(realState);
lm::FullScoreReturn ret(m_ngram->FullScore(copied, new_word, realState));
result.score = TransformLMScore(ret.prob);
result.unknown = (new_word == 0);
result.ngram_length = ret.ngram_length;
return result;
}
template <class Model> LMKenResult LanguageModelKen<Model>::GetKenFullScoreForgotState(const vector<const Word*> &contextFactor, FFState &outState) const
{
LMKenResult result;
if (contextFactor.empty()) {
static_cast<KenLMState&>(outState).state = m_ngram->NullContextState();
result.score = 0.0;
result.unknown = false;
result.ngram_length = 0;
return result;
}
lm::WordIndex indices[contextFactor.size()];
TranslateIDs(contextFactor, indices);
lm::FullScoreReturn ret(m_ngram->FullScoreForgotState(indices + 1, indices + contextFactor.size(), indices[0], static_cast<KenLMState&>(outState).state));
result.score = TransformLMScore(ret.prob);
result.unknown = (indices[0] == 0);
result.ngram_length = ret.ngram_length;
return result;
}
template <class Model> void LanguageModelKen<Model>::GetState(const std::vector<const Word*> &contextFactor, FFState &outState) const
{
if (contextFactor.empty()) {
static_cast<KenLMState&>(outState).state = m_ngram->NullContextState();
return;
}
lm::WordIndex indices[contextFactor.size()];
TranslateIDs(contextFactor, indices);
m_ngram->GetState(indices, indices + contextFactor.size(), static_cast<KenLMState&>(outState).state);
}
template <class Model> const FFState *LanguageModelKen<Model>::GetNullContextState() const
{
return &m_nullContextState;
}
template <class Model> const FFState *LanguageModelKen<Model>::GetBeginSentenceState() const
{
return &m_beginSentenceState;
}
template <class Model> FFState *LanguageModelKen<Model>::NewState(const FFState *from) const
{
KenLMState *ret = new KenLMState;
if (from) {
ret->state = static_cast<const KenLMState&>(*from).state;
}
return ret;
}
template <class Model> lm::WordIndex LanguageModelKen<Model>::GetLmID(const std::string &str) const
{
return m_ngram->GetVocabulary().Index(str);
}
} // namespace
LanguageModelSingleFactor *ConstructKenLM(const std::string &file, bool lazy)
{
lm::ngram::ModelType model_type;
if (lm::ngram::RecognizeBinary(file.c_str(), model_type)) {
switch(model_type) {
case lm::ngram::HASH_PROBING:
return new LanguageModelKen<lm::ngram::ProbingModel>(lazy);
case lm::ngram::TRIE_SORTED:
return new LanguageModelKen<lm::ngram::TrieModel>(lazy);
case lm::ngram::QUANT_TRIE_SORTED:
return new LanguageModelKen<lm::ngram::QuantTrieModel>(lazy);
case lm::ngram::ARRAY_TRIE_SORTED:
return new LanguageModelKen<lm::ngram::ArrayTrieModel>(lazy);
case lm::ngram::QUANT_ARRAY_TRIE_SORTED:
return new LanguageModelKen<lm::ngram::QuantArrayTrieModel>(lazy);
default:
std::cerr << "Unrecognized kenlm model type " << model_type << std::endl;
abort();
}
} else {
return new LanguageModelKen<lm::ngram::ProbingModel>(lazy);
}
}
}
<commit_msg>compile error due to last commit<commit_after>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <cassert>
#include <cstring>
#include <iostream>
#include <stdlib.h>
#include "lm/binary_format.hh"
#include "lm/enumerate_vocab.hh"
#include "lm/model.hh"
#include "LanguageModelKen.h"
#include "FFState.h"
#include "TypeDef.h"
#include "Util.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "InputFileStream.h"
#include "StaticData.h"
#include "ChartHypothesis.h"
using namespace std;
namespace Moses
{
LanguageModelKenBase::~LanguageModelKenBase() {}
namespace
{
class LanguageModelChartStateKenLM : public FFState
{
private:
lm::ngram::ChartState m_state;
const ChartHypothesis *m_hypo;
public:
explicit LanguageModelChartStateKenLM(const ChartHypothesis &hypo)
:m_hypo(&hypo)
{}
const ChartHypothesis* GetHypothesis() const { return m_hypo; }
const lm::ngram::ChartState &GetChartState() const { return m_state; }
lm::ngram::ChartState &GetChartState() { return m_state; }
int Compare(const FFState& o) const
{
const LanguageModelChartStateKenLM &other = static_cast<const LanguageModelChartStateKenLM&>(o);
int ret = m_state.Compare(other.m_state);
return ret;
}
};
class MappingBuilder : public lm::ngram::EnumerateVocab
{
public:
MappingBuilder(FactorCollection &factorCollection, std::vector<lm::WordIndex> &mapping)
: m_factorCollection(factorCollection), m_mapping(mapping) {}
void Add(lm::WordIndex index, const StringPiece &str) {
std::size_t factorId = m_factorCollection.AddFactor(str.data())->GetId();
if (m_mapping.size() <= factorId) {
// 0 is <unk> :-)
m_mapping.resize(factorId + 1);
}
m_mapping[factorId] = index;
}
private:
FactorCollection &m_factorCollection;
std::vector<lm::WordIndex> &m_mapping;
};
struct KenLMState : public FFState {
lm::ngram::State state;
int Compare(const FFState &o) const {
const KenLMState &other = static_cast<const KenLMState &>(o);
if (state.length < other.state.length) return -1;
if (state.length > other.state.length) return 1;
return std::memcmp(state.words, other.state.words, sizeof(lm::WordIndex) * state.length);
}
};
/*
* An implementation of single factor LM using Ken's code.
*/
template <class Model> class LanguageModelKen : public LanguageModelKenBase
{
private:
Model *m_ngram;
std::vector<lm::WordIndex> m_lmIdLookup;
bool m_lazy;
KenLMState m_nullContextState;
KenLMState m_beginSentenceState;
void TranslateIDs(const std::vector<const Word*> &contextFactor, lm::WordIndex *indices) const;
public:
LanguageModelKen(bool lazy);
~LanguageModelKen();
bool Load(const std::string &filePath
, FactorType factorType
, size_t nGramOrder);
LMResult GetValueGivenState(const std::vector<const Word*> &contextFactor, FFState &state) const {
return GetKenFullScoreGivenState(contextFactor, state);
}
LMKenResult GetKenFullScoreGivenState(const std::vector<const Word*> &contextFactor, FFState &state) const;
LMResult GetValueForgotState(const std::vector<const Word*> &contextFactor, FFState &outState) const {
return GetKenFullScoreForgotState(contextFactor, outState);
}
LMKenResult GetKenFullScoreForgotState(const std::vector<const Word*> &contextFactor, FFState &outState) const;
void GetState(const std::vector<const Word*> &contextFactor, FFState &outState) const;
const FFState *GetNullContextState() const;
const FFState *GetBeginSentenceState() const;
FFState *NewState(const FFState *from = NULL) const;
lm::WordIndex GetLmID(const std::string &str) const;
void CleanUpAfterSentenceProcessing() {}
void InitializeBeforeSentenceProcessing() {}
FFState *EvaluateChart(const ChartHypothesis& cur_hypo,
int featureID,
ScoreComponentCollection *accumulator,
const LanguageModel *feature) const;
};
template <class Model>
FFState *LanguageModelKen<Model>::EvaluateChart(
const ChartHypothesis& hypo,
int featureID,
ScoreComponentCollection *accumulator,
const LanguageModel *feature) const
{
LanguageModelChartStateKenLM *newState = new LanguageModelChartStateKenLM(hypo);
lm::ngram::RuleScore<Model> ruleScore(*m_ngram, newState->GetChartState());
const AlignmentInfo::NonTermIndexMap &nonTermIndexMap = hypo.GetCurrTargetPhrase().GetAlignmentInfo().GetNonTermIndexMap();
const size_t size = hypo.GetCurrTargetPhrase().GetSize();
size_t phrasePos = 0;
// Special cases for first word.
if (size) {
const Word &word = hypo.GetCurrTargetPhrase().GetWord(0);
if (word == GetSentenceStartArray()) {
// Begin of sentence
ruleScore.BeginSentence();
phrasePos++;
} else if (word.IsNonTerminal()) {
// Non-terminal is first so we can copy instead of rescoring.
const ChartHypothesis *prevHypo = hypo.GetPrevHypo(nonTermIndexMap[phrasePos]);
const lm::ngram::ChartState &prevState = static_cast<const LanguageModelChartStateKenLM*>(prevHypo->GetFFState(featureID))->GetChartState();
ruleScore.BeginNonTerminal(prevState, prevHypo->GetScoreBreakdown().GetScoresForProducer(feature)[0]);
phrasePos++;
}
}
for (; phrasePos < size; phrasePos++) {
const Word &word = hypo.GetCurrTargetPhrase().GetWord(phrasePos);
if (word.IsNonTerminal()) {
const ChartHypothesis *prevHypo = hypo.GetPrevHypo(nonTermIndexMap[phrasePos]);
const lm::ngram::ChartState &prevState = static_cast<const LanguageModelChartStateKenLM*>(prevHypo->GetFFState(featureID))->GetChartState();
ruleScore.NonTerminal(prevState, prevHypo->GetScoreBreakdown().GetScoresForProducer(feature)[0]);
} else {
std::size_t factor = word.GetFactor(GetFactorType())->GetId();
lm::WordIndex new_word = (factor >= m_lmIdLookup.size() ? 0 : m_lmIdLookup[factor]);
ruleScore.Terminal(new_word);
}
}
accumulator->Assign(feature, ruleScore.Finish());
return newState;
}
template <class Model> void LanguageModelKen<Model>::TranslateIDs(const std::vector<const Word*> &contextFactor, lm::WordIndex *indices) const
{
FactorType factorType = GetFactorType();
// set up context
for (size_t i = 0 ; i < contextFactor.size(); i++) {
std::size_t factor = contextFactor[i]->GetFactor(factorType)->GetId();
lm::WordIndex new_word = (factor >= m_lmIdLookup.size() ? 0 : m_lmIdLookup[factor]);
indices[contextFactor.size() - 1 - i] = new_word;
}
}
template <class Model> LanguageModelKen<Model>::LanguageModelKen(bool lazy)
:m_ngram(NULL), m_lazy(lazy)
{
}
template <class Model> LanguageModelKen<Model>::~LanguageModelKen()
{
delete m_ngram;
}
template <class Model> bool LanguageModelKen<Model>::Load(const std::string &filePath,
FactorType factorType,
size_t /*nGramOrder*/)
{
m_factorType = factorType;
m_filePath = filePath;
FactorCollection &factorCollection = FactorCollection::Instance();
m_sentenceStart = factorCollection.AddFactor(BOS_);
m_sentenceStartArray[m_factorType] = m_sentenceStart;
m_sentenceEnd = factorCollection.AddFactor(EOS_);
m_sentenceEndArray[m_factorType] = m_sentenceEnd;
MappingBuilder builder(factorCollection, m_lmIdLookup);
lm::ngram::Config config;
IFVERBOSE(1) {
config.messages = &std::cerr;
}
else {
config.messages = NULL;
}
config.enumerate_vocab = &builder;
config.load_method = m_lazy ? util::LAZY : util::POPULATE_OR_READ;
try {
m_ngram = new Model(filePath.c_str(), config);
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
abort();
}
m_nGramOrder = m_ngram->Order();
m_nullContextState.state = m_ngram->NullContextState();
m_beginSentenceState.state = m_ngram->BeginSentenceState();
return true;
}
template <class Model> LMKenResult LanguageModelKen<Model>::GetKenFullScoreGivenState(const std::vector<const Word*> &contextFactor, FFState &state) const
{
LMKenResult result;
if (contextFactor.empty()) {
result.score = 0.0;
result.unknown = false;
result.ngram_length = 0;
return result;
}
lm::ngram::State &realState = static_cast<KenLMState&>(state).state;
std::size_t factor = contextFactor.back()->GetFactor(GetFactorType())->GetId();
lm::WordIndex new_word = (factor >= m_lmIdLookup.size() ? 0 : m_lmIdLookup[factor]);
lm::ngram::State copied(realState);
lm::FullScoreReturn ret(m_ngram->FullScore(copied, new_word, realState));
result.score = TransformLMScore(ret.prob);
result.unknown = (new_word == 0);
result.ngram_length = ret.ngram_length;
return result;
}
template <class Model> LMKenResult LanguageModelKen<Model>::GetKenFullScoreForgotState(const vector<const Word*> &contextFactor, FFState &outState) const
{
LMKenResult result;
if (contextFactor.empty()) {
static_cast<KenLMState&>(outState).state = m_ngram->NullContextState();
result.score = 0.0;
result.unknown = false;
result.ngram_length = 0;
return result;
}
lm::WordIndex indices[contextFactor.size()];
TranslateIDs(contextFactor, indices);
lm::FullScoreReturn ret(m_ngram->FullScoreForgotState(indices + 1, indices + contextFactor.size(), indices[0], static_cast<KenLMState&>(outState).state));
result.score = TransformLMScore(ret.prob);
result.unknown = (indices[0] == 0);
result.ngram_length = ret.ngram_length;
return result;
}
template <class Model> void LanguageModelKen<Model>::GetState(const std::vector<const Word*> &contextFactor, FFState &outState) const
{
if (contextFactor.empty()) {
static_cast<KenLMState&>(outState).state = m_ngram->NullContextState();
return;
}
lm::WordIndex indices[contextFactor.size()];
TranslateIDs(contextFactor, indices);
m_ngram->GetState(indices, indices + contextFactor.size(), static_cast<KenLMState&>(outState).state);
}
template <class Model> const FFState *LanguageModelKen<Model>::GetNullContextState() const
{
return &m_nullContextState;
}
template <class Model> const FFState *LanguageModelKen<Model>::GetBeginSentenceState() const
{
return &m_beginSentenceState;
}
template <class Model> FFState *LanguageModelKen<Model>::NewState(const FFState *from) const
{
KenLMState *ret = new KenLMState;
if (from) {
ret->state = static_cast<const KenLMState&>(*from).state;
}
return ret;
}
template <class Model> lm::WordIndex LanguageModelKen<Model>::GetLmID(const std::string &str) const
{
return m_ngram->GetVocabulary().Index(str);
}
} // namespace
LanguageModelSingleFactor *ConstructKenLM(const std::string &file, bool lazy)
{
lm::ngram::ModelType model_type;
if (lm::ngram::RecognizeBinary(file.c_str(), model_type)) {
switch(model_type) {
case lm::ngram::HASH_PROBING:
return new LanguageModelKen<lm::ngram::ProbingModel>(lazy);
case lm::ngram::TRIE_SORTED:
return new LanguageModelKen<lm::ngram::TrieModel>(lazy);
case lm::ngram::QUANT_TRIE_SORTED:
return new LanguageModelKen<lm::ngram::QuantTrieModel>(lazy);
case lm::ngram::ARRAY_TRIE_SORTED:
return new LanguageModelKen<lm::ngram::ArrayTrieModel>(lazy);
case lm::ngram::QUANT_ARRAY_TRIE_SORTED:
return new LanguageModelKen<lm::ngram::QuantArrayTrieModel>(lazy);
default:
std::cerr << "Unrecognized kenlm model type " << model_type << std::endl;
abort();
}
} else {
return new LanguageModelKen<lm::ngram::ProbingModel>(lazy);
}
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickanimatorcontroller_p.h"
#include <private/qquickwindow_p.h>
#include <private/qsgrenderloop_p.h>
#include <private/qanimationgroupjob_p.h>
#include <QtGui/qscreen.h>
QT_BEGIN_NAMESPACE
QQuickAnimatorController::QQuickAnimatorController()
: window(0)
{
}
QQuickAnimatorController::~QQuickAnimatorController()
{
qDeleteAll(activeRootAnimations);
}
void QQuickAnimatorController::itemDestroyed(QObject *o)
{
deletedSinceLastFrame << (QQuickItem *) o;
}
void QQuickAnimatorController::advance()
{
bool running = false;
for (QSet<QAbstractAnimationJob *>::const_iterator it = activeRootAnimations.constBegin();
!running && it != activeRootAnimations.constEnd(); ++it) {
if ((*it)->isRunning())
running = true;
}
for (QSet<QQuickAnimatorJob *>::const_iterator it = activeLeafAnimations.constBegin();
it != activeLeafAnimations.constEnd(); ++it) {
if ((*it)->isTransform()) {
QQuickTransformAnimatorJob *xform = static_cast<QQuickTransformAnimatorJob *>(*it);
xform->transformHelper()->apply();
}
}
if (running)
window->update();
}
static void qquick_initialize_helper(QAbstractAnimationJob *job, QQuickAnimatorController *c)
{
if (job->isRenderThreadJob()) {
QQuickAnimatorJob *j = static_cast<QQuickAnimatorJob *>(job);
if (j->target() && c->deletedSinceLastFrame.contains(j->target()))
j->targetWasDeleted();
else
j->initialize(c);
} else if (job->isGroup()) {
QAnimationGroupJob *g = static_cast<QAnimationGroupJob *>(job);
for (QAbstractAnimationJob *a = g->firstChild(); a; a = a->nextSibling())
qquick_initialize_helper(a, c);
}
}
void QQuickAnimatorController::beforeNodeSync()
{
// Force a render pass if we are adding new animations
// so that advance will be called..
if (starting.size())
window->update();
for (int i=0; i<starting.size(); ++i) {
QAbstractAnimationJob *job = starting.at(i);
job->addAnimationChangeListener(this, QAbstractAnimationJob::StateChange);
qquick_initialize_helper(job, this);
job->start();
}
starting.clear();
deletedSinceLastFrame.clear();
for (QSet<QQuickAnimatorJob *>::const_iterator it = activeLeafAnimations.constBegin();
it != activeLeafAnimations.constEnd(); ++it) {
if ((*it)->isTransform()) {
QQuickTransformAnimatorJob *xform = static_cast<QQuickTransformAnimatorJob *>(*it);
xform->transformHelper()->sync();
}
}
}
void QQuickAnimatorController::afterNodeSync()
{
for (QSet<QQuickAnimatorJob *>::const_iterator it = activeLeafAnimations.constBegin();
it != activeLeafAnimations.constEnd(); ++it) {
if ((*it)->isUniform()) {
QQuickUniformAnimatorJob *job = static_cast<QQuickUniformAnimatorJob *>(*it);
job->afterNodeSync();
}
}
}
void QQuickAnimatorController::startAnimation(QAbstractAnimationJob *job)
{
mutex.lock();
starting << job;
mutex.unlock();
}
void QQuickAnimatorController::animationsStarted()
{
window->update();
}
void QQuickAnimatorController::animationStateChanged(QAbstractAnimationJob *job,
QAbstractAnimationJob::State newState,
QAbstractAnimationJob::State)
{
if (newState == QAbstractAnimationJob::Running)
activeRootAnimations << job;
else
activeRootAnimations.remove(job);
}
bool QQuickAnimatorController::event(QEvent *e)
{
if ((int) e->type() == StopAnimation) {
QAbstractAnimationJob *job = static_cast<Event *>(e)->job;
mutex.lock();
starting.removeOne(job);
mutex.unlock();
job->stop();
return true;
} else if ((uint) e->type() == DeleteAnimation) {
QAbstractAnimationJob *job = static_cast<Event *>(e)->job;
mutex.lock();
starting.removeOne(job);
mutex.unlock();
job->stop();
delete job;
return true;
}
return QObject::event(e);
}
QT_END_NAMESPACE
<commit_msg>Fix crash in tst_qmltest with the new animators.<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickanimatorcontroller_p.h"
#include <private/qquickwindow_p.h>
#include <private/qsgrenderloop_p.h>
#include <private/qanimationgroupjob_p.h>
#include <QtGui/qscreen.h>
QT_BEGIN_NAMESPACE
QQuickAnimatorController::QQuickAnimatorController()
: window(0)
{
}
QQuickAnimatorController::~QQuickAnimatorController()
{
qDeleteAll(activeRootAnimations);
}
void QQuickAnimatorController::itemDestroyed(QObject *o)
{
deletedSinceLastFrame << (QQuickItem *) o;
}
void QQuickAnimatorController::advance()
{
bool running = false;
for (QSet<QAbstractAnimationJob *>::const_iterator it = activeRootAnimations.constBegin();
!running && it != activeRootAnimations.constEnd(); ++it) {
if ((*it)->isRunning())
running = true;
}
for (QSet<QQuickAnimatorJob *>::const_iterator it = activeLeafAnimations.constBegin();
it != activeLeafAnimations.constEnd(); ++it) {
QQuickAnimatorJob *job = *it;
if (job->isTransform() && job->target()) {
QQuickTransformAnimatorJob *xform = static_cast<QQuickTransformAnimatorJob *>(*it);
xform->transformHelper()->apply();
}
}
if (running)
window->update();
}
static void qquick_initialize_helper(QAbstractAnimationJob *job, QQuickAnimatorController *c)
{
if (job->isRenderThreadJob()) {
QQuickAnimatorJob *j = static_cast<QQuickAnimatorJob *>(job);
if (!j->target())
return;
else if (c->deletedSinceLastFrame.contains(j->target()))
j->targetWasDeleted();
else
j->initialize(c);
} else if (job->isGroup()) {
QAnimationGroupJob *g = static_cast<QAnimationGroupJob *>(job);
for (QAbstractAnimationJob *a = g->firstChild(); a; a = a->nextSibling())
qquick_initialize_helper(a, c);
}
}
void QQuickAnimatorController::beforeNodeSync()
{
// Force a render pass if we are adding new animations
// so that advance will be called..
if (starting.size())
window->update();
for (int i=0; i<starting.size(); ++i) {
QAbstractAnimationJob *job = starting.at(i);
job->addAnimationChangeListener(this, QAbstractAnimationJob::StateChange);
qquick_initialize_helper(job, this);
job->start();
}
starting.clear();
for (QSet<QQuickAnimatorJob *>::const_iterator it = activeLeafAnimations.constBegin();
it != activeLeafAnimations.constEnd(); ++it) {
QQuickAnimatorJob *job = *it;
if (!job->target())
continue;
else if (deletedSinceLastFrame.contains(job->target()))
job->targetWasDeleted();
else if (job->isTransform()) {
QQuickTransformAnimatorJob *xform = static_cast<QQuickTransformAnimatorJob *>(*it);
xform->transformHelper()->sync();
}
}
deletedSinceLastFrame.clear();
}
void QQuickAnimatorController::afterNodeSync()
{
for (QSet<QQuickAnimatorJob *>::const_iterator it = activeLeafAnimations.constBegin();
it != activeLeafAnimations.constEnd(); ++it) {
QQuickAnimatorJob *job = *it;
if (job->isUniform() && job->target()) {
QQuickUniformAnimatorJob *job = static_cast<QQuickUniformAnimatorJob *>(*it);
job->afterNodeSync();
}
}
}
void QQuickAnimatorController::startAnimation(QAbstractAnimationJob *job)
{
mutex.lock();
starting << job;
mutex.unlock();
}
void QQuickAnimatorController::animationsStarted()
{
window->update();
}
void QQuickAnimatorController::animationStateChanged(QAbstractAnimationJob *job,
QAbstractAnimationJob::State newState,
QAbstractAnimationJob::State)
{
if (newState == QAbstractAnimationJob::Running)
activeRootAnimations << job;
else
activeRootAnimations.remove(job);
}
bool QQuickAnimatorController::event(QEvent *e)
{
if ((int) e->type() == StopAnimation) {
QAbstractAnimationJob *job = static_cast<Event *>(e)->job;
mutex.lock();
starting.removeOne(job);
mutex.unlock();
job->stop();
return true;
} else if ((uint) e->type() == DeleteAnimation) {
QAbstractAnimationJob *job = static_cast<Event *>(e)->job;
mutex.lock();
starting.removeOne(job);
mutex.unlock();
job->stop();
delete job;
return true;
}
return QObject::event(e);
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>/*
* Copyright 2018 Google, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include "base/logging.hh"
#include "systemc/core/process.hh"
#include "systemc/core/scheduler.hh"
#include "systemc/ext/core/sc_main.hh"
#include "systemc/ext/core/sc_process_handle.hh"
#include "systemc/ext/utils/sc_report_handler.hh"
namespace sc_core
{
const char *
sc_unwind_exception::what() const throw()
{
return _isReset ? "RESET" : "KILL";
}
bool
sc_unwind_exception::is_reset() const
{
return _isReset;
}
sc_unwind_exception::sc_unwind_exception() : _isReset(false) {}
sc_unwind_exception::sc_unwind_exception(const sc_unwind_exception &e) :
_isReset(e._isReset)
{}
sc_unwind_exception::~sc_unwind_exception() throw() {}
void
sc_set_location(const char *file, int lineno)
{
sc_process_b *current = ::sc_gem5::scheduler.current();
if (!current)
return;
current->file = file;
current->lineno = lineno;
}
sc_process_b *
sc_get_curr_process_handle()
{
warn("%s not implemented.\n", __PRETTY_FUNCTION__);
return nullptr;
}
sc_process_handle::sc_process_handle() : _gem5_process(nullptr) {}
sc_process_handle::sc_process_handle(const sc_process_handle &handle) :
_gem5_process(handle._gem5_process)
{
if (_gem5_process)
_gem5_process->incref();
}
sc_process_handle::sc_process_handle(sc_object *obj) :
_gem5_process(dynamic_cast<::sc_gem5::Process *>(obj))
{
if (_gem5_process)
_gem5_process->incref();
}
sc_process_handle::~sc_process_handle()
{
if (_gem5_process)
_gem5_process->decref();
}
bool
sc_process_handle::valid() const
{
return _gem5_process != nullptr;
}
sc_process_handle &
sc_process_handle::operator = (const sc_process_handle &handle)
{
if (_gem5_process)
_gem5_process->decref();
_gem5_process = handle._gem5_process;
if (_gem5_process)
_gem5_process->incref();
return *this;
}
bool
sc_process_handle::operator == (const sc_process_handle &handle) const
{
return _gem5_process && handle._gem5_process &&
(_gem5_process == handle._gem5_process);
}
bool
sc_process_handle::operator != (const sc_process_handle &handle) const
{
return !(handle == *this);
}
bool
sc_process_handle::operator < (const sc_process_handle &other) const
{
return _gem5_process < other._gem5_process;
}
void
sc_process_handle::swap(sc_process_handle &handle)
{
::sc_gem5::Process *temp = handle._gem5_process;
handle._gem5_process = _gem5_process;
_gem5_process = temp;
}
const char *
sc_process_handle::name() const
{
return _gem5_process ? _gem5_process->name() : "";
}
sc_curr_proc_kind
sc_process_handle::proc_kind() const
{
return _gem5_process ? _gem5_process->procKind() : SC_NO_PROC_;
}
const std::vector<sc_object *> &
sc_process_handle::get_child_objects() const
{
static const std::vector<sc_object *> empty;
return _gem5_process ? _gem5_process->get_child_objects() : empty;
}
const std::vector<sc_event *> &
sc_process_handle::get_child_events() const
{
static const std::vector<sc_event *> empty;
return _gem5_process ? _gem5_process->get_child_events() : empty;
}
sc_object *
sc_process_handle::get_parent_object() const
{
return _gem5_process ? _gem5_process->get_parent_object() : nullptr;
}
sc_object *
sc_process_handle::get_process_object() const
{
return _gem5_process;
}
bool
sc_process_handle::dynamic() const
{
return _gem5_process ? _gem5_process->dynamic() : false;
}
bool
sc_process_handle::terminated() const
{
return _gem5_process ? _gem5_process->terminated() : false;
}
const sc_event &
sc_process_handle::terminated_event() const
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "terminated_event()");
static sc_event non_event;
return non_event;
}
return _gem5_process->terminatedEvent();
}
void
sc_process_handle::suspend(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "suspend()");
return;
}
_gem5_process->suspend(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::resume(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "resume()");
return;
}
_gem5_process->resume(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::disable(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "disable()");
return;
}
_gem5_process->disable(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::enable(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "enable()");
return;
}
_gem5_process->enable(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::kill(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "kill()");
return;
}
_gem5_process->kill(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::reset(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "reset()");
return;
}
_gem5_process->reset(include_descendants == SC_INCLUDE_DESCENDANTS);
}
bool
sc_process_handle::is_unwinding()
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "is_unwinding()");
return false;
}
return _gem5_process->isUnwinding();
}
const sc_event &
sc_process_handle::reset_event() const
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "reset()");
static sc_event non_event;
return non_event;
}
return _gem5_process->resetEvent();
}
void
sc_process_handle::sync_reset_on(
sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "sync_reset_on()");
return;
}
_gem5_process->syncResetOn(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::sync_reset_off(
sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "sync_reset_off()");
return;
}
_gem5_process->syncResetOff(include_descendants == SC_INCLUDE_DESCENDANTS);
}
sc_process_handle
sc_get_current_process_handle()
{
if (sc_is_running())
return sc_process_handle(::sc_gem5::scheduler.current());
else
return sc_process_handle(::sc_gem5::Process::newest());
}
bool
sc_is_unwinding()
{
return sc_get_current_process_handle().is_unwinding();
}
bool sc_allow_process_control_corners;
} // namespace sc_core
<commit_msg>systemc: Implement sc_get_curr_process_handle().<commit_after>/*
* Copyright 2018 Google, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include "base/logging.hh"
#include "systemc/core/process.hh"
#include "systemc/core/scheduler.hh"
#include "systemc/ext/core/sc_main.hh"
#include "systemc/ext/core/sc_process_handle.hh"
#include "systemc/ext/utils/sc_report_handler.hh"
namespace sc_core
{
const char *
sc_unwind_exception::what() const throw()
{
return _isReset ? "RESET" : "KILL";
}
bool
sc_unwind_exception::is_reset() const
{
return _isReset;
}
sc_unwind_exception::sc_unwind_exception() : _isReset(false) {}
sc_unwind_exception::sc_unwind_exception(const sc_unwind_exception &e) :
_isReset(e._isReset)
{}
sc_unwind_exception::~sc_unwind_exception() throw() {}
void
sc_set_location(const char *file, int lineno)
{
sc_process_b *current = ::sc_gem5::scheduler.current();
if (!current)
return;
current->file = file;
current->lineno = lineno;
}
sc_process_b *
sc_get_curr_process_handle()
{
return ::sc_gem5::scheduler.current();
}
sc_process_handle::sc_process_handle() : _gem5_process(nullptr) {}
sc_process_handle::sc_process_handle(const sc_process_handle &handle) :
_gem5_process(handle._gem5_process)
{
if (_gem5_process)
_gem5_process->incref();
}
sc_process_handle::sc_process_handle(sc_object *obj) :
_gem5_process(dynamic_cast<::sc_gem5::Process *>(obj))
{
if (_gem5_process)
_gem5_process->incref();
}
sc_process_handle::~sc_process_handle()
{
if (_gem5_process)
_gem5_process->decref();
}
bool
sc_process_handle::valid() const
{
return _gem5_process != nullptr;
}
sc_process_handle &
sc_process_handle::operator = (const sc_process_handle &handle)
{
if (_gem5_process)
_gem5_process->decref();
_gem5_process = handle._gem5_process;
if (_gem5_process)
_gem5_process->incref();
return *this;
}
bool
sc_process_handle::operator == (const sc_process_handle &handle) const
{
return _gem5_process && handle._gem5_process &&
(_gem5_process == handle._gem5_process);
}
bool
sc_process_handle::operator != (const sc_process_handle &handle) const
{
return !(handle == *this);
}
bool
sc_process_handle::operator < (const sc_process_handle &other) const
{
return _gem5_process < other._gem5_process;
}
void
sc_process_handle::swap(sc_process_handle &handle)
{
::sc_gem5::Process *temp = handle._gem5_process;
handle._gem5_process = _gem5_process;
_gem5_process = temp;
}
const char *
sc_process_handle::name() const
{
return _gem5_process ? _gem5_process->name() : "";
}
sc_curr_proc_kind
sc_process_handle::proc_kind() const
{
return _gem5_process ? _gem5_process->procKind() : SC_NO_PROC_;
}
const std::vector<sc_object *> &
sc_process_handle::get_child_objects() const
{
static const std::vector<sc_object *> empty;
return _gem5_process ? _gem5_process->get_child_objects() : empty;
}
const std::vector<sc_event *> &
sc_process_handle::get_child_events() const
{
static const std::vector<sc_event *> empty;
return _gem5_process ? _gem5_process->get_child_events() : empty;
}
sc_object *
sc_process_handle::get_parent_object() const
{
return _gem5_process ? _gem5_process->get_parent_object() : nullptr;
}
sc_object *
sc_process_handle::get_process_object() const
{
return _gem5_process;
}
bool
sc_process_handle::dynamic() const
{
return _gem5_process ? _gem5_process->dynamic() : false;
}
bool
sc_process_handle::terminated() const
{
return _gem5_process ? _gem5_process->terminated() : false;
}
const sc_event &
sc_process_handle::terminated_event() const
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "terminated_event()");
static sc_event non_event;
return non_event;
}
return _gem5_process->terminatedEvent();
}
void
sc_process_handle::suspend(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "suspend()");
return;
}
_gem5_process->suspend(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::resume(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "resume()");
return;
}
_gem5_process->resume(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::disable(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "disable()");
return;
}
_gem5_process->disable(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::enable(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "enable()");
return;
}
_gem5_process->enable(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::kill(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "kill()");
return;
}
_gem5_process->kill(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::reset(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "reset()");
return;
}
_gem5_process->reset(include_descendants == SC_INCLUDE_DESCENDANTS);
}
bool
sc_process_handle::is_unwinding()
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "is_unwinding()");
return false;
}
return _gem5_process->isUnwinding();
}
const sc_event &
sc_process_handle::reset_event() const
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "reset()");
static sc_event non_event;
return non_event;
}
return _gem5_process->resetEvent();
}
void
sc_process_handle::sync_reset_on(
sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "sync_reset_on()");
return;
}
_gem5_process->syncResetOn(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::sync_reset_off(
sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING("(W570) attempt to use an empty "
"process handle ignored", "sync_reset_off()");
return;
}
_gem5_process->syncResetOff(include_descendants == SC_INCLUDE_DESCENDANTS);
}
sc_process_handle
sc_get_current_process_handle()
{
if (sc_is_running())
return sc_process_handle(::sc_gem5::scheduler.current());
else
return sc_process_handle(::sc_gem5::Process::newest());
}
bool
sc_is_unwinding()
{
return sc_get_current_process_handle().is_unwinding();
}
bool sc_allow_process_control_corners;
} // namespace sc_core
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsystemnetworkinfo.h"
#include "qsysteminfocommon_p.h"
#include <QMetaType>
QTM_BEGIN_NAMESPACE
Q_GLOBAL_STATIC(QSystemNetworkInfoPrivate, netInfoPrivate)
#ifdef QT_SIMULATOR
QSystemNetworkInfoPrivate *getSystemNetworkInfoPrivate() { return netInfoPrivate(); }
#endif
/*!
\class QSystemNetworkInfo
\ingroup systeminfo
\inmodule QtSystemInfo
\brief The QSystemNetworkInfo class provides access to various networking status and signals.
*/
/*!
\enum QSystemNetworkInfo::NetworkStatus
This enum describes the status of the network connection:
\value UndefinedStatus There is no network device, or error.
\value NoNetworkAvailable There is no network available.
\value EmergencyOnly Emergency calls only.
\value Searching Searching for or connecting with the network.
\value Busy Network is busy.
\value Connected Connected to network.
\value HomeNetwork On Home Network.
\value Denied Network access denied.
\value Roaming On Roaming network.
*/
/*!
\enum QSystemNetworkInfo::NetworkMode
This enum describes the type of network:
\value UnknownMode Unknown network, or network error.
\value GsmMode Global System for Mobile (GSM) network.
\value CdmaMode Code division multiple access (CDMA) network.
\value WcdmaMode Wideband Code Division Multiple Access (W-CDMA) network.
\value WlanMode Wireless Local Area Network (WLAN) network.
\value EthernetMode Wired Local Area network.
\value BluetoothMode Bluetooth network.
\value WimaxMode Wimax network.
\value LteMode Lte network.
*/
/*!
\enum QSystemNetworkInfo::CellDataTechnology
This enum describes the type of cellular technology:
\value UnknownDataTechnology Unknown cellular technology, or error.
\value GprsDataTechnology General Packet Radio Service (GPRS) data service.
\value EdgeDataTechnology Enhanced Data Rates for GSM Evolution (EDGE) data service.
\value UmtsDataTechnology Universal Mobile Telecommunications System (UMTS) data service.
\value HspaDataTechnology High Speed Packet Access (HSPA) data service.
*/
/*!
\fn void QSystemNetworkInfo::networkStatusChanged(QSystemNetworkInfo::NetworkMode mode, QSystemNetworkInfo::NetworkStatus status)
This signal is emitted whenever the network status of \a mode changes, specified by \a status.
*/
/*!
\fn void QSystemNetworkInfo::networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode mode,int strength)
This signal is emitted whenever the network \a mode signal strength changes, specified by \a strength.
*/
/*!
\fn void QSystemNetworkInfo::currentMobileCountryCodeChanged(const QString &mcc)
This signal is emitted whenever the Mobile Country Code changes, specified by \a mcc.
*/
/*!
\fn void QSystemNetworkInfo::currentMobileNetworkCodeChanged(const QString &mnc)
This signal is emitted whenever the network Mobile Network Code changes, specified by \a mnc.
*/
/*!
\fn void QSystemNetworkInfo::networkNameChanged(QSystemNetworkInfo::NetworkMode mode,const QString & netName)
This signal is emitted whenever the network \a mode name changes, specified by \a netName.
*/
/*!
\fn void QSystemNetworkInfo::cellIdChanged(int cellId)
This signal is emitted whenever the network cell changes, specified by \a cellId.
*/
/*!
\fn void QSystemNetworkInfo::networkModeChanged(QSystemNetworkInfo::NetworkMode mode)
This signal is emitted whenever the network mode changes, specified by \a mode.
*/
/*!
\fn void QSystemNetworkInfo::cellDataTechnologyChanged(QSystemNetworkInfo::CellDataTechnology cellTech)
This signal is emitted whenever the cellular technology changes, specified by \a cellTech.
*/
/*!
Constructs a QSystemNetworkInfo with the given \a parent.
*/
QSystemNetworkInfo::QSystemNetworkInfo(QObject *parent)
: QObject(parent), d(netInfoPrivate())
{
qRegisterMetaType<QSystemNetworkInfo::NetworkMode>("QSystemNetworkInfo::NetworkMode");
qRegisterMetaType<QSystemNetworkInfo::NetworkStatus>("QSystemNetworkInfo::NetworkStatus");
}
/*!
Destroys the QSystemNetworkInfo object.
*/
QSystemNetworkInfo::~QSystemNetworkInfo()
{
}
/*!
Returns the status of the network \a mode.
*/
QSystemNetworkInfo::NetworkStatus QSystemNetworkInfo::networkStatus(QSystemNetworkInfo::NetworkMode mode)
{
return netInfoPrivate()->networkStatus(mode);
}
/*!
Returns the strength of the network signal, per network \a mode , 0 - 100 linear scaling,
or -1 in the case of unknown network mode or error.
In the case of QSystemNetworkInfo::EthMode, it will either be 100 for carrier active, or 0 for when
there is no carrier or cable connected.
*/
int QSystemNetworkInfo::networkSignalStrength(QSystemNetworkInfo::NetworkMode mode)
{
QSystemNetworkInfo::NetworkStatus info = netInfoPrivate()->networkStatus(mode);
if(info == QSystemNetworkInfo::UndefinedStatus
|| info == QSystemNetworkInfo::NoNetworkAvailable) {
return 0;
}
return netInfoPrivate()->networkSignalStrength(mode);
}
/*!
\property QSystemNetworkInfo::cellId
\brief The devices Cell ID
Returns the Cell ID of the connected tower or based station, or 0 if not connected.
*/
int QSystemNetworkInfo::cellId()
{
return netInfoPrivate()->cellId();
}
/*!
\property QSystemNetworkInfo::locationAreaCode
\brief The LAC.
Returns the Location Area Code. In the case of a Desktop computer, 0 is returned.
*/
int QSystemNetworkInfo::locationAreaCode()
{
return netInfoPrivate()->locationAreaCode();
}
/*!
\property QSystemNetworkInfo::currentMobileCountryCode
\brief The current MCC.
Returns the current Mobile Country Code. In the case of a Desktop computer, an empty string is returned.
*/
QString QSystemNetworkInfo::currentMobileCountryCode()
{
return netInfoPrivate()->currentMobileCountryCode();
}
/*!
\property QSystemNetworkInfo::currentMobileNetworkCode
\brief The current MNC.
Returns the current Mobile Network Code. In the case of a Desktop computer, an empty string is returned.
*/
QString QSystemNetworkInfo::currentMobileNetworkCode()
{
return netInfoPrivate()->currentMobileNetworkCode();
}
/*!
\property QSystemNetworkInfo::homeMobileCountryCode
\brief The home MNC.
Returns the home Mobile Country Code. In the case of a Desktop computer, an empty string is returned.
*/
QString QSystemNetworkInfo::homeMobileCountryCode()
{
return netInfoPrivate()->homeMobileCountryCode();
}
/*!
\property QSystemNetworkInfo::homeMobileNetworkCode
\brief The home MCC.
Returns the home Mobile Network Code. In the case of a Desktop computer, an empty string is returned.
Note: Some platforms don't support retrieving this info. In this case the Network Code is
returned only when the device is registered on home network.
*/
QString QSystemNetworkInfo::homeMobileNetworkCode()
{
return netInfoPrivate()->homeMobileNetworkCode();
}
/*!
Returns the name of the operator for the network \a mode. For wlan this returns the network's current SSID.
In the case of a Desktop computer, an empty string is returned.
*/
QString QSystemNetworkInfo::networkName(QSystemNetworkInfo::NetworkMode mode)
{
return netInfoPrivate()->networkName(mode);
}
/*!
Returns the MAC address for the interface servicing the network \a mode.
*/
QString QSystemNetworkInfo::macAddress(QSystemNetworkInfo::NetworkMode mode)
{
return netInfoPrivate()->macAddress(mode);
}
/*!
Returns the first found QNetworkInterface for type \a mode, or an invalid QNetworkInterface, if none is found.
*/
QNetworkInterface QSystemNetworkInfo::interfaceForMode(QSystemNetworkInfo::NetworkMode mode)
{
return netInfoPrivate()->interfaceForMode(mode);
}
/*!
\property QSystemNetworkInfo::currentMode
Returns the current active mode. If more than one mode is active, returns the
default or preferred mode. If no modes are active, returns UnknownMode.
*/
QSystemNetworkInfo::NetworkMode QSystemNetworkInfo::currentMode()
{
return netInfoPrivate()->currentMode();
}
/*!
\internal
This function is called when the client connects to the networkSignalStrengthChanged()
signal.
*/
void QSystemNetworkInfo::connectNotify(const char *signal)
{
//check for networkSignalStrengthChanged() signal connect notification
//This is not required on all platforms
#if defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode, int))))) {
netInfoPrivate()->setWlanSignalStrengthCheckEnabled(true);
}
#endif
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
currentMobileCountryCodeChanged(QString))))) {
connect(d,SIGNAL(currentMobileCountryCodeChanged(QString)),
this,SIGNAL(currentMobileCountryCodeChanged(QString)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
currentMobileNetworkCodeChanged(QString))))) {
connect(d,SIGNAL(currentMobileNetworkCodeChanged(QString)),
this,SIGNAL(currentMobileNetworkCodeChanged(QString)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkModeChanged(QSystemNetworkInfo::NetworkMode))))) {
connect(d,SIGNAL(networkModeChanged(QSystemNetworkInfo::NetworkMode)),
this,SIGNAL(networkModeChanged(QSystemNetworkInfo::NetworkMode)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkNameChanged(QSystemNetworkInfo::NetworkMode,QString))))) {
connect(d,SIGNAL(networkNameChanged(QSystemNetworkInfo::NetworkMode,QString)),
this,SIGNAL(networkNameChanged(QSystemNetworkInfo::NetworkMode,QString)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode,int))))) {
connect(d,SIGNAL(networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode,int)),
this,SIGNAL(networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode,int)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus))))) {
connect(d,SIGNAL(networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus)),
this,SIGNAL(networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
cellIdChanged(int))))) {
connect(d,SIGNAL(cellIdChanged(int)),this,SIGNAL(cellIdChanged(int)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
cellIdChanged(int))))) {
connect(d,SIGNAL(cellDataTechnologyChanged(QSystemNetworkInfo::CellDataTechnology)),
this,SIGNAL(cellDataTechnologyChanged(QSystemNetworkInfo::CellDataTechnology)));
}
}
/*!
\internal
This function is called when the client disconnects from the networkSignalStrengthChanged()
signal.
\sa connectNotify()
*/
void QSystemNetworkInfo::disconnectNotify(const char *signal)
{
//check for networkSignalStrengthChanged() signal disconnect notification
//This is not required on all platforms
#if defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode, int))))) {
netInfoPrivate()->setWlanSignalStrengthCheckEnabled(false);
}
#endif
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
currentMobileCountryCodeChanged(QString))))) {
disconnect(d,SIGNAL(currentMobileCountryCodeChanged(QString)),
this,SIGNAL(currentMobileCountryCodeChanged(QString)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
currentMobileNetworkCodeChanged(QString))))) {
disconnect(d,SIGNAL(currentMobileNetworkCodeChanged(QString)),
this,SIGNAL(currentMobileNetworkCodeChanged(QString)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkModeChanged(QSystemNetworkInfo::NetworkMode))))) {
disconnect(d,SIGNAL(networkModeChanged(QSystemNetworkInfo::NetworkMode)),
this,SIGNAL(networkModeChanged(QSystemNetworkInfo::NetworkMode)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkNameChanged(QSystemNetworkInfo::NetworkMode,QString))))) {
disconnect(d,SIGNAL(networkNameChanged(QSystemNetworkInfo::NetworkMode,QString)),
this,SIGNAL(networkNameChanged(QSystemNetworkInfo::NetworkMode,QString)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode,int))))) {
disconnect(d,SIGNAL(networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode,int)),
this,SIGNAL(networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode,int)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus))))) {
disconnect(d,SIGNAL(networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus)),
this,SIGNAL(networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
cellIdChanged(int))))) {
disconnect(d,SIGNAL(cellIdChanged(int)),this,SIGNAL(cellIdChanged(int)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
cellIdChanged(int))))) {
disconnect(d,SIGNAL(cellDataTechnologyChanged(QSystemNetworkInfo::CellDataTechnology)),
this,SIGNAL(cellDataTechnologyChanged(QSystemNetworkInfo::CellDataTechnology)));
}
}
/*!
\property QSystemNetworkInfo::cellDataTechnology
Returns the current active cell data technology.
If no data technology is active, or data technology is not supported, QSystemNetworkInfo::UnknownDataTechnology
is returned.
*/
QSystemNetworkInfo::CellDataTechnology QSystemNetworkInfo::cellDataTechnology()
{
return netInfoPrivate()->cellDataTechnology();
}
#include "moc_qsystemnetworkinfo.cpp"
QTM_END_NAMESPACE
<commit_msg>Fix the doc for interfaceForMode().<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsystemnetworkinfo.h"
#include "qsysteminfocommon_p.h"
#include <QMetaType>
QTM_BEGIN_NAMESPACE
Q_GLOBAL_STATIC(QSystemNetworkInfoPrivate, netInfoPrivate)
#ifdef QT_SIMULATOR
QSystemNetworkInfoPrivate *getSystemNetworkInfoPrivate() { return netInfoPrivate(); }
#endif
/*!
\class QSystemNetworkInfo
\ingroup systeminfo
\inmodule QtSystemInfo
\brief The QSystemNetworkInfo class provides access to various networking status and signals.
*/
/*!
\enum QSystemNetworkInfo::NetworkStatus
This enum describes the status of the network connection:
\value UndefinedStatus There is no network device, or error.
\value NoNetworkAvailable There is no network available.
\value EmergencyOnly Emergency calls only.
\value Searching Searching for or connecting with the network.
\value Busy Network is busy.
\value Connected Connected to network.
\value HomeNetwork On Home Network.
\value Denied Network access denied.
\value Roaming On Roaming network.
*/
/*!
\enum QSystemNetworkInfo::NetworkMode
This enum describes the type of network:
\value UnknownMode Unknown network, or network error.
\value GsmMode Global System for Mobile (GSM) network.
\value CdmaMode Code division multiple access (CDMA) network.
\value WcdmaMode Wideband Code Division Multiple Access (W-CDMA) network.
\value WlanMode Wireless Local Area Network (WLAN) network.
\value EthernetMode Wired Local Area network.
\value BluetoothMode Bluetooth network.
\value WimaxMode Wimax network.
\value LteMode Lte network.
*/
/*!
\enum QSystemNetworkInfo::CellDataTechnology
This enum describes the type of cellular technology:
\value UnknownDataTechnology Unknown cellular technology, or error.
\value GprsDataTechnology General Packet Radio Service (GPRS) data service.
\value EdgeDataTechnology Enhanced Data Rates for GSM Evolution (EDGE) data service.
\value UmtsDataTechnology Universal Mobile Telecommunications System (UMTS) data service.
\value HspaDataTechnology High Speed Packet Access (HSPA) data service.
*/
/*!
\fn void QSystemNetworkInfo::networkStatusChanged(QSystemNetworkInfo::NetworkMode mode, QSystemNetworkInfo::NetworkStatus status)
This signal is emitted whenever the network status of \a mode changes, specified by \a status.
*/
/*!
\fn void QSystemNetworkInfo::networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode mode,int strength)
This signal is emitted whenever the network \a mode signal strength changes, specified by \a strength.
*/
/*!
\fn void QSystemNetworkInfo::currentMobileCountryCodeChanged(const QString &mcc)
This signal is emitted whenever the Mobile Country Code changes, specified by \a mcc.
*/
/*!
\fn void QSystemNetworkInfo::currentMobileNetworkCodeChanged(const QString &mnc)
This signal is emitted whenever the network Mobile Network Code changes, specified by \a mnc.
*/
/*!
\fn void QSystemNetworkInfo::networkNameChanged(QSystemNetworkInfo::NetworkMode mode,const QString & netName)
This signal is emitted whenever the network \a mode name changes, specified by \a netName.
*/
/*!
\fn void QSystemNetworkInfo::cellIdChanged(int cellId)
This signal is emitted whenever the network cell changes, specified by \a cellId.
*/
/*!
\fn void QSystemNetworkInfo::networkModeChanged(QSystemNetworkInfo::NetworkMode mode)
This signal is emitted whenever the network mode changes, specified by \a mode.
*/
/*!
\fn void QSystemNetworkInfo::cellDataTechnologyChanged(QSystemNetworkInfo::CellDataTechnology cellTech)
This signal is emitted whenever the cellular technology changes, specified by \a cellTech.
*/
/*!
Constructs a QSystemNetworkInfo with the given \a parent.
*/
QSystemNetworkInfo::QSystemNetworkInfo(QObject *parent)
: QObject(parent), d(netInfoPrivate())
{
qRegisterMetaType<QSystemNetworkInfo::NetworkMode>("QSystemNetworkInfo::NetworkMode");
qRegisterMetaType<QSystemNetworkInfo::NetworkStatus>("QSystemNetworkInfo::NetworkStatus");
}
/*!
Destroys the QSystemNetworkInfo object.
*/
QSystemNetworkInfo::~QSystemNetworkInfo()
{
}
/*!
Returns the status of the network \a mode.
*/
QSystemNetworkInfo::NetworkStatus QSystemNetworkInfo::networkStatus(QSystemNetworkInfo::NetworkMode mode)
{
return netInfoPrivate()->networkStatus(mode);
}
/*!
Returns the strength of the network signal, per network \a mode , 0 - 100 linear scaling,
or -1 in the case of unknown network mode or error.
In the case of QSystemNetworkInfo::EthMode, it will either be 100 for carrier active, or 0 for when
there is no carrier or cable connected.
*/
int QSystemNetworkInfo::networkSignalStrength(QSystemNetworkInfo::NetworkMode mode)
{
QSystemNetworkInfo::NetworkStatus info = netInfoPrivate()->networkStatus(mode);
if(info == QSystemNetworkInfo::UndefinedStatus
|| info == QSystemNetworkInfo::NoNetworkAvailable) {
return 0;
}
return netInfoPrivate()->networkSignalStrength(mode);
}
/*!
\property QSystemNetworkInfo::cellId
\brief The devices Cell ID
Returns the Cell ID of the connected tower or based station, or 0 if not connected.
*/
int QSystemNetworkInfo::cellId()
{
return netInfoPrivate()->cellId();
}
/*!
\property QSystemNetworkInfo::locationAreaCode
\brief The LAC.
Returns the Location Area Code. In the case of a Desktop computer, 0 is returned.
*/
int QSystemNetworkInfo::locationAreaCode()
{
return netInfoPrivate()->locationAreaCode();
}
/*!
\property QSystemNetworkInfo::currentMobileCountryCode
\brief The current MCC.
Returns the current Mobile Country Code. In the case of a Desktop computer, an empty string is returned.
*/
QString QSystemNetworkInfo::currentMobileCountryCode()
{
return netInfoPrivate()->currentMobileCountryCode();
}
/*!
\property QSystemNetworkInfo::currentMobileNetworkCode
\brief The current MNC.
Returns the current Mobile Network Code. In the case of a Desktop computer, an empty string is returned.
*/
QString QSystemNetworkInfo::currentMobileNetworkCode()
{
return netInfoPrivate()->currentMobileNetworkCode();
}
/*!
\property QSystemNetworkInfo::homeMobileCountryCode
\brief The home MNC.
Returns the home Mobile Country Code. In the case of a Desktop computer, an empty string is returned.
*/
QString QSystemNetworkInfo::homeMobileCountryCode()
{
return netInfoPrivate()->homeMobileCountryCode();
}
/*!
\property QSystemNetworkInfo::homeMobileNetworkCode
\brief The home MCC.
Returns the home Mobile Network Code. In the case of a Desktop computer, an empty string is returned.
Note: Some platforms don't support retrieving this info. In this case the Network Code is
returned only when the device is registered on home network.
*/
QString QSystemNetworkInfo::homeMobileNetworkCode()
{
return netInfoPrivate()->homeMobileNetworkCode();
}
/*!
Returns the name of the operator for the network \a mode. For wlan this returns the network's current SSID.
In the case of a Desktop computer, an empty string is returned.
*/
QString QSystemNetworkInfo::networkName(QSystemNetworkInfo::NetworkMode mode)
{
return netInfoPrivate()->networkName(mode);
}
/*!
Returns the MAC address for the interface servicing the network \a mode.
*/
QString QSystemNetworkInfo::macAddress(QSystemNetworkInfo::NetworkMode mode)
{
return netInfoPrivate()->macAddress(mode);
}
/*!
Returns the first found QNetworkInterface for type \a mode. If none is found, or it can't be represented
by QNetworkInterface (e.g. Bluetooth), an invalid QNetworkInterface object is returned.
*/
QNetworkInterface QSystemNetworkInfo::interfaceForMode(QSystemNetworkInfo::NetworkMode mode)
{
return netInfoPrivate()->interfaceForMode(mode);
}
/*!
\property QSystemNetworkInfo::currentMode
Returns the current active mode. If more than one mode is active, returns the
default or preferred mode. If no modes are active, returns UnknownMode.
*/
QSystemNetworkInfo::NetworkMode QSystemNetworkInfo::currentMode()
{
return netInfoPrivate()->currentMode();
}
/*!
\internal
This function is called when the client connects to the networkSignalStrengthChanged()
signal.
*/
void QSystemNetworkInfo::connectNotify(const char *signal)
{
//check for networkSignalStrengthChanged() signal connect notification
//This is not required on all platforms
#if defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode, int))))) {
netInfoPrivate()->setWlanSignalStrengthCheckEnabled(true);
}
#endif
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
currentMobileCountryCodeChanged(QString))))) {
connect(d,SIGNAL(currentMobileCountryCodeChanged(QString)),
this,SIGNAL(currentMobileCountryCodeChanged(QString)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
currentMobileNetworkCodeChanged(QString))))) {
connect(d,SIGNAL(currentMobileNetworkCodeChanged(QString)),
this,SIGNAL(currentMobileNetworkCodeChanged(QString)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkModeChanged(QSystemNetworkInfo::NetworkMode))))) {
connect(d,SIGNAL(networkModeChanged(QSystemNetworkInfo::NetworkMode)),
this,SIGNAL(networkModeChanged(QSystemNetworkInfo::NetworkMode)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkNameChanged(QSystemNetworkInfo::NetworkMode,QString))))) {
connect(d,SIGNAL(networkNameChanged(QSystemNetworkInfo::NetworkMode,QString)),
this,SIGNAL(networkNameChanged(QSystemNetworkInfo::NetworkMode,QString)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode,int))))) {
connect(d,SIGNAL(networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode,int)),
this,SIGNAL(networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode,int)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus))))) {
connect(d,SIGNAL(networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus)),
this,SIGNAL(networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
cellIdChanged(int))))) {
connect(d,SIGNAL(cellIdChanged(int)),this,SIGNAL(cellIdChanged(int)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
cellIdChanged(int))))) {
connect(d,SIGNAL(cellDataTechnologyChanged(QSystemNetworkInfo::CellDataTechnology)),
this,SIGNAL(cellDataTechnologyChanged(QSystemNetworkInfo::CellDataTechnology)));
}
}
/*!
\internal
This function is called when the client disconnects from the networkSignalStrengthChanged()
signal.
\sa connectNotify()
*/
void QSystemNetworkInfo::disconnectNotify(const char *signal)
{
//check for networkSignalStrengthChanged() signal disconnect notification
//This is not required on all platforms
#if defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode, int))))) {
netInfoPrivate()->setWlanSignalStrengthCheckEnabled(false);
}
#endif
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
currentMobileCountryCodeChanged(QString))))) {
disconnect(d,SIGNAL(currentMobileCountryCodeChanged(QString)),
this,SIGNAL(currentMobileCountryCodeChanged(QString)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
currentMobileNetworkCodeChanged(QString))))) {
disconnect(d,SIGNAL(currentMobileNetworkCodeChanged(QString)),
this,SIGNAL(currentMobileNetworkCodeChanged(QString)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkModeChanged(QSystemNetworkInfo::NetworkMode))))) {
disconnect(d,SIGNAL(networkModeChanged(QSystemNetworkInfo::NetworkMode)),
this,SIGNAL(networkModeChanged(QSystemNetworkInfo::NetworkMode)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkNameChanged(QSystemNetworkInfo::NetworkMode,QString))))) {
disconnect(d,SIGNAL(networkNameChanged(QSystemNetworkInfo::NetworkMode,QString)),
this,SIGNAL(networkNameChanged(QSystemNetworkInfo::NetworkMode,QString)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode,int))))) {
disconnect(d,SIGNAL(networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode,int)),
this,SIGNAL(networkSignalStrengthChanged(QSystemNetworkInfo::NetworkMode,int)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus))))) {
disconnect(d,SIGNAL(networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus)),
this,SIGNAL(networkStatusChanged(QSystemNetworkInfo::NetworkMode,QSystemNetworkInfo::NetworkStatus)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
cellIdChanged(int))))) {
disconnect(d,SIGNAL(cellIdChanged(int)),this,SIGNAL(cellIdChanged(int)));
}
if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(
cellIdChanged(int))))) {
disconnect(d,SIGNAL(cellDataTechnologyChanged(QSystemNetworkInfo::CellDataTechnology)),
this,SIGNAL(cellDataTechnologyChanged(QSystemNetworkInfo::CellDataTechnology)));
}
}
/*!
\property QSystemNetworkInfo::cellDataTechnology
Returns the current active cell data technology.
If no data technology is active, or data technology is not supported, QSystemNetworkInfo::UnknownDataTechnology
is returned.
*/
QSystemNetworkInfo::CellDataTechnology QSystemNetworkInfo::cellDataTechnology()
{
return netInfoPrivate()->cellDataTechnology();
}
#include "moc_qsystemnetworkinfo.cpp"
QTM_END_NAMESPACE
<|endoftext|>
|
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
#ifndef __PROCESS_POSIX_SUBPROCESS_HPP__
#define __PROCESS_POSIX_SUBPROCESS_HPP__
#ifdef __linux__
#include <sys/prctl.h>
#endif // __linux__
#include <sys/types.h>
#include <string>
#include <glog/logging.h>
#include <process/subprocess.hpp>
#include <stout/check.hpp>
#include <stout/error.hpp>
#include <stout/foreach.hpp>
#include <stout/hashset.hpp>
#include <stout/nothing.hpp>
#include <stout/lambda.hpp>
#include <stout/none.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/try.hpp>
#include <stout/unreachable.hpp>
#include <stout/os/close.hpp>
#include <stout/os/environment.hpp>
#include <stout/os/fcntl.hpp>
#include <stout/os/signals.hpp>
#include <stout/os/strerror.hpp>
namespace process {
namespace internal {
static void close(std::initializer_list<int_fd> fds);
static void close(
const Subprocess::IO::InputFileDescriptors& stdinfds,
const Subprocess::IO::OutputFileDescriptors& stdoutfds,
const Subprocess::IO::OutputFileDescriptors& stderrfds);
inline pid_t defaultClone(const lambda::function<int()>& func)
{
pid_t pid = ::fork();
if (pid == -1) {
return -1;
} else if (pid == 0) {
// Child.
::exit(func());
UNREACHABLE();
} else {
// Parent.
return pid;
}
}
// This function will invoke `os::cloexec` on all specified file
// descriptors that are valid (i.e., not `None` and >= 0).
inline Try<Nothing> cloexec(
const InputFileDescriptors& stdinfds,
const OutputFileDescriptors& stdoutfds,
const OutputFileDescriptors& stderrfds)
{
hashset<int> fds = {
stdinfds.read,
stdinfds.write.getOrElse(-1),
stdoutfds.read.getOrElse(-1),
stdoutfds.write,
stderrfds.read.getOrElse(-1),
stderrfds.write
};
foreach (int fd, fds) {
if (fd >= 0) {
Try<Nothing> cloexec = os::cloexec(fd);
if (cloexec.isError()) {
return Error(cloexec.error());
}
}
}
return Nothing();
}
// The main entry of the child process.
//
// NOTE: This function has to be async signal safe.
inline int childMain(
const std::string& path,
char** argv,
char** envp,
const InputFileDescriptors& stdinfds,
const OutputFileDescriptors& stdoutfds,
const OutputFileDescriptors& stderrfds,
bool blocking,
int pipes[2],
const std::vector<Subprocess::ChildHook>& child_hooks)
{
// Close parent's end of the pipes.
if (stdinfds.write.isSome()) {
::close(stdinfds.write.get());
}
if (stdoutfds.read.isSome()) {
::close(stdoutfds.read.get());
}
if (stderrfds.read.isSome()) {
::close(stderrfds.read.get());
}
// Currently we will block the child's execution of the new process
// until all the parent hooks (if any) have executed.
if (blocking) {
::close(pipes[1]);
}
// Redirect I/O for stdin/stdout/stderr.
while (::dup2(stdinfds.read, STDIN_FILENO) == -1 && errno == EINTR);
while (::dup2(stdoutfds.write, STDOUT_FILENO) == -1 && errno == EINTR);
while (::dup2(stderrfds.write, STDERR_FILENO) == -1 && errno == EINTR);
// Close the copies. We need to make sure that we do not close the
// file descriptor assigned to stdin/stdout/stderr in case the
// parent has closed stdin/stdout/stderr when calling this
// function (in that case, a dup'ed file descriptor may have the
// same file descriptor number as stdin/stdout/stderr).
//
// We also need to ensure that we don't "double close" any file
// descriptors in the case where one of stdinfds.read,
// stdoutfds.write, or stdoutfds.write are equal.
if (stdinfds.read != STDIN_FILENO &&
stdinfds.read != STDOUT_FILENO &&
stdinfds.read != STDERR_FILENO) {
::close(stdinfds.read);
}
if (stdoutfds.write != STDIN_FILENO &&
stdoutfds.write != STDOUT_FILENO &&
stdoutfds.write != STDERR_FILENO &&
stdoutfds.write != stdinfds.read) {
::close(stdoutfds.write);
}
if (stderrfds.write != STDIN_FILENO &&
stderrfds.write != STDOUT_FILENO &&
stderrfds.write != STDERR_FILENO &&
stderrfds.write != stdinfds.read &&
stderrfds.write != stdoutfds.write) {
::close(stderrfds.write);
}
if (blocking) {
// Do a blocking read on the pipe until the parent signals us to
// continue.
char dummy;
ssize_t length;
while ((length = ::read(pipes[0], &dummy, sizeof(dummy))) == -1 &&
errno == EINTR);
if (length != sizeof(dummy)) {
ABORT("Failed to synchronize with parent");
}
// Now close the pipe as we don't need it anymore.
::close(pipes[0]);
}
// Run the child hooks.
foreach (const Subprocess::ChildHook& hook, child_hooks) {
Try<Nothing> callback = hook();
// If the callback failed, we should abort execution.
if (callback.isError()) {
ABORT("Failed to execute Subprocess::ChildHook: " + callback.error());
}
}
os::execvpe(path.c_str(), argv, envp);
ABORT("Failed to os::execvpe on path '" + path + "': " + os::strerror(errno));
}
inline Try<pid_t> cloneChild(
const std::string& path,
std::vector<std::string> argv,
const Option<std::map<std::string, std::string>>& environment,
const Option<lambda::function<
pid_t(const lambda::function<int()>&)>>& _clone,
const std::vector<Subprocess::ParentHook>& parent_hooks,
const std::vector<Subprocess::ChildHook>& child_hooks,
const InputFileDescriptors stdinfds,
const OutputFileDescriptors stdoutfds,
const OutputFileDescriptors stderrfds)
{
// The real arguments that will be passed to 'os::execvpe'. We need
// to construct them here before doing the clone as it might not be
// async signal safe to perform the memory allocation.
char** _argv = new char*[argv.size() + 1];
for (size_t i = 0; i < argv.size(); i++) {
_argv[i] = (char*) argv[i].c_str();
}
_argv[argv.size()] = nullptr;
// Like above, we need to construct the environment that we'll pass
// to 'os::execvpe' as it might not be async-safe to perform the
// memory allocations.
char** envp = os::raw::environment();
if (environment.isSome()) {
// NOTE: We add 1 to the size for a `nullptr` terminator.
envp = new char*[environment.get().size() + 1];
size_t index = 0;
foreachpair (
const std::string& key,
const std::string& value, environment.get()) {
std::string entry = key + "=" + value;
envp[index] = new char[entry.size() + 1];
strncpy(envp[index], entry.c_str(), entry.size() + 1);
++index;
}
envp[index] = nullptr;
}
// Determine the function to clone the child process. If the user
// does not specify the clone function, we will use the default.
lambda::function<pid_t(const lambda::function<int()>&)> clone =
(_clone.isSome() ? _clone.get() : defaultClone);
// Currently we will block the child's execution of the new process
// until all the `parent_hooks` (if any) have executed.
std::array<int, 2> pipes;
const bool blocking = !parent_hooks.empty();
if (blocking) {
// We assume this should not fail under reasonable conditions so we
// use CHECK.
Try<std::array<int, 2>> pipe = os::pipe();
CHECK_SOME(pipe);
pipes = pipe.get();
}
// Now, clone the child process.
pid_t pid = clone(lambda::bind(
&childMain,
path,
_argv,
envp,
stdinfds,
stdoutfds,
stderrfds,
blocking,
pipes.data(),
child_hooks));
delete[] _argv;
// Need to delete 'envp' if we had environment variables passed to
// us and we needed to allocate the space.
if (environment.isSome()) {
CHECK_NE(os::raw::environment(), envp);
// We ignore the last 'envp' entry since it is nullptr.
for (size_t index = 0; index < environment->size(); index++) {
delete[] envp[index];
}
delete[] envp;
}
if (pid == -1) {
// Save the errno as 'close' below might overwrite it.
ErrnoError error("Failed to clone");
internal::close(stdinfds, stdoutfds, stderrfds);
if (blocking) {
os::close(pipes[0]);
os::close(pipes[1]);
}
return error;
}
// Close the child-ends of the file descriptors that are created by
// this function.
internal::close({stdinfds.read, stdoutfds.write, stderrfds.write});
if (blocking) {
os::close(pipes[0]);
// Run the parent hooks.
foreach (const Subprocess::ParentHook& hook, parent_hooks) {
Try<Nothing> parentSetup = hook.parent_setup(pid);
// If the hook callback fails, we shouldn't proceed with the
// execution and hence the child process should be killed.
if (parentSetup.isError()) {
LOG(WARNING)
<< "Failed to execute Subprocess::ParentHook in parent for child '"
<< pid << "': " << parentSetup.error();
os::close(pipes[1]);
// Ensure the child is killed.
::kill(pid, SIGKILL);
return Error(
"Failed to execute Subprocess::ParentHook in parent for child '" +
stringify(pid) + "': " + parentSetup.error());
}
}
// Now that we've executed the parent hooks, we can signal the child to
// continue by writing to the pipe.
char dummy;
ssize_t length;
while ((length = ::write(pipes[1], &dummy, sizeof(dummy))) == -1 &&
errno == EINTR);
os::close(pipes[1]);
if (length != sizeof(dummy)) {
// Ensure the child is killed.
::kill(pid, SIGKILL);
return Error("Failed to synchronize child process");
}
}
return pid;
}
} // namespace internal {
} // namespace process {
#endif // __PROCESS_POSIX_SUBPROCESS_HPP__
<commit_msg>Replaced ABORT with SAFE_EXIT in childhook in `subprocess_posix.hpp`.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
#ifndef __PROCESS_POSIX_SUBPROCESS_HPP__
#define __PROCESS_POSIX_SUBPROCESS_HPP__
#ifdef __linux__
#include <sys/prctl.h>
#endif // __linux__
#include <sys/types.h>
#include <string>
#include <glog/logging.h>
#include <process/subprocess.hpp>
#include <stout/check.hpp>
#include <stout/error.hpp>
#include <stout/exit.hpp>
#include <stout/foreach.hpp>
#include <stout/hashset.hpp>
#include <stout/nothing.hpp>
#include <stout/lambda.hpp>
#include <stout/none.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/try.hpp>
#include <stout/unreachable.hpp>
#include <stout/os/close.hpp>
#include <stout/os/environment.hpp>
#include <stout/os/fcntl.hpp>
#include <stout/os/signals.hpp>
#include <stout/os/strerror.hpp>
namespace process {
namespace internal {
static void close(std::initializer_list<int_fd> fds);
static void close(
const Subprocess::IO::InputFileDescriptors& stdinfds,
const Subprocess::IO::OutputFileDescriptors& stdoutfds,
const Subprocess::IO::OutputFileDescriptors& stderrfds);
inline pid_t defaultClone(const lambda::function<int()>& func)
{
pid_t pid = ::fork();
if (pid == -1) {
return -1;
} else if (pid == 0) {
// Child.
::exit(func());
UNREACHABLE();
} else {
// Parent.
return pid;
}
}
// This function will invoke `os::cloexec` on all specified file
// descriptors that are valid (i.e., not `None` and >= 0).
inline Try<Nothing> cloexec(
const InputFileDescriptors& stdinfds,
const OutputFileDescriptors& stdoutfds,
const OutputFileDescriptors& stderrfds)
{
hashset<int> fds = {
stdinfds.read,
stdinfds.write.getOrElse(-1),
stdoutfds.read.getOrElse(-1),
stdoutfds.write,
stderrfds.read.getOrElse(-1),
stderrfds.write
};
foreach (int fd, fds) {
if (fd >= 0) {
Try<Nothing> cloexec = os::cloexec(fd);
if (cloexec.isError()) {
return Error(cloexec.error());
}
}
}
return Nothing();
}
// The main entry of the child process.
//
// NOTE: This function has to be async signal safe.
inline int childMain(
const std::string& path,
char** argv,
char** envp,
const InputFileDescriptors& stdinfds,
const OutputFileDescriptors& stdoutfds,
const OutputFileDescriptors& stderrfds,
bool blocking,
int pipes[2],
const std::vector<Subprocess::ChildHook>& child_hooks)
{
// Close parent's end of the pipes.
if (stdinfds.write.isSome()) {
::close(stdinfds.write.get());
}
if (stdoutfds.read.isSome()) {
::close(stdoutfds.read.get());
}
if (stderrfds.read.isSome()) {
::close(stderrfds.read.get());
}
// Currently we will block the child's execution of the new process
// until all the parent hooks (if any) have executed.
if (blocking) {
::close(pipes[1]);
}
// Redirect I/O for stdin/stdout/stderr.
while (::dup2(stdinfds.read, STDIN_FILENO) == -1 && errno == EINTR);
while (::dup2(stdoutfds.write, STDOUT_FILENO) == -1 && errno == EINTR);
while (::dup2(stderrfds.write, STDERR_FILENO) == -1 && errno == EINTR);
// Close the copies. We need to make sure that we do not close the
// file descriptor assigned to stdin/stdout/stderr in case the
// parent has closed stdin/stdout/stderr when calling this
// function (in that case, a dup'ed file descriptor may have the
// same file descriptor number as stdin/stdout/stderr).
//
// We also need to ensure that we don't "double close" any file
// descriptors in the case where one of stdinfds.read,
// stdoutfds.write, or stdoutfds.write are equal.
if (stdinfds.read != STDIN_FILENO &&
stdinfds.read != STDOUT_FILENO &&
stdinfds.read != STDERR_FILENO) {
::close(stdinfds.read);
}
if (stdoutfds.write != STDIN_FILENO &&
stdoutfds.write != STDOUT_FILENO &&
stdoutfds.write != STDERR_FILENO &&
stdoutfds.write != stdinfds.read) {
::close(stdoutfds.write);
}
if (stderrfds.write != STDIN_FILENO &&
stderrfds.write != STDOUT_FILENO &&
stderrfds.write != STDERR_FILENO &&
stderrfds.write != stdinfds.read &&
stderrfds.write != stdoutfds.write) {
::close(stderrfds.write);
}
if (blocking) {
// Do a blocking read on the pipe until the parent signals us to
// continue.
char dummy;
ssize_t length;
while ((length = ::read(pipes[0], &dummy, sizeof(dummy))) == -1 &&
errno == EINTR);
if (length != sizeof(dummy)) {
ABORT("Failed to synchronize with parent");
}
// Now close the pipe as we don't need it anymore.
::close(pipes[0]);
}
// Run the child hooks.
foreach (const Subprocess::ChildHook& hook, child_hooks) {
Try<Nothing> callback = hook();
// If the callback failed, we should abort execution.
if (callback.isError()) {
ABORT("Failed to execute Subprocess::ChildHook: " + callback.error());
}
}
os::execvpe(path.c_str(), argv, envp);
SAFE_EXIT(
errno, "Failed to os::execvpe on path '%s': %d", path.c_str(), errno);
}
inline Try<pid_t> cloneChild(
const std::string& path,
std::vector<std::string> argv,
const Option<std::map<std::string, std::string>>& environment,
const Option<lambda::function<
pid_t(const lambda::function<int()>&)>>& _clone,
const std::vector<Subprocess::ParentHook>& parent_hooks,
const std::vector<Subprocess::ChildHook>& child_hooks,
const InputFileDescriptors stdinfds,
const OutputFileDescriptors stdoutfds,
const OutputFileDescriptors stderrfds)
{
// The real arguments that will be passed to 'os::execvpe'. We need
// to construct them here before doing the clone as it might not be
// async signal safe to perform the memory allocation.
char** _argv = new char*[argv.size() + 1];
for (size_t i = 0; i < argv.size(); i++) {
_argv[i] = (char*) argv[i].c_str();
}
_argv[argv.size()] = nullptr;
// Like above, we need to construct the environment that we'll pass
// to 'os::execvpe' as it might not be async-safe to perform the
// memory allocations.
char** envp = os::raw::environment();
if (environment.isSome()) {
// NOTE: We add 1 to the size for a `nullptr` terminator.
envp = new char*[environment.get().size() + 1];
size_t index = 0;
foreachpair (
const std::string& key,
const std::string& value, environment.get()) {
std::string entry = key + "=" + value;
envp[index] = new char[entry.size() + 1];
strncpy(envp[index], entry.c_str(), entry.size() + 1);
++index;
}
envp[index] = nullptr;
}
// Determine the function to clone the child process. If the user
// does not specify the clone function, we will use the default.
lambda::function<pid_t(const lambda::function<int()>&)> clone =
(_clone.isSome() ? _clone.get() : defaultClone);
// Currently we will block the child's execution of the new process
// until all the `parent_hooks` (if any) have executed.
std::array<int, 2> pipes;
const bool blocking = !parent_hooks.empty();
if (blocking) {
// We assume this should not fail under reasonable conditions so we
// use CHECK.
Try<std::array<int, 2>> pipe = os::pipe();
CHECK_SOME(pipe);
pipes = pipe.get();
}
// Now, clone the child process.
pid_t pid = clone(lambda::bind(
&childMain,
path,
_argv,
envp,
stdinfds,
stdoutfds,
stderrfds,
blocking,
pipes.data(),
child_hooks));
delete[] _argv;
// Need to delete 'envp' if we had environment variables passed to
// us and we needed to allocate the space.
if (environment.isSome()) {
CHECK_NE(os::raw::environment(), envp);
// We ignore the last 'envp' entry since it is nullptr.
for (size_t index = 0; index < environment->size(); index++) {
delete[] envp[index];
}
delete[] envp;
}
if (pid == -1) {
// Save the errno as 'close' below might overwrite it.
ErrnoError error("Failed to clone");
internal::close(stdinfds, stdoutfds, stderrfds);
if (blocking) {
os::close(pipes[0]);
os::close(pipes[1]);
}
return error;
}
// Close the child-ends of the file descriptors that are created by
// this function.
internal::close({stdinfds.read, stdoutfds.write, stderrfds.write});
if (blocking) {
os::close(pipes[0]);
// Run the parent hooks.
foreach (const Subprocess::ParentHook& hook, parent_hooks) {
Try<Nothing> parentSetup = hook.parent_setup(pid);
// If the hook callback fails, we shouldn't proceed with the
// execution and hence the child process should be killed.
if (parentSetup.isError()) {
LOG(WARNING)
<< "Failed to execute Subprocess::ParentHook in parent for child '"
<< pid << "': " << parentSetup.error();
os::close(pipes[1]);
// Ensure the child is killed.
::kill(pid, SIGKILL);
return Error(
"Failed to execute Subprocess::ParentHook in parent for child '" +
stringify(pid) + "': " + parentSetup.error());
}
}
// Now that we've executed the parent hooks, we can signal the child to
// continue by writing to the pipe.
char dummy;
ssize_t length;
while ((length = ::write(pipes[1], &dummy, sizeof(dummy))) == -1 &&
errno == EINTR);
os::close(pipes[1]);
if (length != sizeof(dummy)) {
// Ensure the child is killed.
::kill(pid, SIGKILL);
return Error("Failed to synchronize child process");
}
}
return pid;
}
} // namespace internal {
} // namespace process {
#endif // __PROCESS_POSIX_SUBPROCESS_HPP__
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkThinPlateSplineMeshWarp.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to Tim Hutton (MINORI Project, Dental and Medical
Informatics, Eastman Dental Institute, London, UK) who
developed and contributed this class.
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkThinPlateSplineMeshWarp.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkThinPlateSplineMeshWarp* vtkThinPlateSplineMeshWarp::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkThinPlateSplineMeshWarp");
if(ret)
{
return (vtkThinPlateSplineMeshWarp*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkThinPlateSplineMeshWarp;
}
vtkThinPlateSplineMeshWarp::vtkThinPlateSplineMeshWarp()
{
this->SourceLandmarks=NULL;
this->TargetLandmarks=NULL;
this->Sigma=1.0;
}
vtkThinPlateSplineMeshWarp::~vtkThinPlateSplineMeshWarp()
{
if (this->SourceLandmarks)
{
this->SourceLandmarks->Delete();
}
if (this->TargetLandmarks)
{
this->TargetLandmarks->Delete();
}
}
//------------------------------------------------------------------------
// some dull matrix things
inline double** NewMatrix(int x,int y)
{
double** m = new double*[x];
for(int i=0;i<x;i++)
{
m[i] = new double[y];
}
return m;
}
inline void DeleteMatrix(double** m,int x,int y)
{
for(int i=0;i<x;i++)
{
delete [] m[i]; // OK, we don't actually need y
}
delete [] m;
}
inline void FillMatrixWithZeros(double** m,int x,int y)
{
int i,j;
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
m[i][j]=0.0;
}
}
}
inline void TransposeMatrix(double*** m,int x,int y)
{
double swap,*a,*b;
int r,c;
if(x==y)
{
// matrix is square, can just swap values over the diagonal (fast)
for(c=1;c<x;c++)
{
for(r=0;r<c;r++)
{
a = &((*m)[r][c]); // (what a mess)
b = &((*m)[c][r]);
swap=*a;
*a=*b;
*b=swap;
}
}
}
else
{
// matrix is not square, must reallocate memory first
double **result = NewMatrix(y,x);
int r,c;
for(r=0;r<y;r++)
{
for(c=0;c<x;c++)
{
result[r][c] = (*m)[c][r];
}
}
// plug in the replacement matrix
DeleteMatrix(*m,x,y);
*m=result;
}
}
inline void MatrixMultiply(double** a,double** b,double** c,int ar,int ac,
int br,int bc)
{
if(ac!=br)
{
return; // ac must equal br otherwise we can't proceed
}
// c must have size ar*bc (we assume this)
const int cr=ar,cc=bc;
int row,col,i;
for(row=0;row<cr;row++)
{
for(col=0;col<cc;col++)
{
c[row][col]=0.0;
for(i=0;i<ac;i++)
{
c[row][col] += a[row][i]*b[i][col];
}
}
}
}
//------------------------------------------------------------------------
// a teeny-tiny but rather crucial function
inline float U(float x,float sigma) {
if(x==0.0F)
{
return x;
}
else
{
return (x/sigma)*(x/sigma)*log(x/sigma);
}
}
//------------------------------------------------------------------------
void vtkThinPlateSplineMeshWarp::Execute()
{
if(this->SourceLandmarks==NULL)
{
vtkWarningMacro(<<"No source landmarks - output will be empty");
return;
}
if(this->TargetLandmarks==NULL)
{
vtkWarningMacro(<<"No target landmarks - output will be empty");
return;
}
// Notation and inspiration from:
// Fred L. Bookstein (1997) "Shape and the Information in Medical Images:
// A Decade of the Morphometric Synthesis" Computer Vision and Image
// Understanding 66(2):97-118
// and online work published by Tim Cootes (http://www.wiau.man.ac.uk/~bim)
const int N = this->SourceLandmarks->GetNumberOfPoints();
const int D = 3; // dimensions
// the input matrices
double **L = NewMatrix(N+D+1,N+D+1);
double **X = NewMatrix(N+D+1,D);
// the output weights matrix
double **W = NewMatrix(N+D+1,D); // will be transposed later, mind
// build L
FillMatrixWithZeros(L,N+D+1,N+D+1); // will leave the bottom-right corner with zeros
int r,c;
float p[3],p2[3];
for(r=0;r<N;r++)
{
this->SourceLandmarks->GetPoint(r,p);
// fill in the top-right corner of L (Q)
L[r][N] = 1.0;
L[r][N+1] = p[0];
L[r][N+2] = p[1];
L[r][N+3] = p[2];
// fill in the bottom-left corner of L (Q transposed)
L[N][r] = 1.0;
L[N+1][r] = p[0];
L[N+2][r] = p[1];
L[N+3][r] = p[2];
// fill in the top-left corner of L (K)
for(c=0;c<N;c++)
{
this->SourceLandmarks->GetPoint(c,p2);
L[r][c] = U(sqrt(vtkMath::Distance2BetweenPoints(p,p2)),this->Sigma);
}
}
// build X
FillMatrixWithZeros(X,N+D+1,D);
for(r=0;r<N;r++)
{
this->TargetLandmarks->GetPoint(r,p);
X[r][0] = p[0];
X[r][1] = p[1];
X[r][2] = p[2];
}
// solve for W
double **LI = NewMatrix(N+D+1,N+D+1);
vtkMath::InvertMatrix(L,LI,N+D+1);
MatrixMultiply(LI,X,W,N+D+1,N+D+1,N+D+1,D);
TransposeMatrix(&W,N+D+1,D);
//W = Transpose(Inverse(L)*X);
// much easier if we have a decent matrix class, no?
// resample input based on transform given by x' = Wu(x)
vtkPolyData *input = this->GetInput();
vtkPolyData *output = this->GetOutput();
// copy the topology from the input mesh, as well as the point and cell
// attributes
output->CopyStructure(input);
output->GetPointData()->PassData(input->GetPointData());
output->GetCellData()->PassData(input->GetCellData());
// create a new points structure for the output mesh
vtkPoints *outputPoints = vtkPoints::New();
output->SetPoints(outputPoints);
outputPoints->SetNumberOfPoints(input->GetPoints()->GetNumberOfPoints());
double **SOURCE = NewMatrix(D,1); // we know the target, we want the source
double **UDX = NewMatrix(N+D+1,1);
float *point;
for(int j=0;j<input->GetPoints()->GetNumberOfPoints();j++)
{
point = input->GetPoints()->GetPoint(j);
// build the N+D+1*1 vector UDX (Ud(x))
for(int i=0;i<N;i++)
{
this->SourceLandmarks->GetPoint(i,p);
UDX[i][0] = U(sqrt(vtkMath::Distance2BetweenPoints(point,p)),this->Sigma);
}
UDX[N][0] = 1.0;
UDX[N+1][0] = point[0];
UDX[N+2][0] = point[1];
UDX[N+3][0] = point[2];
// find the source point
MatrixMultiply(W,UDX,SOURCE,D,N+D+1,N+D+1,1);
//SOURCE = W*UDX; // would be so effortless...
output->GetPoints()->SetPoint(j,SOURCE[0][0],SOURCE[1][0],SOURCE[2][0]);
}
DeleteMatrix(UDX,N+D+1,1);
DeleteMatrix(SOURCE,D,1);
DeleteMatrix(LI,N+D+1,N+D+1);
DeleteMatrix(L,N+D+1,N+D+1);
DeleteMatrix(X,N+D+1,D);
DeleteMatrix(W,D,N+D+1); // W has been transposed since it was created
}
void vtkThinPlateSplineMeshWarp::PrintSelf(ostream& os, vtkIndent indent)
{
vtkPolyDataToPolyDataFilter::PrintSelf(os,indent);
os << indent << "Sigma:" << this->Sigma << "\n";
os << indent << "Source Landmarks: " << this->SourceLandmarks << "\n";
os << indent << "Target Landmarks: " << this->TargetLandmarks << "\n";
}
<commit_msg>ERR: memory leak.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkThinPlateSplineMeshWarp.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to Tim Hutton (MINORI Project, Dental and Medical
Informatics, Eastman Dental Institute, London, UK) who
developed and contributed this class.
Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkThinPlateSplineMeshWarp.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkThinPlateSplineMeshWarp* vtkThinPlateSplineMeshWarp::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkThinPlateSplineMeshWarp");
if(ret)
{
return (vtkThinPlateSplineMeshWarp*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkThinPlateSplineMeshWarp;
}
vtkThinPlateSplineMeshWarp::vtkThinPlateSplineMeshWarp()
{
this->SourceLandmarks=NULL;
this->TargetLandmarks=NULL;
this->Sigma=1.0;
}
vtkThinPlateSplineMeshWarp::~vtkThinPlateSplineMeshWarp()
{
if (this->SourceLandmarks)
{
this->SourceLandmarks->Delete();
}
if (this->TargetLandmarks)
{
this->TargetLandmarks->Delete();
}
}
//------------------------------------------------------------------------
// some dull matrix things
inline double** NewMatrix(int x,int y)
{
double** m = new double*[x];
for(int i=0;i<x;i++)
{
m[i] = new double[y];
}
return m;
}
inline void DeleteMatrix(double** m,int x,int y)
{
for(int i=0;i<x;i++)
{
delete [] m[i]; // OK, we don't actually need y
}
delete [] m;
}
inline void FillMatrixWithZeros(double** m,int x,int y)
{
int i,j;
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
m[i][j]=0.0;
}
}
}
inline void TransposeMatrix(double*** m,int x,int y)
{
double swap,*a,*b;
int r,c;
if(x==y)
{
// matrix is square, can just swap values over the diagonal (fast)
for(c=1;c<x;c++)
{
for(r=0;r<c;r++)
{
a = &((*m)[r][c]); // (what a mess)
b = &((*m)[c][r]);
swap=*a;
*a=*b;
*b=swap;
}
}
}
else
{
// matrix is not square, must reallocate memory first
double **result = NewMatrix(y,x);
int r,c;
for(r=0;r<y;r++)
{
for(c=0;c<x;c++)
{
result[r][c] = (*m)[c][r];
}
}
// plug in the replacement matrix
DeleteMatrix(*m,x,y);
*m=result;
}
}
inline void MatrixMultiply(double** a,double** b,double** c,int ar,int ac,
int br,int bc)
{
if(ac!=br)
{
return; // ac must equal br otherwise we can't proceed
}
// c must have size ar*bc (we assume this)
const int cr=ar,cc=bc;
int row,col,i;
for(row=0;row<cr;row++)
{
for(col=0;col<cc;col++)
{
c[row][col]=0.0;
for(i=0;i<ac;i++)
{
c[row][col] += a[row][i]*b[i][col];
}
}
}
}
//------------------------------------------------------------------------
// a teeny-tiny but rather crucial function
inline float U(float x,float sigma) {
if(x==0.0F)
{
return x;
}
else
{
return (x/sigma)*(x/sigma)*log(x/sigma);
}
}
//------------------------------------------------------------------------
void vtkThinPlateSplineMeshWarp::Execute()
{
if(this->SourceLandmarks==NULL)
{
vtkWarningMacro(<<"No source landmarks - output will be empty");
return;
}
if(this->TargetLandmarks==NULL)
{
vtkWarningMacro(<<"No target landmarks - output will be empty");
return;
}
// Notation and inspiration from:
// Fred L. Bookstein (1997) "Shape and the Information in Medical Images:
// A Decade of the Morphometric Synthesis" Computer Vision and Image
// Understanding 66(2):97-118
// and online work published by Tim Cootes (http://www.wiau.man.ac.uk/~bim)
const int N = this->SourceLandmarks->GetNumberOfPoints();
const int D = 3; // dimensions
// the input matrices
double **L = NewMatrix(N+D+1,N+D+1);
double **X = NewMatrix(N+D+1,D);
// the output weights matrix
double **W = NewMatrix(N+D+1,D); // will be transposed later, mind
// build L
FillMatrixWithZeros(L,N+D+1,N+D+1); // will leave the bottom-right corner with zeros
int r,c;
float p[3],p2[3];
for(r=0;r<N;r++)
{
this->SourceLandmarks->GetPoint(r,p);
// fill in the top-right corner of L (Q)
L[r][N] = 1.0;
L[r][N+1] = p[0];
L[r][N+2] = p[1];
L[r][N+3] = p[2];
// fill in the bottom-left corner of L (Q transposed)
L[N][r] = 1.0;
L[N+1][r] = p[0];
L[N+2][r] = p[1];
L[N+3][r] = p[2];
// fill in the top-left corner of L (K)
for(c=0;c<N;c++)
{
this->SourceLandmarks->GetPoint(c,p2);
L[r][c] = U(sqrt(vtkMath::Distance2BetweenPoints(p,p2)),this->Sigma);
}
}
// build X
FillMatrixWithZeros(X,N+D+1,D);
for(r=0;r<N;r++)
{
this->TargetLandmarks->GetPoint(r,p);
X[r][0] = p[0];
X[r][1] = p[1];
X[r][2] = p[2];
}
// solve for W
double **LI = NewMatrix(N+D+1,N+D+1);
vtkMath::InvertMatrix(L,LI,N+D+1);
MatrixMultiply(LI,X,W,N+D+1,N+D+1,N+D+1,D);
TransposeMatrix(&W,N+D+1,D);
//W = Transpose(Inverse(L)*X);
// much easier if we have a decent matrix class, no?
// resample input based on transform given by x' = Wu(x)
vtkPolyData *input = this->GetInput();
vtkPolyData *output = this->GetOutput();
// copy the topology from the input mesh, as well as the point and cell
// attributes
output->CopyStructure(input);
output->GetPointData()->PassData(input->GetPointData());
output->GetCellData()->PassData(input->GetCellData());
// create a new points structure for the output mesh
vtkPoints *outputPoints = vtkPoints::New();
output->SetPoints(outputPoints);
outputPoints->Delete();
outputPoints->SetNumberOfPoints(input->GetPoints()->GetNumberOfPoints());
double **SOURCE = NewMatrix(D,1); // we know the target, we want the source
double **UDX = NewMatrix(N+D+1,1);
float *point;
for(int j=0;j<input->GetPoints()->GetNumberOfPoints();j++)
{
point = input->GetPoints()->GetPoint(j);
// build the N+D+1*1 vector UDX (Ud(x))
for(int i=0;i<N;i++)
{
this->SourceLandmarks->GetPoint(i,p);
UDX[i][0] = U(sqrt(vtkMath::Distance2BetweenPoints(point,p)),this->Sigma);
}
UDX[N][0] = 1.0;
UDX[N+1][0] = point[0];
UDX[N+2][0] = point[1];
UDX[N+3][0] = point[2];
// find the source point
MatrixMultiply(W,UDX,SOURCE,D,N+D+1,N+D+1,1);
//SOURCE = W*UDX; // would be so effortless...
output->GetPoints()->SetPoint(j,SOURCE[0][0],SOURCE[1][0],SOURCE[2][0]);
}
DeleteMatrix(UDX,N+D+1,1);
DeleteMatrix(SOURCE,D,1);
DeleteMatrix(LI,N+D+1,N+D+1);
DeleteMatrix(L,N+D+1,N+D+1);
DeleteMatrix(X,N+D+1,D);
DeleteMatrix(W,D,N+D+1); // W has been transposed since it was created
}
void vtkThinPlateSplineMeshWarp::PrintSelf(ostream& os, vtkIndent indent)
{
vtkPolyDataToPolyDataFilter::PrintSelf(os,indent);
os << indent << "Sigma:" << this->Sigma << "\n";
os << indent << "Source Landmarks: " << this->SourceLandmarks << "\n";
os << indent << "Target Landmarks: " << this->TargetLandmarks << "\n";
}
<|endoftext|>
|
<commit_before>
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrContextFactory.h"
#include "gl/GLTestContext.h"
#if SK_ANGLE
#include "gl/angle/GLTestContext_angle.h"
#endif
#include "gl/command_buffer/GLTestContext_command_buffer.h"
#include "gl/debug/DebugGLTestContext.h"
#ifdef SK_VULKAN
#include "vk/VkTestContext.h"
#endif
#ifdef SK_METAL
#include "mtl/MtlTestContext.h"
#endif
#include "gl/null/NullGLTestContext.h"
#include "gl/GrGLGpu.h"
#include "mock/MockTestContext.h"
#include "GrCaps.h"
#if defined(SK_BUILD_FOR_WIN32) && defined(SK_ENABLE_DISCRETE_GPU)
extern "C" {
// NVIDIA documents that the presence and value of this symbol programmatically enable the high
// performance GPU in laptops with switchable graphics.
// https://docs.nvidia.com/gameworks/content/technologies/desktop/optimus.htm
// From testing, including this symbol, even if it is set to 0, we still get the NVIDIA GPU.
_declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
// AMD has a similar mechanism, although I don't have an AMD laptop, so this is untested.
// https://community.amd.com/thread/169965
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
}
#endif
namespace sk_gpu_test {
GrContextFactory::GrContextFactory() { }
GrContextFactory::GrContextFactory(const GrContextOptions& opts)
: fGlobalOptions(opts) {
}
GrContextFactory::~GrContextFactory() {
this->destroyContexts();
}
void GrContextFactory::destroyContexts() {
for (Context& context : fContexts) {
SkScopeExit restore(nullptr);
if (context.fTestContext) {
restore = context.fTestContext->makeCurrentAndAutoRestore();
}
if (!context.fGrContext->unique()) {
context.fGrContext->releaseResourcesAndAbandonContext();
context.fAbandoned = true;
}
context.fGrContext->unref();
delete context.fTestContext;
}
fContexts.reset();
}
void GrContextFactory::abandonContexts() {
for (Context& context : fContexts) {
if (!context.fAbandoned) {
if (context.fTestContext) {
auto restore = context.fTestContext->makeCurrentAndAutoRestore();
context.fTestContext->testAbandon();
delete(context.fTestContext);
context.fTestContext = nullptr;
}
context.fGrContext->abandonContext();
context.fAbandoned = true;
}
}
}
void GrContextFactory::releaseResourcesAndAbandonContexts() {
for (Context& context : fContexts) {
SkScopeExit restore(nullptr);
if (!context.fAbandoned) {
if (context.fTestContext) {
restore = context.fTestContext->makeCurrentAndAutoRestore();
}
context.fGrContext->releaseResourcesAndAbandonContext();
context.fAbandoned = true;
if (context.fTestContext) {
delete context.fTestContext;
context.fTestContext = nullptr;
}
}
}
}
GrContext* GrContextFactory::get(ContextType type, ContextOverrides overrides) {
return this->getContextInfo(type, overrides).grContext();
}
ContextInfo GrContextFactory::getContextInfoInternal(ContextType type, ContextOverrides overrides,
GrContext* shareContext, uint32_t shareIndex) {
// (shareIndex != 0) -> (shareContext != nullptr)
SkASSERT((shareIndex == 0) || (shareContext != nullptr));
for (int i = 0; i < fContexts.count(); ++i) {
Context& context = fContexts[i];
if (context.fType == type &&
context.fOverrides == overrides &&
context.fShareContext == shareContext &&
context.fShareIndex == shareIndex &&
!context.fAbandoned) {
context.fTestContext->makeCurrent();
return ContextInfo(context.fType, context.fTestContext, context.fGrContext,
context.fOptions);
}
}
// If we're trying to create a context in a share group, find the master context
Context* masterContext = nullptr;
if (shareContext) {
for (int i = 0; i < fContexts.count(); ++i) {
if (!fContexts[i].fAbandoned && fContexts[i].fGrContext == shareContext) {
masterContext = &fContexts[i];
break;
}
}
SkASSERT(masterContext && masterContext->fType == type);
}
std::unique_ptr<TestContext> testCtx;
GrBackend backend = ContextTypeBackend(type);
switch (backend) {
case kOpenGL_GrBackend: {
GLTestContext* glShareContext = masterContext
? static_cast<GLTestContext*>(masterContext->fTestContext) : nullptr;
GLTestContext* glCtx;
switch (type) {
case kGL_ContextType:
glCtx = CreatePlatformGLTestContext(kGL_GrGLStandard, glShareContext);
break;
case kGLES_ContextType:
glCtx = CreatePlatformGLTestContext(kGLES_GrGLStandard, glShareContext);
break;
#if SK_ANGLE
case kANGLE_D3D9_ES2_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kD3D9, ANGLEContextVersion::kES2,
glShareContext).release();
break;
case kANGLE_D3D11_ES2_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kD3D11, ANGLEContextVersion::kES2,
glShareContext).release();
break;
case kANGLE_D3D11_ES3_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kD3D11, ANGLEContextVersion::kES3,
glShareContext).release();
break;
case kANGLE_GL_ES2_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kOpenGL, ANGLEContextVersion::kES2,
glShareContext).release();
break;
case kANGLE_GL_ES3_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kOpenGL, ANGLEContextVersion::kES3,
glShareContext).release();
break;
#endif
#ifndef SK_NO_COMMAND_BUFFER
case kCommandBuffer_ContextType:
glCtx = CommandBufferGLTestContext::Create(glShareContext);
break;
#endif
case kNullGL_ContextType:
glCtx = CreateNullGLTestContext(
ContextOverrides::kRequireNVPRSupport & overrides, glShareContext);
break;
case kDebugGL_ContextType:
glCtx = CreateDebugGLTestContext(glShareContext);
break;
default:
return ContextInfo();
}
if (!glCtx) {
return ContextInfo();
}
testCtx.reset(glCtx);
break;
}
#ifdef SK_VULKAN
case kVulkan_GrBackend: {
VkTestContext* vkSharedContext = masterContext
? static_cast<VkTestContext*>(masterContext->fTestContext) : nullptr;
SkASSERT(kVulkan_ContextType == type);
if (ContextOverrides::kRequireNVPRSupport & overrides) {
return ContextInfo();
}
testCtx.reset(CreatePlatformVkTestContext(vkSharedContext));
if (!testCtx) {
return ContextInfo();
}
// There is some bug (either in Skia or the NV Vulkan driver) where VkDevice
// destruction will hang occaisonally. For some reason having an existing GL
// context fixes this.
if (!fSentinelGLContext) {
fSentinelGLContext.reset(CreatePlatformGLTestContext(kGL_GrGLStandard));
if (!fSentinelGLContext) {
fSentinelGLContext.reset(CreatePlatformGLTestContext(kGLES_GrGLStandard));
}
}
break;
}
#endif
#ifdef SK_METAL
case kMetal_GrBackend: {
SkASSERT(!masterContext);
testCtx.reset(CreatePlatformMtlTestContext(nullptr));
if (!testCtx) {
return ContextInfo();
}
break;
}
#endif
case kMock_GrBackend: {
TestContext* sharedContext = masterContext ? masterContext->fTestContext : nullptr;
SkASSERT(kMock_ContextType == type);
if (ContextOverrides::kRequireNVPRSupport & overrides) {
return ContextInfo();
}
testCtx.reset(CreateMockTestContext(sharedContext));
if (!testCtx) {
return ContextInfo();
}
break;
}
default:
return ContextInfo();
}
SkASSERT(testCtx && testCtx->backend() == backend);
GrContextOptions grOptions = fGlobalOptions;
if (ContextOverrides::kDisableNVPR & overrides) {
grOptions.fSuppressPathRendering = true;
}
if (ContextOverrides::kAllowSRGBWithoutDecodeControl & overrides) {
grOptions.fRequireDecodeDisableForSRGB = false;
}
if (ContextOverrides::kAvoidStencilBuffers & overrides) {
grOptions.fAvoidStencilBuffers = true;
}
sk_sp<GrContext> grCtx;
{
auto restore = testCtx->makeCurrentAndAutoRestore();
grCtx = testCtx->makeGrContext(grOptions);
}
if (!grCtx.get()) {
return ContextInfo();
}
if (ContextOverrides::kRequireNVPRSupport & overrides) {
if (!grCtx->caps()->shaderCaps()->pathRenderingSupport()) {
return ContextInfo();
}
}
if (ContextOverrides::kRequireSRGBSupport & overrides) {
if (!grCtx->caps()->srgbSupport()) {
return ContextInfo();
}
}
Context& context = fContexts.push_back();
context.fBackend = backend;
context.fTestContext = testCtx.release();
context.fGrContext = SkRef(grCtx.get());
context.fType = type;
context.fOverrides = overrides;
context.fAbandoned = false;
context.fShareContext = shareContext;
context.fShareIndex = shareIndex;
context.fOptions = grOptions;
context.fTestContext->makeCurrent();
return ContextInfo(context.fType, context.fTestContext, context.fGrContext, context.fOptions);
}
ContextInfo GrContextFactory::getContextInfo(ContextType type, ContextOverrides overrides) {
return this->getContextInfoInternal(type, overrides, nullptr, 0);
}
ContextInfo GrContextFactory::getSharedContextInfo(GrContext* shareContext, uint32_t shareIndex) {
SkASSERT(shareContext);
for (int i = 0; i < fContexts.count(); ++i) {
if (!fContexts[i].fAbandoned && fContexts[i].fGrContext == shareContext) {
return this->getContextInfoInternal(fContexts[i].fType, fContexts[i].fOverrides,
shareContext, shareIndex);
}
}
return ContextInfo();
}
} // namespace sk_gpu_test
<commit_msg>Delete Gr testing contexts in reverse order<commit_after>
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrContextFactory.h"
#include "gl/GLTestContext.h"
#if SK_ANGLE
#include "gl/angle/GLTestContext_angle.h"
#endif
#include "gl/command_buffer/GLTestContext_command_buffer.h"
#include "gl/debug/DebugGLTestContext.h"
#ifdef SK_VULKAN
#include "vk/VkTestContext.h"
#endif
#ifdef SK_METAL
#include "mtl/MtlTestContext.h"
#endif
#include "gl/null/NullGLTestContext.h"
#include "gl/GrGLGpu.h"
#include "mock/MockTestContext.h"
#include "GrCaps.h"
#if defined(SK_BUILD_FOR_WIN32) && defined(SK_ENABLE_DISCRETE_GPU)
extern "C" {
// NVIDIA documents that the presence and value of this symbol programmatically enable the high
// performance GPU in laptops with switchable graphics.
// https://docs.nvidia.com/gameworks/content/technologies/desktop/optimus.htm
// From testing, including this symbol, even if it is set to 0, we still get the NVIDIA GPU.
_declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
// AMD has a similar mechanism, although I don't have an AMD laptop, so this is untested.
// https://community.amd.com/thread/169965
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
}
#endif
namespace sk_gpu_test {
GrContextFactory::GrContextFactory() { }
GrContextFactory::GrContextFactory(const GrContextOptions& opts)
: fGlobalOptions(opts) {
}
GrContextFactory::~GrContextFactory() {
this->destroyContexts();
}
void GrContextFactory::destroyContexts() {
// We must delete the test contexts in reverse order so that any child context is finished and
// deleted before a parent context. This relies on the fact that when we make a new context we
// append it to the end of fContexts array.
// TODO: Look into keeping a dependency dag for contexts and deletion order
for (int i = fContexts.count() - 1; i >= 0; --i) {
Context& context = fContexts[i];
SkScopeExit restore(nullptr);
if (context.fTestContext) {
restore = context.fTestContext->makeCurrentAndAutoRestore();
}
if (!context.fGrContext->unique()) {
context.fGrContext->releaseResourcesAndAbandonContext();
context.fAbandoned = true;
}
context.fGrContext->unref();
delete context.fTestContext;
}
fContexts.reset();
}
void GrContextFactory::abandonContexts() {
// We must abandon the test contexts in reverse order so that any child context is finished and
// abandoned before a parent context. This relies on the fact that when we make a new context we
// append it to the end of fContexts array.
// TODO: Look into keeping a dependency dag for contexts and deletion order
for (int i = fContexts.count() - 1; i >= 0; --i) {
Context& context = fContexts[i];
if (!context.fAbandoned) {
if (context.fTestContext) {
auto restore = context.fTestContext->makeCurrentAndAutoRestore();
context.fTestContext->testAbandon();
delete(context.fTestContext);
context.fTestContext = nullptr;
}
context.fGrContext->abandonContext();
context.fAbandoned = true;
}
}
}
void GrContextFactory::releaseResourcesAndAbandonContexts() {
// We must abandon the test contexts in reverse order so that any child context is finished and
// abandoned before a parent context. This relies on the fact that when we make a new context we
// append it to the end of fContexts array.
// TODO: Look into keeping a dependency dag for contexts and deletion order
for (int i = fContexts.count() - 1; i >= 0; --i) {
Context& context = fContexts[i];
SkScopeExit restore(nullptr);
if (!context.fAbandoned) {
if (context.fTestContext) {
restore = context.fTestContext->makeCurrentAndAutoRestore();
}
context.fGrContext->releaseResourcesAndAbandonContext();
context.fAbandoned = true;
if (context.fTestContext) {
delete context.fTestContext;
context.fTestContext = nullptr;
}
}
}
}
GrContext* GrContextFactory::get(ContextType type, ContextOverrides overrides) {
return this->getContextInfo(type, overrides).grContext();
}
ContextInfo GrContextFactory::getContextInfoInternal(ContextType type, ContextOverrides overrides,
GrContext* shareContext, uint32_t shareIndex) {
// (shareIndex != 0) -> (shareContext != nullptr)
SkASSERT((shareIndex == 0) || (shareContext != nullptr));
for (int i = 0; i < fContexts.count(); ++i) {
Context& context = fContexts[i];
if (context.fType == type &&
context.fOverrides == overrides &&
context.fShareContext == shareContext &&
context.fShareIndex == shareIndex &&
!context.fAbandoned) {
context.fTestContext->makeCurrent();
return ContextInfo(context.fType, context.fTestContext, context.fGrContext,
context.fOptions);
}
}
// If we're trying to create a context in a share group, find the master context
Context* masterContext = nullptr;
if (shareContext) {
for (int i = 0; i < fContexts.count(); ++i) {
if (!fContexts[i].fAbandoned && fContexts[i].fGrContext == shareContext) {
masterContext = &fContexts[i];
break;
}
}
SkASSERT(masterContext && masterContext->fType == type);
}
std::unique_ptr<TestContext> testCtx;
GrBackend backend = ContextTypeBackend(type);
switch (backend) {
case kOpenGL_GrBackend: {
GLTestContext* glShareContext = masterContext
? static_cast<GLTestContext*>(masterContext->fTestContext) : nullptr;
GLTestContext* glCtx;
switch (type) {
case kGL_ContextType:
glCtx = CreatePlatformGLTestContext(kGL_GrGLStandard, glShareContext);
break;
case kGLES_ContextType:
glCtx = CreatePlatformGLTestContext(kGLES_GrGLStandard, glShareContext);
break;
#if SK_ANGLE
case kANGLE_D3D9_ES2_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kD3D9, ANGLEContextVersion::kES2,
glShareContext).release();
break;
case kANGLE_D3D11_ES2_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kD3D11, ANGLEContextVersion::kES2,
glShareContext).release();
break;
case kANGLE_D3D11_ES3_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kD3D11, ANGLEContextVersion::kES3,
glShareContext).release();
break;
case kANGLE_GL_ES2_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kOpenGL, ANGLEContextVersion::kES2,
glShareContext).release();
break;
case kANGLE_GL_ES3_ContextType:
glCtx = MakeANGLETestContext(ANGLEBackend::kOpenGL, ANGLEContextVersion::kES3,
glShareContext).release();
break;
#endif
#ifndef SK_NO_COMMAND_BUFFER
case kCommandBuffer_ContextType:
glCtx = CommandBufferGLTestContext::Create(glShareContext);
break;
#endif
case kNullGL_ContextType:
glCtx = CreateNullGLTestContext(
ContextOverrides::kRequireNVPRSupport & overrides, glShareContext);
break;
case kDebugGL_ContextType:
glCtx = CreateDebugGLTestContext(glShareContext);
break;
default:
return ContextInfo();
}
if (!glCtx) {
return ContextInfo();
}
testCtx.reset(glCtx);
break;
}
#ifdef SK_VULKAN
case kVulkan_GrBackend: {
VkTestContext* vkSharedContext = masterContext
? static_cast<VkTestContext*>(masterContext->fTestContext) : nullptr;
SkASSERT(kVulkan_ContextType == type);
if (ContextOverrides::kRequireNVPRSupport & overrides) {
return ContextInfo();
}
testCtx.reset(CreatePlatformVkTestContext(vkSharedContext));
if (!testCtx) {
return ContextInfo();
}
// There is some bug (either in Skia or the NV Vulkan driver) where VkDevice
// destruction will hang occaisonally. For some reason having an existing GL
// context fixes this.
if (!fSentinelGLContext) {
fSentinelGLContext.reset(CreatePlatformGLTestContext(kGL_GrGLStandard));
if (!fSentinelGLContext) {
fSentinelGLContext.reset(CreatePlatformGLTestContext(kGLES_GrGLStandard));
}
}
break;
}
#endif
#ifdef SK_METAL
case kMetal_GrBackend: {
SkASSERT(!masterContext);
testCtx.reset(CreatePlatformMtlTestContext(nullptr));
if (!testCtx) {
return ContextInfo();
}
break;
}
#endif
case kMock_GrBackend: {
TestContext* sharedContext = masterContext ? masterContext->fTestContext : nullptr;
SkASSERT(kMock_ContextType == type);
if (ContextOverrides::kRequireNVPRSupport & overrides) {
return ContextInfo();
}
testCtx.reset(CreateMockTestContext(sharedContext));
if (!testCtx) {
return ContextInfo();
}
break;
}
default:
return ContextInfo();
}
SkASSERT(testCtx && testCtx->backend() == backend);
GrContextOptions grOptions = fGlobalOptions;
if (ContextOverrides::kDisableNVPR & overrides) {
grOptions.fSuppressPathRendering = true;
}
if (ContextOverrides::kAllowSRGBWithoutDecodeControl & overrides) {
grOptions.fRequireDecodeDisableForSRGB = false;
}
if (ContextOverrides::kAvoidStencilBuffers & overrides) {
grOptions.fAvoidStencilBuffers = true;
}
sk_sp<GrContext> grCtx;
{
auto restore = testCtx->makeCurrentAndAutoRestore();
grCtx = testCtx->makeGrContext(grOptions);
}
if (!grCtx.get()) {
return ContextInfo();
}
if (ContextOverrides::kRequireNVPRSupport & overrides) {
if (!grCtx->caps()->shaderCaps()->pathRenderingSupport()) {
return ContextInfo();
}
}
if (ContextOverrides::kRequireSRGBSupport & overrides) {
if (!grCtx->caps()->srgbSupport()) {
return ContextInfo();
}
}
// We must always add new contexts by pushing to the back so that when we delete them we delete
// them in reverse order in which they were made.
Context& context = fContexts.push_back();
context.fBackend = backend;
context.fTestContext = testCtx.release();
context.fGrContext = SkRef(grCtx.get());
context.fType = type;
context.fOverrides = overrides;
context.fAbandoned = false;
context.fShareContext = shareContext;
context.fShareIndex = shareIndex;
context.fOptions = grOptions;
context.fTestContext->makeCurrent();
return ContextInfo(context.fType, context.fTestContext, context.fGrContext, context.fOptions);
}
ContextInfo GrContextFactory::getContextInfo(ContextType type, ContextOverrides overrides) {
return this->getContextInfoInternal(type, overrides, nullptr, 0);
}
ContextInfo GrContextFactory::getSharedContextInfo(GrContext* shareContext, uint32_t shareIndex) {
SkASSERT(shareContext);
for (int i = 0; i < fContexts.count(); ++i) {
if (!fContexts[i].fAbandoned && fContexts[i].fGrContext == shareContext) {
return this->getContextInfoInternal(fContexts[i].fType, fContexts[i].fOverrides,
shareContext, shareIndex);
}
}
return ContextInfo();
}
} // namespace sk_gpu_test
<|endoftext|>
|
<commit_before>#ifndef GENERIC_ALGORITHM_HPP
# define GENERIC_ALGORITHM_HPP
# pragma once
#include <cstddef>
#include <type_traits>
#include <utility>
#include "meta.hpp"
namespace generic
{
// min, max
template <typename T>
constexpr inline T const& max(T const& a, T const& b) noexcept
{
return a > b ? a : b;
}
template <typename T>
constexpr inline T const& min(T const& a, T const& b) noexcept
{
return a < b ? a : b;
}
template <typename T, typename ...A>
constexpr inline typename ::std::enable_if<
bool(sizeof...(A)) &&
all_of<
::std::is_same<
typename ::std::decay<T>::type,
typename ::std::decay<A>::type
>...
>{},
T
>::type
max(T const& a, T const& b, A&& ...args) noexcept
{
return a > b ?
max(a, ::std::forward<A>(args)...) :
max(b, ::std::forward<A>(args)...);
}
template <typename T, typename ...A>
constexpr inline typename ::std::enable_if<
bool(sizeof...(A)) &&
all_of<
::std::is_same<
typename ::std::decay<T>::type,
typename ::std::decay<A>::type
>...
>{},
T
>::type
min(T const& a, T const& b, A&& ...args) noexcept
{
return a < b ?
min(a, ::std::forward<A>(args)...) :
min(b, ::std::forward<A>(args)...);
}
template <typename ...A>
constexpr inline typename ::std::enable_if<
bool(sizeof...(A)) &&
all_of<
::std::is_same<
typename ::std::decay<typename front<A...>::type>::type,
typename ::std::decay<A>::type
>...
>{},
::std::pair<
typename ::std::decay<typename front<A...>::type>::type,
typename ::std::decay<typename front<A...>::type>::type
>
>::type
minmax(A&& ...args) noexcept
{
return {
min(::std::forward<A>(args)...),
max(::std::forward<A>(args)...)
};
}
template<typename T, typename U, typename V>
constexpr inline ::std::enable_if_t<
::std::is_same<T, U>{} &&
::std::is_same<U, V>{},
T const&
>
clamp(T const& v, U const& lo, V const& hi) noexcept
{
return v < lo ?
lo :
hi < v ?
hi :
v;
}
}
#endif // GENERIC_ALGORITHM_HPP
<commit_msg>some fixes<commit_after>#ifndef GENERIC_ALGORITHM_HPP
# define GENERIC_ALGORITHM_HPP
# pragma once
#include <cstddef>
#include <type_traits>
#include <utility>
#include "meta.hpp"
namespace generic
{
// min, max
template <typename T>
constexpr inline T const& max(T const& a, T const& b) noexcept
{
return a > b ? a : b;
}
template <typename T>
constexpr inline T const& min(T const& a, T const& b) noexcept
{
return a < b ? a : b;
}
template <typename T, typename ...A>
constexpr inline ::std::enable_if_t<
bool(sizeof...(A)) &&
all_of<
::std::is_same<
typename ::std::decay<T>::type,
typename ::std::decay<A>::type
>...
>{},
T
>
max(T const& a, T const& b, A&& ...args) noexcept
{
return a > b ?
max(a, ::std::forward<A>(args)...) :
max(b, ::std::forward<A>(args)...);
}
template <typename T, typename ...A>
constexpr inline ::std::enable_if_t<
bool(sizeof...(A)) &&
all_of<
::std::is_same<
typename ::std::decay<T>::type,
typename ::std::decay<A>::type
>...
>{},
T
>
min(T const& a, T const& b, A&& ...args) noexcept
{
return a < b ?
min(a, ::std::forward<A>(args)...) :
min(b, ::std::forward<A>(args)...);
}
template <typename ...A>
constexpr inline typename ::std::enable_if_t<
bool(sizeof...(A)) &&
all_of<
::std::is_same<
typename ::std::decay<typename front<A...>::type>::type,
typename ::std::decay<A>::type
>...
>{},
::std::pair<
typename ::std::decay<typename front<A...>::type>::type,
typename ::std::decay<typename front<A...>::type>::type
>
>
minmax(A&& ...args) noexcept
{
return {
min(::std::forward<A>(args)...),
max(::std::forward<A>(args)...)
};
}
template<typename T, typename U, typename V>
constexpr inline ::std::enable_if_t<
::std::is_same<T, U>{} &&
::std::is_same<U, V>{},
T const&
>
clamp(T const& v, U const& lo, V const& hi) noexcept
{
return v < lo ?
lo :
hi < v ?
hi :
v;
}
}
#endif // GENERIC_ALGORITHM_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stdafx.h"
// This include needs to be kept in order to make sure the
// auto_ptr<dynamic_context> manages to dealocate the
// dynamic_context object.
#include "context/dynamic_context.h"
#include "runtime/function_item/function_item.h"
#include "runtime/core/fncall_iterator.h"
#include "runtime/base/plan_iterator.h"
#include "runtime/api/plan_iterator_wrapper.h"
#include "runtime/visitors/planiter_visitor.h"
#include "compiler/api/compilercb.h"
#include "compiler/expression/var_expr.h"
#include "compiler/expression/function_item_expr.h"
#include "compiler/expression/expr_manager.h"
#include "functions/signature.h"
#include "functions/udf.h"
#include "store/api/temp_seq.h"
#include "zorbaserialization/serialize_template_types.h"
#include "zorbaserialization/serialize_zorba_types.h"
namespace zorba
{
SERIALIZABLE_CLASS_VERSIONS(DynamicFunctionInfo)
SERIALIZABLE_CLASS_VERSIONS(FunctionItem)
SERIALIZABLE_CLASS_VERSIONS(DynamicFunctionIterator)
/*******************************************************************************
********************************************************************************/
DynamicFunctionInfo::DynamicFunctionInfo(// CompilerCB *ccb,
static_context* closureSctx,
const QueryLoc& loc,
function* func,
store::Item_t qname,
uint32_t arity,
bool isInline,
bool needsContextItem)
:
theMustDeleteCCB(false),
theClosureSctx(closureSctx),
theLoc(loc),
theFunction(func),
theQName(qname),
theArity(arity),
theIsInline(isInline),
theNeedsContextItem(needsContextItem)
{
}
DynamicFunctionInfo::DynamicFunctionInfo(::zorba::serialization::Archiver& ar)
{
}
DynamicFunctionInfo::~DynamicFunctionInfo()
{
if (theMustDeleteCCB)
delete theCCB;
}
void DynamicFunctionInfo::serialize(::zorba::serialization::Archiver& ar)
{
ar & theCCB;
ar & theMustDeleteCCB;
ar & theClosureSctx;
ar & theLoc;
ar & theFunction;
ar & theQName;
ar & theArity;
ar & theIsInline;
ar & theNeedsContextItem;
// These are not serialized
// ar & theScopedVarsValues;
// ar & theSubstVarsValues;
ar & theScopedVarsNames;
ar & theIsGlobalVar;
ar & theVarId;
ar & theScopedVarsIterators;
if (ar.is_serializing_out())
{
uint32_t planStateSize;
(void)static_cast<user_function*>(theFunction.getp())->getPlan(planStateSize);
}
}
void DynamicFunctionInfo::add_variable(expr* var, var_expr* substVar, const store::Item_t& name, int isGlobal)
{
theScopedVarsValues.push_back(var);
theSubstVarsValues.push_back(substVar);
theScopedVarsNames.push_back(name);
theIsGlobalVar.push_back(isGlobal);
theVarId.push_back(0);
}
/*******************************************************************************
********************************************************************************/
FunctionItem::FunctionItem(::zorba::serialization::Archiver& ar)
:
store::Item(store::Item::FUNCTION)
{
}
FunctionItem::FunctionItem(const DynamicFunctionInfo_t& dynamicFunctionInfo,
dynamic_context* dctx)
:
store::Item(store::Item::FUNCTION),
theDynamicFunctionInfo(dynamicFunctionInfo),
theArity(dynamicFunctionInfo->theArity),
theClosureDctx(dctx)
{
assert(theDynamicFunctionInfo->theFunction->isUdf());
theArgumentsValues.resize(theDynamicFunctionInfo->theArity);
}
void FunctionItem::serialize(::zorba::serialization::Archiver& ar)
{
ar & theDynamicFunctionInfo;
ar & theArity;
ar & theArgumentsValues;
}
const store::Item_t FunctionItem::getFunctionName() const
{
return theDynamicFunctionInfo->theQName;
}
uint32_t FunctionItem::getArity() const
{
return theArity;
}
uint32_t FunctionItem::getStartArity() const
{
return theDynamicFunctionInfo->theArity;
}
const signature& FunctionItem::getSignature() const
{
return theDynamicFunctionInfo->theFunction->getSignature();
}
const std::vector<PlanIter_t>& FunctionItem::getArgumentsValues() const
{
return theArgumentsValues;
}
bool FunctionItem::isArgumentApplied(unsigned int pos) const
{
assert(pos < theArgumentsValues.size());
return (theArgumentsValues[pos].getp() != NULL);
}
void FunctionItem::setArgumentValue(unsigned int pos, const PlanIter_t& value)
{
theArity--;
// find the pos-th NULL value and fill it
for (unsigned int i=0; i<theArgumentsValues.size(); i++)
if (theArgumentsValues[i] == NULL)
{
if (pos == 0)
{
theArgumentsValues[i] = value;
return;
}
else
pos--;
}
assert(false);
}
PlanIter_t FunctionItem::getImplementation(const std::vector<PlanIter_t>& dynChildren, CompilerCB* ccb)
{
std::vector<PlanIter_t> args;
args.resize(theArgumentsValues.size());
std::vector<PlanIter_t>::iterator argsIte = args.begin();
std::vector<PlanIter_t>::iterator ite = theArgumentsValues.begin();
std::vector<PlanIter_t>::const_iterator ite2 = dynChildren.begin();
++ite2; // skip the first child because it's the function item
for( ; argsIte != args.end(); ++argsIte, ++ite)
{
if (*ite != NULL)
{
*argsIte = *ite;
static_cast<PlanStateIteratorWrapper*>(ite->getp())->reset();
}
else
{
*argsIte = *ite2;
++ite2;
}
}
// if (theDynamicFunctionInfo->theCCB != NULL)
// ccb = theDynamicFunctionInfo->theCCB;
std::cerr << "--> FunctionItem::getImplementation() using CompilerCB: " << ccb << std::endl;
expr* dummy = ccb->theEM->create_function_item_expr(NULL, NULL, theDynamicFunctionInfo->theLoc, NULL, false, false);
PlanIter_t udfCallIterator =
theDynamicFunctionInfo->theFunction->codegen(ccb,
theDynamicFunctionInfo->theClosureSctx,
theDynamicFunctionInfo->theLoc,
args,
*dummy);
UDFunctionCallIterator* udfIter = static_cast<UDFunctionCallIterator*>(udfCallIterator.getp());
udfIter->setDynamic();
udfIter->setFunctionItem(this);
return udfCallIterator;
}
zstring FunctionItem::show() const
{
std::ostringstream lRes;
lRes << getFunctionName()->getStringValue();
if (!isInline())
lRes << "#" << getArity() << " (" << theDynamicFunctionInfo->theLoc << ")";
return lRes.str();
}
/*******************************************************************************
********************************************************************************/
void DynamicFunctionIterator::serialize(::zorba::serialization::Archiver& ar)
{
serialize_baseclass(ar, (NaryBaseIterator<DynamicFunctionIterator, PlanIteratorState>*)this);
ar & theDynamicFunctionInfo;
}
/*******************************************************************************
********************************************************************************/
DynamicFunctionIterator::DynamicFunctionIterator(
static_context* sctx,
const QueryLoc& loc,
DynamicFunctionInfo* fnInfo)
:
NaryBaseIterator<DynamicFunctionIterator, PlanIteratorState>(sctx, loc, fnInfo->theScopedVarsIterators),
theDynamicFunctionInfo(fnInfo)
{
}
DynamicFunctionIterator::~DynamicFunctionIterator()
{
}
bool DynamicFunctionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
PlanIteratorState* state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
// This portion is taken from the eval iterator
{
// Create the dynamic context for the eval query
std::auto_ptr<dynamic_context> evalDctx;
evalDctx.reset(new dynamic_context(planState.theGlobalDynCtx));
// Import the outer environment.
importOuterEnv(planState, theDynamicFunctionInfo->theCCB, theDynamicFunctionInfo->theClosureSctx, evalDctx.get());
result = new FunctionItem(theDynamicFunctionInfo, evalDctx.release());
}
STACK_PUSH ( result != NULL, state );
STACK_END (state);
}
/********************************************************************************
These functions are copied from the EvalIterator -- maybe they could be shared.
********************************************************************************/
/****************************************************************************//**
This method imports a static and dynamic environment from the quter query into
the eval query. In particular:
(a) imports into the importSctx all the outer vars of the eval query
(b) imports into the importSctx all the ns bindings of the outer query at the
place where the eval call appears at
(c) Copies all the var values from the outer-query global dctx into the eval-
query dctx.
(d) For each of the non-global outer vars, places its value into the eval dctx.
The var value is represented as a PlanIteratorWrapper over the subplan that
evaluates the domain expr of the eval var.
(e) Computes the max var id of all the var values set in steps (c) and (d).
This max varid will be passed to the compiler of the eval query so that
the varids that will be generated for the eval query will not conflict with
the varids of the outer vars and the outer-query global vars.
********************************************************************************/
void DynamicFunctionIterator::importOuterEnv(
PlanState& planState,
CompilerCB* evalCCB,
static_context* importSctx,
dynamic_context* evalDctx) const
{
ulong maxOuterVarId = 1;
// Copy all the var values from the outer-query global dctx into the eval-query
// dctx. This is need to handle the following scenario: (a) $x is an outer-query
// global var that is not among the outer vars of the eval query (because $x was
// hidden at the point where the eval call is made inside the outer query), and
// (b) foo() is a function decalred in the outer query that accessed $x and is
// invoked by the eval query. The copying must be done using the same positions
// (i.e., var ids) in the eval dctx as in the outer-query dctx.
dynamic_context* outerDctx = evalDctx->getParent();
const std::vector<dynamic_context::VarValue>& outerGlobalValues =
outerDctx->get_variables();
csize numOuterGlobalVars = outerGlobalValues.size();
for (csize i = 0; i < numOuterGlobalVars; ++i)
{
const dynamic_context::VarValue& outerVar = outerGlobalValues[i];
if (!outerVar.isSet())
continue;
ulong outerVarId = static_cast<ulong>(i);
if (outerVarId > maxOuterVarId)
maxOuterVarId = outerVarId;
store::Item_t itemValue;
store::TempSeq_t seqValue;
if (outerVar.hasItemValue())
{
store::Item_t value = outerVar.theValue.item;
evalDctx->add_variable(outerVarId, value);
}
else
{
store::Iterator_t iteValue = outerVar.theValue.temp_seq->getIterator();
evalDctx->add_variable(outerVarId, iteValue);
}
}
++maxOuterVarId;
// Import the outer vars. Specifically, for each outer var:
// (a) create a declaration inside the importSctx.
// (b) Set its var id
// (c) If it is not a global one, set its value within the eval dctx.
csize curChild = -1;
csize numOuterVars = theDynamicFunctionInfo->theScopedVarsNames.size();
for (csize i = 0; i < numOuterVars; ++i)
{
if (!theDynamicFunctionInfo->theIsGlobalVar[i])
{
++curChild;
store::Iterator_t iter = new PlanIteratorWrapper(theChildren[curChild], planState);
evalDctx->add_variable(theDynamicFunctionInfo->theVarId[i], iter);
}
}
// Import the outer-query ns bindings
store::NsBindings::const_iterator ite = theDynamicFunctionInfo->theLocalBindings.begin();
store::NsBindings::const_iterator end = theDynamicFunctionInfo->theLocalBindings.end();
for (; ite != end; ++ite)
{
importSctx->bind_ns(ite->first, ite->second, loc);
}
}
/****************************************************************************//**
********************************************************************************/
void DynamicFunctionIterator::setExternalVariables(
CompilerCB* ccb,
static_context* importSctx,
dynamic_context* evalDctx) const
{
std::vector<VarInfo*> innerVars;
CompilerCB::SctxMap::const_iterator sctxIte = ccb->theSctxMap.begin();
CompilerCB::SctxMap::const_iterator sctxEnd = ccb->theSctxMap.end();
for (; sctxIte != sctxEnd; ++sctxIte)
{
sctxIte->second->getVariables(innerVars, true, false, true);
}
FOR_EACH(std::vector<VarInfo*>, ite, innerVars)
{
VarInfo* innerVar = (*ite);
if (!innerVar->isExternal())
continue;
ulong innerVarId = innerVar->getId();
VarInfo* outerVar = importSctx->lookup_var(innerVar->getName());
if (!outerVar)
continue;
store::Item_t itemValue;
store::TempSeq_t seqValue;
evalDctx->get_variable(outerVar->getId(),
outerVar->getName(),
loc,
itemValue,
seqValue);
if (itemValue != NULL)
{
evalDctx->add_variable(innerVarId, itemValue);
}
else
{
store::Iterator_t iteValue = seqValue->getIterator();
evalDctx->add_variable(innerVarId, iteValue);
}
}
}
NARY_ACCEPT(DynamicFunctionIterator)
} //namespace zorba
/* vim:set et sw=2 ts=2: */
<commit_msg>Removed a debug message<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stdafx.h"
// This include needs to be kept in order to make sure the
// auto_ptr<dynamic_context> manages to dealocate the
// dynamic_context object.
#include "context/dynamic_context.h"
#include "runtime/function_item/function_item.h"
#include "runtime/core/fncall_iterator.h"
#include "runtime/base/plan_iterator.h"
#include "runtime/api/plan_iterator_wrapper.h"
#include "runtime/visitors/planiter_visitor.h"
#include "compiler/api/compilercb.h"
#include "compiler/expression/var_expr.h"
#include "compiler/expression/function_item_expr.h"
#include "compiler/expression/expr_manager.h"
#include "functions/signature.h"
#include "functions/udf.h"
#include "store/api/temp_seq.h"
#include "zorbaserialization/serialize_template_types.h"
#include "zorbaserialization/serialize_zorba_types.h"
namespace zorba
{
SERIALIZABLE_CLASS_VERSIONS(DynamicFunctionInfo)
SERIALIZABLE_CLASS_VERSIONS(FunctionItem)
SERIALIZABLE_CLASS_VERSIONS(DynamicFunctionIterator)
/*******************************************************************************
********************************************************************************/
DynamicFunctionInfo::DynamicFunctionInfo(// CompilerCB *ccb,
static_context* closureSctx,
const QueryLoc& loc,
function* func,
store::Item_t qname,
uint32_t arity,
bool isInline,
bool needsContextItem)
:
theMustDeleteCCB(false),
theClosureSctx(closureSctx),
theLoc(loc),
theFunction(func),
theQName(qname),
theArity(arity),
theIsInline(isInline),
theNeedsContextItem(needsContextItem)
{
}
DynamicFunctionInfo::DynamicFunctionInfo(::zorba::serialization::Archiver& ar)
{
}
DynamicFunctionInfo::~DynamicFunctionInfo()
{
if (theMustDeleteCCB)
delete theCCB;
}
void DynamicFunctionInfo::serialize(::zorba::serialization::Archiver& ar)
{
ar & theCCB;
ar & theMustDeleteCCB;
ar & theClosureSctx;
ar & theLoc;
ar & theFunction;
ar & theQName;
ar & theArity;
ar & theIsInline;
ar & theNeedsContextItem;
// These are not serialized
// ar & theScopedVarsValues;
// ar & theSubstVarsValues;
ar & theScopedVarsNames;
ar & theIsGlobalVar;
ar & theVarId;
ar & theScopedVarsIterators;
if (ar.is_serializing_out())
{
uint32_t planStateSize;
(void)static_cast<user_function*>(theFunction.getp())->getPlan(planStateSize);
}
}
void DynamicFunctionInfo::add_variable(expr* var, var_expr* substVar, const store::Item_t& name, int isGlobal)
{
theScopedVarsValues.push_back(var);
theSubstVarsValues.push_back(substVar);
theScopedVarsNames.push_back(name);
theIsGlobalVar.push_back(isGlobal);
theVarId.push_back(0);
}
/*******************************************************************************
********************************************************************************/
FunctionItem::FunctionItem(::zorba::serialization::Archiver& ar)
:
store::Item(store::Item::FUNCTION)
{
}
FunctionItem::FunctionItem(const DynamicFunctionInfo_t& dynamicFunctionInfo,
dynamic_context* dctx)
:
store::Item(store::Item::FUNCTION),
theDynamicFunctionInfo(dynamicFunctionInfo),
theArity(dynamicFunctionInfo->theArity),
theClosureDctx(dctx)
{
assert(theDynamicFunctionInfo->theFunction->isUdf());
theArgumentsValues.resize(theDynamicFunctionInfo->theArity);
}
void FunctionItem::serialize(::zorba::serialization::Archiver& ar)
{
ar & theDynamicFunctionInfo;
ar & theArity;
ar & theArgumentsValues;
}
const store::Item_t FunctionItem::getFunctionName() const
{
return theDynamicFunctionInfo->theQName;
}
uint32_t FunctionItem::getArity() const
{
return theArity;
}
uint32_t FunctionItem::getStartArity() const
{
return theDynamicFunctionInfo->theArity;
}
const signature& FunctionItem::getSignature() const
{
return theDynamicFunctionInfo->theFunction->getSignature();
}
const std::vector<PlanIter_t>& FunctionItem::getArgumentsValues() const
{
return theArgumentsValues;
}
bool FunctionItem::isArgumentApplied(unsigned int pos) const
{
assert(pos < theArgumentsValues.size());
return (theArgumentsValues[pos].getp() != NULL);
}
void FunctionItem::setArgumentValue(unsigned int pos, const PlanIter_t& value)
{
theArity--;
// find the pos-th NULL value and fill it
for (unsigned int i=0; i<theArgumentsValues.size(); i++)
if (theArgumentsValues[i] == NULL)
{
if (pos == 0)
{
theArgumentsValues[i] = value;
return;
}
else
pos--;
}
assert(false);
}
PlanIter_t FunctionItem::getImplementation(const std::vector<PlanIter_t>& dynChildren, CompilerCB* ccb)
{
std::vector<PlanIter_t> args;
args.resize(theArgumentsValues.size());
std::vector<PlanIter_t>::iterator argsIte = args.begin();
std::vector<PlanIter_t>::iterator ite = theArgumentsValues.begin();
std::vector<PlanIter_t>::const_iterator ite2 = dynChildren.begin();
++ite2; // skip the first child because it's the function item
for( ; argsIte != args.end(); ++argsIte, ++ite)
{
if (*ite != NULL)
{
*argsIte = *ite;
static_cast<PlanStateIteratorWrapper*>(ite->getp())->reset();
}
else
{
*argsIte = *ite2;
++ite2;
}
}
// if (theDynamicFunctionInfo->theCCB != NULL)
// ccb = theDynamicFunctionInfo->theCCB;
expr* dummy = ccb->theEM->create_function_item_expr(NULL, NULL, theDynamicFunctionInfo->theLoc, NULL, false, false);
PlanIter_t udfCallIterator =
theDynamicFunctionInfo->theFunction->codegen(ccb,
theDynamicFunctionInfo->theClosureSctx,
theDynamicFunctionInfo->theLoc,
args,
*dummy);
UDFunctionCallIterator* udfIter = static_cast<UDFunctionCallIterator*>(udfCallIterator.getp());
udfIter->setDynamic();
udfIter->setFunctionItem(this);
return udfCallIterator;
}
zstring FunctionItem::show() const
{
std::ostringstream lRes;
lRes << getFunctionName()->getStringValue();
if (!isInline())
lRes << "#" << getArity() << " (" << theDynamicFunctionInfo->theLoc << ")";
return lRes.str();
}
/*******************************************************************************
********************************************************************************/
void DynamicFunctionIterator::serialize(::zorba::serialization::Archiver& ar)
{
serialize_baseclass(ar, (NaryBaseIterator<DynamicFunctionIterator, PlanIteratorState>*)this);
ar & theDynamicFunctionInfo;
}
/*******************************************************************************
********************************************************************************/
DynamicFunctionIterator::DynamicFunctionIterator(
static_context* sctx,
const QueryLoc& loc,
DynamicFunctionInfo* fnInfo)
:
NaryBaseIterator<DynamicFunctionIterator, PlanIteratorState>(sctx, loc, fnInfo->theScopedVarsIterators),
theDynamicFunctionInfo(fnInfo)
{
}
DynamicFunctionIterator::~DynamicFunctionIterator()
{
}
bool DynamicFunctionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
PlanIteratorState* state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
// This portion is taken from the eval iterator
{
// Create the dynamic context for the eval query
std::auto_ptr<dynamic_context> evalDctx;
evalDctx.reset(new dynamic_context(planState.theGlobalDynCtx));
// Import the outer environment.
importOuterEnv(planState, theDynamicFunctionInfo->theCCB, theDynamicFunctionInfo->theClosureSctx, evalDctx.get());
result = new FunctionItem(theDynamicFunctionInfo, evalDctx.release());
}
STACK_PUSH ( result != NULL, state );
STACK_END (state);
}
/********************************************************************************
These functions are copied from the EvalIterator -- maybe they could be shared.
********************************************************************************/
/****************************************************************************//**
This method imports a static and dynamic environment from the quter query into
the eval query. In particular:
(a) imports into the importSctx all the outer vars of the eval query
(b) imports into the importSctx all the ns bindings of the outer query at the
place where the eval call appears at
(c) Copies all the var values from the outer-query global dctx into the eval-
query dctx.
(d) For each of the non-global outer vars, places its value into the eval dctx.
The var value is represented as a PlanIteratorWrapper over the subplan that
evaluates the domain expr of the eval var.
(e) Computes the max var id of all the var values set in steps (c) and (d).
This max varid will be passed to the compiler of the eval query so that
the varids that will be generated for the eval query will not conflict with
the varids of the outer vars and the outer-query global vars.
********************************************************************************/
void DynamicFunctionIterator::importOuterEnv(
PlanState& planState,
CompilerCB* evalCCB,
static_context* importSctx,
dynamic_context* evalDctx) const
{
ulong maxOuterVarId = 1;
// Copy all the var values from the outer-query global dctx into the eval-query
// dctx. This is need to handle the following scenario: (a) $x is an outer-query
// global var that is not among the outer vars of the eval query (because $x was
// hidden at the point where the eval call is made inside the outer query), and
// (b) foo() is a function decalred in the outer query that accessed $x and is
// invoked by the eval query. The copying must be done using the same positions
// (i.e., var ids) in the eval dctx as in the outer-query dctx.
dynamic_context* outerDctx = evalDctx->getParent();
const std::vector<dynamic_context::VarValue>& outerGlobalValues =
outerDctx->get_variables();
csize numOuterGlobalVars = outerGlobalValues.size();
for (csize i = 0; i < numOuterGlobalVars; ++i)
{
const dynamic_context::VarValue& outerVar = outerGlobalValues[i];
if (!outerVar.isSet())
continue;
ulong outerVarId = static_cast<ulong>(i);
if (outerVarId > maxOuterVarId)
maxOuterVarId = outerVarId;
store::Item_t itemValue;
store::TempSeq_t seqValue;
if (outerVar.hasItemValue())
{
store::Item_t value = outerVar.theValue.item;
evalDctx->add_variable(outerVarId, value);
}
else
{
store::Iterator_t iteValue = outerVar.theValue.temp_seq->getIterator();
evalDctx->add_variable(outerVarId, iteValue);
}
}
++maxOuterVarId;
// Import the outer vars. Specifically, for each outer var:
// (a) create a declaration inside the importSctx.
// (b) Set its var id
// (c) If it is not a global one, set its value within the eval dctx.
csize curChild = -1;
csize numOuterVars = theDynamicFunctionInfo->theScopedVarsNames.size();
for (csize i = 0; i < numOuterVars; ++i)
{
if (!theDynamicFunctionInfo->theIsGlobalVar[i])
{
++curChild;
store::Iterator_t iter = new PlanIteratorWrapper(theChildren[curChild], planState);
evalDctx->add_variable(theDynamicFunctionInfo->theVarId[i], iter);
}
}
// Import the outer-query ns bindings
store::NsBindings::const_iterator ite = theDynamicFunctionInfo->theLocalBindings.begin();
store::NsBindings::const_iterator end = theDynamicFunctionInfo->theLocalBindings.end();
for (; ite != end; ++ite)
{
importSctx->bind_ns(ite->first, ite->second, loc);
}
}
/****************************************************************************//**
********************************************************************************/
void DynamicFunctionIterator::setExternalVariables(
CompilerCB* ccb,
static_context* importSctx,
dynamic_context* evalDctx) const
{
std::vector<VarInfo*> innerVars;
CompilerCB::SctxMap::const_iterator sctxIte = ccb->theSctxMap.begin();
CompilerCB::SctxMap::const_iterator sctxEnd = ccb->theSctxMap.end();
for (; sctxIte != sctxEnd; ++sctxIte)
{
sctxIte->second->getVariables(innerVars, true, false, true);
}
FOR_EACH(std::vector<VarInfo*>, ite, innerVars)
{
VarInfo* innerVar = (*ite);
if (!innerVar->isExternal())
continue;
ulong innerVarId = innerVar->getId();
VarInfo* outerVar = importSctx->lookup_var(innerVar->getName());
if (!outerVar)
continue;
store::Item_t itemValue;
store::TempSeq_t seqValue;
evalDctx->get_variable(outerVar->getId(),
outerVar->getName(),
loc,
itemValue,
seqValue);
if (itemValue != NULL)
{
evalDctx->add_variable(innerVarId, itemValue);
}
else
{
store::Iterator_t iteValue = seqValue->getIterator();
evalDctx->add_variable(innerVarId, iteValue);
}
}
}
NARY_ACCEPT(DynamicFunctionIterator)
} //namespace zorba
/* vim:set et sw=2 ts=2: */
<|endoftext|>
|
<commit_before>#include <memory.h>
#include "vtrc-hash-iface.h"
#include "hash/sha2-traits.h"
namespace vtrc { namespace common { namespace hash {
namespace {
template <typename HashTraits>
struct hasher_sha: public hash_iface {
size_t hash_size( ) const
{
return HashTraits::digest_length;
}
std::string get_data_hash(const void *data,
size_t length ) const
{
typename HashTraits::context_type context;
HashTraits::init( &context );
HashTraits::update( &context,
reinterpret_cast<const vtrc::uint8_t *>(data), length );
return HashTraits::fin( &context );
}
void get_data_hash(const void *data, size_t length,
void *result_hash ) const
{
typename HashTraits::context_type context;
HashTraits::init( &context );
HashTraits::update( &context,
reinterpret_cast< const u_int8_t * >(data), length );
HashTraits::fin( &context,
reinterpret_cast<vtrc::uint8_t *>(result_hash));
}
bool check_data_hash( const void * data ,
size_t length,
const void * hash ) const
{
std::string h = get_data_hash( data, length );
return memcmp( h.c_str( ), hash,
HashTraits::digest_length ) == 0;
}
};
}
namespace sha2 {
hash_iface *create256( )
{
return new hasher_sha<vtrc::hash::hash_SHA256_traits>;
}
hash_iface *create348( )
{
return new hasher_sha<vtrc::hash::hash_SHA384_traits>;
}
hash_iface *create512( )
{
return new hasher_sha<vtrc::hash::hash_SHA512_traits>;
}
}
}}}
<commit_msg>hash finish->fin<commit_after>#include <memory.h>
#include "vtrc-hash-iface.h"
#include "hash/sha2-traits.h"
namespace vtrc { namespace common { namespace hash {
namespace {
template <typename HashTraits>
struct hasher_sha: public hash_iface {
size_t hash_size( ) const
{
return HashTraits::digest_length;
}
std::string get_data_hash(const void *data,
size_t length ) const
{
typename HashTraits::context_type context;
HashTraits::init( &context );
HashTraits::update( &context,
reinterpret_cast<const vtrc::uint8_t *>(data), length );
return HashTraits::fin( &context );
}
void get_data_hash(const void *data, size_t length,
void *result_hash ) const
{
typename HashTraits::context_type context;
HashTraits::init( &context );
HashTraits::update( &context,
reinterpret_cast<const vtrc::uint8_t *>(data), length );
HashTraits::fin( &context,
reinterpret_cast<vtrc::uint8_t *>(result_hash));
}
bool check_data_hash( const void * data ,
size_t length,
const void * hash ) const
{
std::string h = get_data_hash( data, length );
return memcmp( h.c_str( ), hash,
HashTraits::digest_length ) == 0;
}
};
}
namespace sha2 {
hash_iface *create256( )
{
return new hasher_sha<vtrc::hash::hash_SHA256_traits>;
}
hash_iface *create348( )
{
return new hasher_sha<vtrc::hash::hash_SHA384_traits>;
}
hash_iface *create512( )
{
return new hasher_sha<vtrc::hash::hash_SHA512_traits>;
}
}
}}}
<|endoftext|>
|
<commit_before>#include "vtrc-pool-pair.h"
#include "vtrc-thread.h"
#include "vtrc-mutex-typedefs.h"
//#include "boost/asio.hpp"
namespace vtrc { namespace common {
namespace basio = boost::asio;
struct pool_pair::impl {
thread_pool *genegal_;
thread_pool *rpc_;
const bool same_;
impl( unsigned thread_count )
:genegal_(new thread_pool(thread_count ? thread_count : 1))
,rpc_(genegal_)
,same_(true)
{
}
impl( unsigned thread_count, unsigned rpc_thread_count )
:genegal_(new thread_pool(thread_count ? thread_count : 1))
,rpc_(new thread_pool(rpc_thread_count ? rpc_thread_count : 1))
,same_(false)
{
}
~impl( )
{
stop_all( );
join_all( );
delete genegal_;
if( !same_ ) delete rpc_;
}
void stop_all( )
{
genegal_->stop( );
if( !same_ ) rpc_->stop( );
}
void join_all( )
{
genegal_->join_all( );
if(!same_) rpc_->join_all( );
}
};
pool_pair::pool_pair( unsigned thread_count )
:impl_(new impl(thread_count))
{}
pool_pair::pool_pair( unsigned thread_count, unsigned rpc_thread_count )
:impl_(new impl(thread_count, rpc_thread_count))
{}
pool_pair::~pool_pair( )
{
delete impl_;
}
boost::asio::io_service &pool_pair::get_io_service( )
{
return impl_->genegal_->get_io_service( );
}
const boost::asio::io_service &pool_pair::get_io_service( ) const
{
return impl_->genegal_->get_io_service( );
}
boost::asio::io_service &pool_pair::get_rpc_service( )
{
return impl_->rpc_->get_io_service( );
}
const boost::asio::io_service &pool_pair::get_rpc_service( ) const
{
return impl_->rpc_->get_io_service( );
}
thread_pool &pool_pair::get_io_pool( )
{
return *impl_->genegal_;
}
const thread_pool &pool_pair::get_io_pool( ) const
{
return *impl_->genegal_;
}
thread_pool &pool_pair::get_rpc_pool( )
{
return *impl_->rpc_;
}
const thread_pool &pool_pair::get_rpc_pool( ) const
{
return *impl_->rpc_;
}
void pool_pair::stop_all( )
{
impl_->stop_all( );
}
void pool_pair::join_all( )
{
impl_->join_all( );
}
}}
<commit_msg>proto<commit_after>#include "vtrc-pool-pair.h"
#include "vtrc-thread.h"
#include "vtrc-mutex-typedefs.h"
//#include "boost/asio.hpp"
namespace vtrc { namespace common {
namespace basio = boost::asio;
struct pool_pair::impl {
thread_pool *genegal_;
thread_pool *rpc_;
const bool same_;
impl( unsigned thread_count )
:genegal_(new thread_pool(thread_count))
,rpc_(genegal_)
,same_(true)
{
}
impl( unsigned thread_count, unsigned rpc_thread_count )
:genegal_(new thread_pool(thread_count))
,rpc_(new thread_pool(rpc_thread_count))
,same_(false)
{
}
~impl( )
{
stop_all( );
join_all( );
delete genegal_;
if( !same_ ) delete rpc_;
}
void stop_all( )
{
genegal_->stop( );
if( !same_ ) rpc_->stop( );
}
void join_all( )
{
genegal_->join_all( );
if(!same_) rpc_->join_all( );
}
};
pool_pair::pool_pair( unsigned thread_count )
:impl_(new impl(thread_count))
{}
pool_pair::pool_pair( unsigned thread_count, unsigned rpc_thread_count )
:impl_(new impl(thread_count, rpc_thread_count))
{}
pool_pair::~pool_pair( )
{
delete impl_;
}
boost::asio::io_service &pool_pair::get_io_service( )
{
return impl_->genegal_->get_io_service( );
}
const boost::asio::io_service &pool_pair::get_io_service( ) const
{
return impl_->genegal_->get_io_service( );
}
boost::asio::io_service &pool_pair::get_rpc_service( )
{
return impl_->rpc_->get_io_service( );
}
const boost::asio::io_service &pool_pair::get_rpc_service( ) const
{
return impl_->rpc_->get_io_service( );
}
thread_pool &pool_pair::get_io_pool( )
{
return *impl_->genegal_;
}
const thread_pool &pool_pair::get_io_pool( ) const
{
return *impl_->genegal_;
}
thread_pool &pool_pair::get_rpc_pool( )
{
return *impl_->rpc_;
}
const thread_pool &pool_pair::get_rpc_pool( ) const
{
return *impl_->rpc_;
}
void pool_pair::stop_all( )
{
impl_->stop_all( );
}
void pool_pair::join_all( )
{
impl_->join_all( );
}
}}
<|endoftext|>
|
<commit_before>/*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
namespace kurento
{
std::string generateUUID ();
}
<commit_msg>UUIDGenerator: Set macros to prevent multi-include dependancies<commit_after>/*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#ifndef __UUID_GENERATOR_HPP__
#define __UUID_GENERATOR_HPP__
namespace kurento
{
std::string generateUUID ();
}
#endif /* __UUID_GENERATOR_HPP__ */
<|endoftext|>
|
<commit_before>/**
* \file main.cc
* \brief Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted
* \author Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot
* \copyright Copyright (c) 2017, The R2D2 Team
* \license See LICENSE
*/
#include "mysql.hh"
#include "mfrc522.hh"
#include "led-controller.hh"
#include "matrix-keypad.hh"
#include "config-file-parser.hh"
#include <wiringPi.h>
#include <wiringPiSPI.h>
#include <iostream>
struct MFAuthentData {
uint8_t command_code;
uint8_t blockAddress;
uint8_t sectorKey[5];
uint8_t serialNumber[4];
};
int main(int argc, char **argv) {
try {
std::string ip;
std::string username;
std::string password;
int encryptionKey;
ConfigFileParser factory("database-config.txt");
factory.loadDatabaseSettings(ip, username, password);
MySql connection;
connection.connectTo(ip, username, password);
connection.selectDatabase("R2D2");
std::cout << "Made connection to the database\n";
wiringPiSetup();
wiringPiSPISetup(0, 10000000);//max speed for mfrc522 is 10Mhz
Mfrc522 rfid;
rfid.init();
//Keypad pinSetup
const int keypadRow[] = {4, 1, 16, 15};
const int keypadColumn[] = {2, 7, 9, 8};
//Keypad objects
MatrixKeypad keypad(keypadRow, keypadColumn, 4);
char c;
LedController led(0);
while (true) {
std::cout << "\n\nWaiting for rfid tag: \n";
while (!rfid.isTagPresent()) {
}
MFAuthentData x;
uint8_t receiveData[64];
rfid.communicateWithTag(Mfrc522::mfrc522Commands::receive,
nullptr,
0,
receiveData;
64*8);
// rfid.communicateWithTag(Mfrc522::mfrc522Commands::mfAuthent, nullptr, 0, nullptr, 0);
std::cout << "Hello tag\n";
std::cout << "Your id = ";
for(size_t i = 0; i < 4; i++){
std::cout << std::hex << receiveData[0];
}
std::cout << "\n";
std::cout << "Waiting for key press\n";
while ((c = keypad.getKey()) == 'h') {
delay(100);
}
//c = keypad.getKey();
std::cout << c << " key has been pressed\n";
connection.executeQuery("SELECT * FROM RFID");
std::cout << "Database information: "
<< connection.getPreviousResponseColumn("CARD_ID")
<< '\n';
std::cout << "String before encryption: R2D2 project\n";
std::cout << "String after encryption: "
<< '\n';
led.blinkLed(1000);
}
} catch (const std::string &error) {
std::cerr << error << '\n';
exit(EXIT_FAILURE);
} catch (...) {
std::cerr << "Something went wrong\n";
exit(EXIT_FAILURE);
}
return 0;
}
<commit_msg>[RFID-02] semicolon to comma<commit_after>/**
* \file main.cc
* \brief Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted
* \author Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot
* \copyright Copyright (c) 2017, The R2D2 Team
* \license See LICENSE
*/
#include "mysql.hh"
#include "mfrc522.hh"
#include "led-controller.hh"
#include "matrix-keypad.hh"
#include "config-file-parser.hh"
#include <wiringPi.h>
#include <wiringPiSPI.h>
#include <iostream>
struct MFAuthentData {
uint8_t command_code;
uint8_t blockAddress;
uint8_t sectorKey[5];
uint8_t serialNumber[4];
};
int main(int argc, char **argv) {
try {
std::string ip;
std::string username;
std::string password;
int encryptionKey;
ConfigFileParser factory("database-config.txt");
factory.loadDatabaseSettings(ip, username, password);
MySql connection;
connection.connectTo(ip, username, password);
connection.selectDatabase("R2D2");
std::cout << "Made connection to the database\n";
wiringPiSetup();
wiringPiSPISetup(0, 10000000);//max speed for mfrc522 is 10Mhz
Mfrc522 rfid;
rfid.init();
//Keypad pinSetup
const int keypadRow[] = {4, 1, 16, 15};
const int keypadColumn[] = {2, 7, 9, 8};
//Keypad objects
MatrixKeypad keypad(keypadRow, keypadColumn, 4);
char c;
LedController led(0);
while (true) {
std::cout << "\n\nWaiting for rfid tag: \n";
while (!rfid.isTagPresent()) {
}
MFAuthentData x;
uint8_t receiveData[64];
rfid.communicateWithTag(Mfrc522::mfrc522Commands::receive,
nullptr,
0,
receiveData,
64*8);
// rfid.communicateWithTag(Mfrc522::mfrc522Commands::mfAuthent, nullptr, 0, nullptr, 0);
std::cout << "Hello tag\n";
std::cout << "Your id = ";
for(size_t i = 0; i < 4; i++){
std::cout << std::hex << receiveData[0];
}
std::cout << "\n";
std::cout << "Waiting for key press\n";
while ((c = keypad.getKey()) == 'h') {
delay(100);
}
//c = keypad.getKey();
std::cout << c << " key has been pressed\n";
connection.executeQuery("SELECT * FROM RFID");
std::cout << "Database information: "
<< connection.getPreviousResponseColumn("CARD_ID")
<< '\n';
std::cout << "String before encryption: R2D2 project\n";
std::cout << "String after encryption: "
<< '\n';
led.blinkLed(1000);
}
} catch (const std::string &error) {
std::cerr << error << '\n';
exit(EXIT_FAILURE);
} catch (...) {
std::cerr << "Something went wrong\n";
exit(EXIT_FAILURE);
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <map>
#include <stack>
#include <string>
#include "arch/alpha/osfpal.hh"
#include "base/trace.hh"
#include "base/statistics.hh"
#include "base/stats/bin.hh"
#include "cpu/exec_context.hh"
#include "cpu/pc_event.hh"
#include "cpu/static_inst.hh"
#include "kern/kernel_stats.hh"
#include "kern/linux/linux_syscalls.hh"
using namespace std;
using namespace Stats;
namespace Kernel {
const char *modestr[] = { "kernel", "user", "idle", "interrupt" };
Statistics::Statistics(ExecContext *context)
: xc(context), idleProcess((Addr)-1), themode(kernel), lastModeTick(0),
iplLast(0), iplLastTick(0)
{
bin_int = xc->system->params->bin_int;
}
void
Statistics::regStats(const string &_name)
{
myname = _name;
_arm
.name(name() + ".inst.arm")
.desc("number of arm instructions executed")
;
_quiesce
.name(name() + ".inst.quiesce")
.desc("number of quiesce instructions executed")
;
_ivlb
.name(name() + ".inst.ivlb")
.desc("number of ivlb instructions executed")
;
_ivle
.name(name() + ".inst.ivle")
.desc("number of ivle instructions executed")
;
_hwrei
.name(name() + ".inst.hwrei")
.desc("number of hwrei instructions executed")
;
_iplCount
.init(32)
.name(name() + ".ipl_count")
.desc("number of times we switched to this ipl")
.flags(total | pdf | nozero | nonan)
;
_iplGood
.init(32)
.name(name() + ".ipl_good")
.desc("number of times we switched to this ipl from a different ipl")
.flags(total | pdf | nozero | nonan)
;
_iplTicks
.init(32)
.name(name() + ".ipl_ticks")
.desc("number of cycles we spent at this ipl")
.flags(total | pdf | nozero | nonan)
;
_iplUsed
.name(name() + ".ipl_used")
.desc("fraction of swpipl calls that actually changed the ipl")
.flags(total | nozero | nonan)
;
_iplUsed = _iplGood / _iplCount;
_callpal
.init(256)
.name(name() + ".callpal")
.desc("number of callpals executed")
.flags(total | pdf | nozero | nonan)
;
for (int i = 0; i < PAL::NumCodes; ++i) {
const char *str = PAL::name(i);
if (str)
_callpal.subname(i, str);
}
_syscall
.init(SystemCalls<Tru64>::Number)
.name(name() + ".syscall")
.desc("number of syscalls executed")
.flags(total | pdf | nozero | nonan)
;
for (int i = 0; i < SystemCalls<Tru64>::Number; ++i) {
const char *str = SystemCalls<Tru64>::name(i);
if (str) {
_syscall.subname(i, str);
}
}
_faults
.init(Num_Faults)
.name(name() + ".faults")
.desc("number of faults")
.flags(total | pdf | nozero | nonan)
;
for (int i = 1; i < Num_Faults; ++i) {
const char *str = FaultName(i);
if (str)
_faults.subname(i, str);
}
_mode
.init(cpu_mode_num)
.name(name() + ".mode_switch")
.desc("number of protection mode switches")
;
for (int i = 0; i < cpu_mode_num; ++i)
_mode.subname(i, modestr[i]);
_modeGood
.init(cpu_mode_num)
.name(name() + ".mode_good")
;
for (int i = 0; i < cpu_mode_num; ++i)
_modeGood.subname(i, modestr[i]);
_modeFraction
.name(name() + ".mode_switch_good")
.desc("fraction of useful protection mode switches")
.flags(total)
;
for (int i = 0; i < cpu_mode_num; ++i)
_modeFraction.subname(i, modestr[i]);
_modeFraction = _modeGood / _mode;
_modeTicks
.init(cpu_mode_num)
.name(name() + ".mode_ticks")
.desc("number of ticks spent at the given mode")
.flags(pdf)
;
for (int i = 0; i < cpu_mode_num; ++i)
_modeTicks.subname(i, modestr[i]);
_swap_context
.name(name() + ".swap_context")
.desc("number of times the context was actually changed")
;
}
void
Statistics::setIdleProcess(Addr idlepcbb)
{
assert(themode == kernel || themode == interrupt);
idleProcess = idlepcbb;
themode = idle;
changeMode(themode);
}
void
Statistics::changeMode(cpu_mode newmode)
{
_mode[newmode]++;
if (newmode == themode)
return;
DPRINTF(Context, "old mode=%-8s new mode=%-8s\n",
modestr[themode], modestr[newmode]);
_modeGood[newmode]++;
_modeTicks[themode] += curTick - lastModeTick;
xc->system->kernelBinning->changeMode(newmode);
lastModeTick = curTick;
themode = newmode;
}
void
Statistics::swpipl(int ipl)
{
assert(ipl >= 0 && ipl <= 0x1f && "invalid IPL\n");
_iplCount[ipl]++;
if (ipl == iplLast)
return;
_iplGood[ipl]++;
_iplTicks[iplLast] += curTick - iplLastTick;
iplLastTick = curTick;
iplLast = ipl;
}
void
Statistics::mode(cpu_mode newmode)
{
Addr pcbb = xc->regs.ipr[AlphaISA::IPR_PALtemp23];
if ((newmode == kernel || newmode == interrupt) &&
pcbb == idleProcess)
newmode = idle;
if (bin_int == false && newmode == interrupt)
newmode = kernel;
changeMode(newmode);
}
void
Statistics::context(Addr oldpcbb, Addr newpcbb)
{
assert(themode != user);
_swap_context++;
changeMode(newpcbb == idleProcess ? idle : kernel);
}
void
Statistics::callpal(int code)
{
if (!PAL::name(code))
return;
_callpal[code]++;
switch (code) {
case PAL::callsys: {
int number = xc->regs.intRegFile[0];
if (SystemCalls<Tru64>::validSyscallNumber(number)) {
int cvtnum = SystemCalls<Tru64>::convert(number);
_syscall[cvtnum]++;
}
} break;
case PAL::swpctx:
if (xc->system->kernelBinning)
xc->system->kernelBinning->palSwapContext(xc);
break;
}
}
void
Statistics::serialize(ostream &os)
{
int exemode = themode;
SERIALIZE_SCALAR(exemode);
SERIALIZE_SCALAR(idleProcess);
}
void
Statistics::unserialize(Checkpoint *cp, const string §ion)
{
int exemode;
UNSERIALIZE_SCALAR(exemode);
UNSERIALIZE_SCALAR(idleProcess);
themode = (cpu_mode)exemode;
}
/* end namespace Kernel */ }
<commit_msg>few more stat items to serialize<commit_after>/*
* Copyright (c) 2003 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <map>
#include <stack>
#include <string>
#include "arch/alpha/osfpal.hh"
#include "base/trace.hh"
#include "base/statistics.hh"
#include "base/stats/bin.hh"
#include "cpu/exec_context.hh"
#include "cpu/pc_event.hh"
#include "cpu/static_inst.hh"
#include "kern/kernel_stats.hh"
#include "kern/linux/linux_syscalls.hh"
using namespace std;
using namespace Stats;
namespace Kernel {
const char *modestr[] = { "kernel", "user", "idle", "interrupt" };
Statistics::Statistics(ExecContext *context)
: xc(context), idleProcess((Addr)-1), themode(kernel), lastModeTick(0),
iplLast(0), iplLastTick(0)
{
bin_int = xc->system->params->bin_int;
}
void
Statistics::regStats(const string &_name)
{
myname = _name;
_arm
.name(name() + ".inst.arm")
.desc("number of arm instructions executed")
;
_quiesce
.name(name() + ".inst.quiesce")
.desc("number of quiesce instructions executed")
;
_ivlb
.name(name() + ".inst.ivlb")
.desc("number of ivlb instructions executed")
;
_ivle
.name(name() + ".inst.ivle")
.desc("number of ivle instructions executed")
;
_hwrei
.name(name() + ".inst.hwrei")
.desc("number of hwrei instructions executed")
;
_iplCount
.init(32)
.name(name() + ".ipl_count")
.desc("number of times we switched to this ipl")
.flags(total | pdf | nozero | nonan)
;
_iplGood
.init(32)
.name(name() + ".ipl_good")
.desc("number of times we switched to this ipl from a different ipl")
.flags(total | pdf | nozero | nonan)
;
_iplTicks
.init(32)
.name(name() + ".ipl_ticks")
.desc("number of cycles we spent at this ipl")
.flags(total | pdf | nozero | nonan)
;
_iplUsed
.name(name() + ".ipl_used")
.desc("fraction of swpipl calls that actually changed the ipl")
.flags(total | nozero | nonan)
;
_iplUsed = _iplGood / _iplCount;
_callpal
.init(256)
.name(name() + ".callpal")
.desc("number of callpals executed")
.flags(total | pdf | nozero | nonan)
;
for (int i = 0; i < PAL::NumCodes; ++i) {
const char *str = PAL::name(i);
if (str)
_callpal.subname(i, str);
}
_syscall
.init(SystemCalls<Tru64>::Number)
.name(name() + ".syscall")
.desc("number of syscalls executed")
.flags(total | pdf | nozero | nonan)
;
for (int i = 0; i < SystemCalls<Tru64>::Number; ++i) {
const char *str = SystemCalls<Tru64>::name(i);
if (str) {
_syscall.subname(i, str);
}
}
_faults
.init(Num_Faults)
.name(name() + ".faults")
.desc("number of faults")
.flags(total | pdf | nozero | nonan)
;
for (int i = 1; i < Num_Faults; ++i) {
const char *str = FaultName(i);
if (str)
_faults.subname(i, str);
}
_mode
.init(cpu_mode_num)
.name(name() + ".mode_switch")
.desc("number of protection mode switches")
;
for (int i = 0; i < cpu_mode_num; ++i)
_mode.subname(i, modestr[i]);
_modeGood
.init(cpu_mode_num)
.name(name() + ".mode_good")
;
for (int i = 0; i < cpu_mode_num; ++i)
_modeGood.subname(i, modestr[i]);
_modeFraction
.name(name() + ".mode_switch_good")
.desc("fraction of useful protection mode switches")
.flags(total)
;
for (int i = 0; i < cpu_mode_num; ++i)
_modeFraction.subname(i, modestr[i]);
_modeFraction = _modeGood / _mode;
_modeTicks
.init(cpu_mode_num)
.name(name() + ".mode_ticks")
.desc("number of ticks spent at the given mode")
.flags(pdf)
;
for (int i = 0; i < cpu_mode_num; ++i)
_modeTicks.subname(i, modestr[i]);
_swap_context
.name(name() + ".swap_context")
.desc("number of times the context was actually changed")
;
}
void
Statistics::setIdleProcess(Addr idlepcbb)
{
assert(themode == kernel || themode == interrupt);
idleProcess = idlepcbb;
themode = idle;
changeMode(themode);
}
void
Statistics::changeMode(cpu_mode newmode)
{
_mode[newmode]++;
if (newmode == themode)
return;
DPRINTF(Context, "old mode=%-8s new mode=%-8s\n",
modestr[themode], modestr[newmode]);
_modeGood[newmode]++;
_modeTicks[themode] += curTick - lastModeTick;
xc->system->kernelBinning->changeMode(newmode);
lastModeTick = curTick;
themode = newmode;
}
void
Statistics::swpipl(int ipl)
{
assert(ipl >= 0 && ipl <= 0x1f && "invalid IPL\n");
_iplCount[ipl]++;
if (ipl == iplLast)
return;
_iplGood[ipl]++;
_iplTicks[iplLast] += curTick - iplLastTick;
iplLastTick = curTick;
iplLast = ipl;
}
void
Statistics::mode(cpu_mode newmode)
{
Addr pcbb = xc->regs.ipr[AlphaISA::IPR_PALtemp23];
if ((newmode == kernel || newmode == interrupt) &&
pcbb == idleProcess)
newmode = idle;
if (bin_int == false && newmode == interrupt)
newmode = kernel;
changeMode(newmode);
}
void
Statistics::context(Addr oldpcbb, Addr newpcbb)
{
assert(themode != user);
_swap_context++;
changeMode(newpcbb == idleProcess ? idle : kernel);
}
void
Statistics::callpal(int code)
{
if (!PAL::name(code))
return;
_callpal[code]++;
switch (code) {
case PAL::callsys: {
int number = xc->regs.intRegFile[0];
if (SystemCalls<Tru64>::validSyscallNumber(number)) {
int cvtnum = SystemCalls<Tru64>::convert(number);
_syscall[cvtnum]++;
}
} break;
case PAL::swpctx:
if (xc->system->kernelBinning)
xc->system->kernelBinning->palSwapContext(xc);
break;
}
}
void
Statistics::serialize(ostream &os)
{
int exemode = themode;
SERIALIZE_SCALAR(exemode);
SERIALIZE_SCALAR(idleProcess);
SERIALIZE_SCALAR(iplLast);
SERIALIZE_SCALAR(iplLastTick);
SERIALIZE_SCALAR(lastModeTick);
}
void
Statistics::unserialize(Checkpoint *cp, const string §ion)
{
int exemode;
UNSERIALIZE_SCALAR(exemode);
UNSERIALIZE_SCALAR(idleProcess);
UNSERIALIZE_SCALAR(iplLast);
UNSERIALIZE_SCALAR(iplLastTick);
UNSERIALIZE_SCALAR(lastModeTick);
themode = (cpu_mode)exemode;
}
/* end namespace Kernel */ }
<|endoftext|>
|
<commit_before>#include "cube-egl.h"
#include "cube.h"
#include <kms++util/kms++util.h>
using namespace std;
EglState::EglState(void *native_display)
{
EGLBoolean b;
EGLint major, minor, n;
static const EGLint context_attribs[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
static const EGLint config_attribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 0,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_NONE
};
m_display = eglGetDisplay((EGLNativeDisplayType)native_display);
FAIL_IF(!m_display, "failed to get egl display");
b = eglInitialize(m_display, &major, &minor);
FAIL_IF(!b, "failed to initialize");
if (s_verbose) {
printf("Using display %p with EGL version %d.%d\n", m_display, major, minor);
printf("EGL_VENDOR: %s\n", eglQueryString(m_display, EGL_VENDOR));
printf("EGL_VERSION: %s\n", eglQueryString(m_display, EGL_VERSION));
printf("EGL_EXTENSIONS: %s\n", eglQueryString(m_display, EGL_EXTENSIONS));
printf("EGL_CLIENT_APIS: %s\n", eglQueryString(m_display, EGL_CLIENT_APIS));
}
b = eglBindAPI(EGL_OPENGL_ES_API);
FAIL_IF(!b, "failed to bind api EGL_OPENGL_ES_API");
b = eglChooseConfig(m_display, config_attribs, &m_config, 1, &n);
FAIL_IF(!b || n != 1, "failed to choose config");
auto getconf = [this](EGLint a) { EGLint v = -1; eglGetConfigAttrib(m_display, m_config, a, &v); return v; };
if (s_verbose) {
printf("EGL Config %d: color buf %d/%d/%d/%d = %d, depth %d, stencil %d\n",
getconf(EGL_CONFIG_ID),
getconf(EGL_ALPHA_SIZE),
getconf(EGL_RED_SIZE),
getconf(EGL_GREEN_SIZE),
getconf(EGL_BLUE_SIZE),
getconf(EGL_BUFFER_SIZE),
getconf(EGL_DEPTH_SIZE),
getconf(EGL_STENCIL_SIZE));
}
m_context = eglCreateContext(m_display, m_config, EGL_NO_CONTEXT, context_attribs);
FAIL_IF(!m_context, "failed to create context");
EGLBoolean ok = eglMakeCurrent(m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, m_context);
FAIL_IF(!ok, "eglMakeCurrent() failed");
}
EglState::~EglState()
{
eglMakeCurrent(m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglTerminate(m_display);
}
EglSurface::EglSurface(const EglState &egl, void *native_window)
: egl(egl)
{
esurface = eglCreateWindowSurface(egl.display(), egl.config(), (EGLNativeWindowType)native_window, NULL);
FAIL_IF(esurface == EGL_NO_SURFACE, "failed to create egl surface");
}
EglSurface::~EglSurface()
{
eglDestroySurface(egl.display(), esurface);
}
void EglSurface::make_current()
{
EGLBoolean ok = eglMakeCurrent(egl.display(), esurface, esurface, egl.context());
FAIL_IF(!ok, "eglMakeCurrent() failed");
}
void EglSurface::swap_buffers()
{
EGLBoolean ok = eglSwapBuffers(egl.display(), esurface);
FAIL_IF(!ok, "eglMakeCurrent() failed");
}
<commit_msg>kmscube: improve egl config prints<commit_after>#include "cube-egl.h"
#include "cube.h"
#include <kms++util/kms++util.h>
using namespace std;
static void print_egl_config(EGLDisplay dpy, EGLConfig cfg)
{
auto getconf = [dpy, cfg](EGLint a) { EGLint v = -1; eglGetConfigAttrib(dpy, cfg, a, &v); return v; };
printf("EGL Config %d: color buf %d/%d/%d/%d = %d, depth %d, stencil %d, native visualid %d, native visualtype %d\n",
getconf(EGL_CONFIG_ID),
getconf(EGL_ALPHA_SIZE),
getconf(EGL_RED_SIZE),
getconf(EGL_GREEN_SIZE),
getconf(EGL_BLUE_SIZE),
getconf(EGL_BUFFER_SIZE),
getconf(EGL_DEPTH_SIZE),
getconf(EGL_STENCIL_SIZE),
getconf(EGL_NATIVE_VISUAL_ID),
getconf(EGL_NATIVE_VISUAL_TYPE));
}
EglState::EglState(void *native_display)
{
EGLBoolean b;
EGLint major, minor, n;
static const EGLint context_attribs[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
static const EGLint config_attribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 0,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_NONE
};
m_display = eglGetDisplay((EGLNativeDisplayType)native_display);
FAIL_IF(!m_display, "failed to get egl display");
b = eglInitialize(m_display, &major, &minor);
FAIL_IF(!b, "failed to initialize");
if (s_verbose) {
printf("Using display %p with EGL version %d.%d\n", m_display, major, minor);
printf("EGL_VENDOR: %s\n", eglQueryString(m_display, EGL_VENDOR));
printf("EGL_VERSION: %s\n", eglQueryString(m_display, EGL_VERSION));
printf("EGL_EXTENSIONS: %s\n", eglQueryString(m_display, EGL_EXTENSIONS));
printf("EGL_CLIENT_APIS: %s\n", eglQueryString(m_display, EGL_CLIENT_APIS));
}
b = eglBindAPI(EGL_OPENGL_ES_API);
FAIL_IF(!b, "failed to bind api EGL_OPENGL_ES_API");
if (s_verbose) {
EGLint numConfigs;
b = eglGetConfigs(m_display, nullptr, 0, &numConfigs);
FAIL_IF(!b, "failed to get number of configs");
EGLConfig configs[numConfigs];
b = eglGetConfigs(m_display, configs, numConfigs, &numConfigs);
printf("Available configs:\n");
for (int i = 0; i < numConfigs; ++i)
print_egl_config(m_display, configs[i]);
}
b = eglChooseConfig(m_display, config_attribs, &m_config, 1, &n);
FAIL_IF(!b || n != 1, "failed to choose config");
if (s_verbose) {
printf("Chosen config:\n");
print_egl_config(m_display, m_config);
}
m_context = eglCreateContext(m_display, m_config, EGL_NO_CONTEXT, context_attribs);
FAIL_IF(!m_context, "failed to create context");
EGLBoolean ok = eglMakeCurrent(m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, m_context);
FAIL_IF(!ok, "eglMakeCurrent() failed");
}
EglState::~EglState()
{
eglMakeCurrent(m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglTerminate(m_display);
}
EglSurface::EglSurface(const EglState &egl, void *native_window)
: egl(egl)
{
esurface = eglCreateWindowSurface(egl.display(), egl.config(), (EGLNativeWindowType)native_window, NULL);
FAIL_IF(esurface == EGL_NO_SURFACE, "failed to create egl surface");
}
EglSurface::~EglSurface()
{
eglDestroySurface(egl.display(), esurface);
}
void EglSurface::make_current()
{
EGLBoolean ok = eglMakeCurrent(egl.display(), esurface, esurface, egl.context());
FAIL_IF(!ok, "eglMakeCurrent() failed");
}
void EglSurface::swap_buffers()
{
EGLBoolean ok = eglSwapBuffers(egl.display(), esurface);
FAIL_IF(!ok, "eglMakeCurrent() failed");
}
<|endoftext|>
|
<commit_before>/*
* MissionTerminalImplementation.cpp
*
* Created on: 03/05/11
* Author: polonel
*/
#include "MissionTerminal.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/packets/scene/AttributeListMessage.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/objects/region/CityRegion.h"
#include "server/zone/objects/player/sessions/SlicingSession.h"
void MissionTerminalImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) {
CityRegion* city = player->getCityRegion();
if(city != NULL && city->isMayor(player->getObjectID())){
menuResponse->addRadialMenuItem(72, 3, "Remove");
}
}
int MissionTerminalImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {
if (selectedID == 69) {
if (player->containsActiveSession(SessionFacadeType::SLICING)) {
player->sendSystemMessage("@slicing/slicing:already_slicing");
return 0;
}
if (!player->checkCooldownRecovery("slicing.terminal")) {
player->sendSystemMessage("@slicing/slicing:not_again");
return 0;
}
//Create Session
ManagedReference<SlicingSession*> session = new SlicingSession(player);
session->initalizeSlicingMenu(player, _this);
return 0;
}
else if (selectedID == 72) {
CityRegion* city = player->getCityRegion();
if (city != NULL)
city->removeMissionTerminal(_this);
_this->destroyObjectFromWorld(true);
_this->destroyObjectFromDatabase(false);
}
else
return TangibleObjectImplementation::handleObjectMenuSelect(player, selectedID);
}
<commit_msg>[Fixed] Mission Terminal Warning<commit_after>/*
* MissionTerminalImplementation.cpp
*
* Created on: 03/05/11
* Author: polonel
*/
#include "MissionTerminal.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/packets/scene/AttributeListMessage.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/objects/region/CityRegion.h"
#include "server/zone/objects/player/sessions/SlicingSession.h"
void MissionTerminalImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) {
CityRegion* city = player->getCityRegion();
if(city != NULL && city->isMayor(player->getObjectID())){
menuResponse->addRadialMenuItem(72, 3, "Remove");
}
}
int MissionTerminalImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {
if (selectedID == 69) {
if (player->containsActiveSession(SessionFacadeType::SLICING)) {
player->sendSystemMessage("@slicing/slicing:already_slicing");
return 0;
}
if (!player->checkCooldownRecovery("slicing.terminal")) {
player->sendSystemMessage("@slicing/slicing:not_again");
return 0;
}
//Create Session
ManagedReference<SlicingSession*> session = new SlicingSession(player);
session->initalizeSlicingMenu(player, _this);
return 0;
}
if (selectedID == 72) {
CityRegion* city = player->getCityRegion();
if (city != NULL)
city->removeMissionTerminal(_this);
_this->destroyObjectFromWorld(true);
_this->destroyObjectFromDatabase(false);
return 0;
}
return TangibleObjectImplementation::handleObjectMenuSelect(player, selectedID);
}
<|endoftext|>
|
<commit_before>/* Copyright 2013 - 2014 Yurii Litvinov, CyberTech Labs Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#include "servoMotor.h"
#include <trikKernel/configurer.h>
#include <trikHal/hardwareAbstractionInterface.h>
#include <QsLog.h>
#include "configurerHelper.h"
using namespace trikControl;
ServoMotor::ServoMotor(const QString &port, const trikKernel::Configurer &configurer
, const trikHal::HardwareAbstractionInterface &hardwareAbstraction)
: mDutyFile(hardwareAbstraction.createOutputDeviceFile(configurer.attributeByPort(port, "deviceFile")))
, mPeriodFile(hardwareAbstraction.createOutputDeviceFile(configurer.attributeByPort(port, "periodFile")))
, mRunFile(hardwareAbstraction.createOutputDeviceFile(configurer.attributeByPort(port, "runFile")))
, mRun(false)
, mCurrentDutyPercent(0)
, mInvert(configurer.attributeByPort(port, "invert") == "true")
, mCurrentPower(0)
, mState("Servomotor on " + port)
{
const auto configure = [this, &port, &configurer](const QString ¶meterName) {
return ConfigurerHelper::configureInt(configurer, mState, port, parameterName);
};
mPeriod = configure("period");
mMin = configure("min");
mMax = configure("max");
mZero = configure("zero");
mStop = configure("stop");
mMinControlRange = configure("controlMin");
mMaxControlRange = configure("controlMax");
if (!mPeriodFile->open()) {
mState.fail();
return;
}
if (!mRunFile->open()) {
mState.fail();
return;
} else {
mRunFile->write(QString::number(mRun));
}
const QString command = QString::number(mPeriod);
mPeriodFile->write(command);
mPeriodFile->close();
if (!mDutyFile->open()) {
mState.fail();
} else {
mState.ready();
}
}
ServoMotor::~ServoMotor()
{
}
ServoMotor::Status ServoMotor::status() const
{
return mState.status();
}
int ServoMotor::minControl() const
{
return mMinControlRange;
}
int ServoMotor::maxControl() const
{
return mMaxControlRange;
}
int ServoMotor::power() const
{
return mCurrentPower;
}
int ServoMotor::frequency() const
{
return 1000000000.0 / static_cast<qreal>(mPeriod);
}
int ServoMotor::duty() const
{
return mCurrentDutyPercent;
}
void ServoMotor::powerOff()
{
if (!mState.isReady()) {
QLOG_ERROR() << "Trying to power off motor which is not ready, ignoring";
return;
}
mDutyFile->write(QString::number(mStop));
mCurrentPower = 0;
mRun = false;
mRunFile->write(QString::number(mRun));
}
void ServoMotor::setPower(int power, bool constrain)
{
if (!mState.isReady()) {
QLOG_ERROR() << "Trying to turn on motor which is not ready, ignoring";
return;
}
if (!mRun) {
mRun = true;
mRunFile->write(QString::number(mRun));
}
if (constrain) {
if (power > mMaxControlRange) {
power = mMaxControlRange;
} else if (power < mMinControlRange) {
power = mMinControlRange;
}
}
mCurrentPower = power;
const int meanControlRange = (mMaxControlRange + mMinControlRange) / 2;
power = (mInvert ? -1 : 1) * (power - meanControlRange) + meanControlRange;
const int range = power <= meanControlRange ? mZero - mMin : mMax - mZero;
const qreal powerFactor = static_cast<qreal>(range) / (mMaxControlRange - mMinControlRange) * 2;
const int duty = static_cast<int>(mZero + (power - meanControlRange) * powerFactor);
const QString command = QString::number(duty);
mCurrentDutyPercent = 100 * duty / mPeriod;
mDutyFile->write(command);
}
<commit_msg>Some changes in motor running<commit_after>/* Copyright 2013 - 2014 Yurii Litvinov, CyberTech Labs Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#include "servoMotor.h"
#include <trikKernel/configurer.h>
#include <trikHal/hardwareAbstractionInterface.h>
#include <QsLog.h>
#include "configurerHelper.h"
using namespace trikControl;
ServoMotor::ServoMotor(const QString &port, const trikKernel::Configurer &configurer
, const trikHal::HardwareAbstractionInterface &hardwareAbstraction)
: mDutyFile(hardwareAbstraction.createOutputDeviceFile(configurer.attributeByPort(port, "deviceFile")))
, mPeriodFile(hardwareAbstraction.createOutputDeviceFile(configurer.attributeByPort(port, "periodFile")))
, mRunFile(hardwareAbstraction.createOutputDeviceFile(configurer.attributeByPort(port, "runFile")))
, mRun(false)
, mCurrentDutyPercent(0)
, mInvert(configurer.attributeByPort(port, "invert") == "true")
, mCurrentPower(0)
, mState("Servomotor on " + port)
{
const auto configure = [this, &port, &configurer](const QString ¶meterName) {
return ConfigurerHelper::configureInt(configurer, mState, port, parameterName);
};
mPeriod = configure("period");
mMin = configure("min");
mMax = configure("max");
mZero = configure("zero");
mStop = configure("stop");
mMinControlRange = configure("controlMin");
mMaxControlRange = configure("controlMax");
if (!mPeriodFile->open()) {
mState.fail();
return;
}
if (!mRunFile->open()) {
mState.fail();
return;
} else {
mRunFile->write(QString::number(mRun));
}
const QString command = QString::number(mPeriod);
mPeriodFile->write(command);
mPeriodFile->close();
if (!mDutyFile->open()) {
mState.fail();
} else {
mState.ready();
}
}
ServoMotor::~ServoMotor()
{
}
ServoMotor::Status ServoMotor::status() const
{
return mState.status();
}
int ServoMotor::minControl() const
{
return mMinControlRange;
}
int ServoMotor::maxControl() const
{
return mMaxControlRange;
}
int ServoMotor::power() const
{
return mCurrentPower;
}
int ServoMotor::frequency() const
{
return 1000000000.0 / static_cast<qreal>(mPeriod);
}
int ServoMotor::duty() const
{
return mCurrentDutyPercent;
}
void ServoMotor::powerOff()
{
if (!mState.isReady()) {
QLOG_ERROR() << "Trying to power off motor which is not ready, ignoring";
return;
}
mDutyFile->write(QString::number(mStop));
mCurrentPower = 0;
mRun = false;
mRunFile->write(QString::number(mRun));
}
void ServoMotor::setPower(int power, bool constrain)
{
if (!mState.isReady()) {
QLOG_ERROR() << "Trying to turn on motor which is not ready, ignoring";
return;
}
if (constrain) {
if (power > mMaxControlRange) {
power = mMaxControlRange;
} else if (power < mMinControlRange) {
power = mMinControlRange;
}
}
mCurrentPower = power;
const int meanControlRange = (mMaxControlRange + mMinControlRange) / 2;
power = (mInvert ? -1 : 1) * (power - meanControlRange) + meanControlRange;
const int range = power <= meanControlRange ? mZero - mMin : mMax - mZero;
const qreal powerFactor = static_cast<qreal>(range) / (mMaxControlRange - mMinControlRange) * 2;
const int duty = static_cast<int>(mZero + (power - meanControlRange) * powerFactor);
const QString command = QString::number(duty);
mCurrentDutyPercent = 100 * duty / mPeriod;
mDutyFile->write(command);
if (!mRun) {
mRun = true;
mRunFile->write(QString::number(mRun));
}
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name: stcdlg.cpp
// Purpose: Implementation of class wxExSTCEntryDialog
// Author: Anton van Wezenbeek
// Created: 2009-11-18
// RCS-ID: $Id$
// Copyright: (c) 2009 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/stcdlg.h>
#include <wx/extension/stc.h>
#if wxUSE_GUI
BEGIN_EVENT_TABLE(wxExSTCEntryDialog, wxExDialog)
EVT_MENU(wxID_FIND, wxExSTCEntryDialog::OnCommand)
EVT_MENU(wxID_REPLACE, wxExSTCEntryDialog::OnCommand)
END_EVENT_TABLE()
wxExSTCEntryDialog::wxExSTCEntryDialog(wxWindow* parent,
const wxString& caption,
const wxString& text,
const wxString& prompt,
long button_style,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style)
: wxExDialog(parent, caption, button_style, id, pos, size, style)
{
if (!prompt.empty())
{
AddUserSizer(CreateTextSizer(prompt), wxSizerFlags().Center());
}
wxFlexGridSizer* sizer = new wxFlexGridSizer(0);
sizer->AddGrowableRow(0);
sizer->AddGrowableCol(0);
m_STC = new wxExSTC(
this,
text,
0,
wxEmptyString, // title
wxExSTC::STC_MENU_SIMPLE |
wxExSTC::STC_MENU_FIND |
wxExSTC::STC_MENU_REPLACE,
wxID_ANY,
wxDefaultPosition);
m_STC->SetEdgeMode(wxSTC_EDGE_NONE);
m_STC->ResetMargins();
m_STC->SetViewEOL(false);
m_STC->SetViewWhiteSpace(wxSTC_WS_INVISIBLE);
if ((button_style & wxCANCEL) == 0 &&
(button_style & wxNO) == 0)
{
// You did not specify one of these buttons,
// so you cannot cancel the operation.
// Therefore make the component readonly.
m_STC->SetReadOnly(true);
}
sizer->Add(m_STC, wxSizerFlags().Center().Border().Expand());
AddUserSizer(sizer);
LayoutSizers();
}
const wxExLexer* wxExSTCEntryDialog::GetLexer() const
{
return &m_STC->GetLexer();
}
const wxString wxExSTCEntryDialog::GetText() const
{
return m_STC->GetText();
}
const wxCharBuffer wxExSTCEntryDialog::GetTextRaw() const
{
return m_STC->GetTextRaw();
}
void wxExSTCEntryDialog::OnCommand(wxCommandEvent& command)
{
switch (command.GetId())
{
// Without these, events are not handled by the frame.
case wxID_FIND:
case wxID_REPLACE:
wxPostEvent(wxTheApp->GetTopWindow(), command);
break;
default: wxFAIL;
}
}
bool wxExSTCEntryDialog::SetLexer(const wxString& lexer)
{
return m_STC->SetLexer(lexer);
}
void wxExSTCEntryDialog::SetText(const wxString& text)
{
const bool readonly = m_STC->GetReadOnly();
if (readonly)
{
m_STC->SetReadOnly(false);
}
m_STC->SetText(text);
if (readonly)
{
m_STC->SetReadOnly(true);
}
}
void wxExSTCEntryDialog::UpdateFromConfig()
{
m_STC->ConfigGet();
}
#endif // wxUSE_GUI
<commit_msg>sizer is not needed<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name: stcdlg.cpp
// Purpose: Implementation of class wxExSTCEntryDialog
// Author: Anton van Wezenbeek
// Created: 2009-11-18
// RCS-ID: $Id$
// Copyright: (c) 2009 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/stcdlg.h>
#include <wx/extension/stc.h>
#if wxUSE_GUI
BEGIN_EVENT_TABLE(wxExSTCEntryDialog, wxExDialog)
EVT_MENU(wxID_FIND, wxExSTCEntryDialog::OnCommand)
EVT_MENU(wxID_REPLACE, wxExSTCEntryDialog::OnCommand)
END_EVENT_TABLE()
wxExSTCEntryDialog::wxExSTCEntryDialog(wxWindow* parent,
const wxString& caption,
const wxString& text,
const wxString& prompt,
long button_style,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style)
: wxExDialog(parent, caption, button_style, id, pos, size, style)
{
if (!prompt.empty())
{
AddUserSizer(CreateTextSizer(prompt), wxSizerFlags().Center());
}
m_STC = new wxExSTC(
this,
text,
0,
wxEmptyString, // title
wxExSTC::STC_MENU_SIMPLE |
wxExSTC::STC_MENU_FIND |
wxExSTC::STC_MENU_REPLACE,
wxID_ANY,
wxDefaultPosition);
m_STC->SetEdgeMode(wxSTC_EDGE_NONE);
m_STC->ResetMargins();
m_STC->SetViewEOL(false);
m_STC->SetViewWhiteSpace(wxSTC_WS_INVISIBLE);
if ((button_style & wxCANCEL) == 0 &&
(button_style & wxNO) == 0)
{
// You did not specify one of these buttons,
// so you cannot cancel the operation.
// Therefore make the component readonly.
m_STC->SetReadOnly(true);
}
AddUserSizer(m_STC);
LayoutSizers();
}
const wxExLexer* wxExSTCEntryDialog::GetLexer() const
{
return &m_STC->GetLexer();
}
const wxString wxExSTCEntryDialog::GetText() const
{
return m_STC->GetText();
}
const wxCharBuffer wxExSTCEntryDialog::GetTextRaw() const
{
return m_STC->GetTextRaw();
}
void wxExSTCEntryDialog::OnCommand(wxCommandEvent& command)
{
switch (command.GetId())
{
// Without these, events are not handled by the frame.
case wxID_FIND:
case wxID_REPLACE:
wxPostEvent(wxTheApp->GetTopWindow(), command);
break;
default: wxFAIL;
}
}
bool wxExSTCEntryDialog::SetLexer(const wxString& lexer)
{
return m_STC->SetLexer(lexer);
}
void wxExSTCEntryDialog::SetText(const wxString& text)
{
const bool readonly = m_STC->GetReadOnly();
if (readonly)
{
m_STC->SetReadOnly(false);
}
m_STC->SetText(text);
if (readonly)
{
m_STC->SetReadOnly(true);
}
}
void wxExSTCEntryDialog::UpdateFromConfig()
{
m_STC->ConfigGet();
}
#endif // wxUSE_GUI
<|endoftext|>
|
<commit_before>//
// Demo showing H -> ZZ -> 4 mu generated by Pythia.
// Requires libPythia6.
//==============================================================================
// Constants.
//------------------------------------------------------------------------------
const Double_t kR_min = 240;
const Double_t kR_max = 250;
const Double_t kZ_d = 300;
// Solenoid field along z, in Tesla.
const Double_t kMagField = 4;
// Color for Higgs, Zs and muons
const Color_t kColors[3] = { kRed, kGreen, kYellow };
//==============================================================================
// Global variables.
//------------------------------------------------------------------------------
class TPythia6;
TPythia6 *g_pythia = 0;
// Implemented in MultiView.C
class MultiView;
MultiView* gMultiView = 0;
TEveTrackList *gTrackList = 0;
//==============================================================================
// Forward decalarations of CINT functions.
//------------------------------------------------------------------------------
void pythia_next_event();
void pythia_make_gui();
//==============================================================================
// Main - pythia_display()
//------------------------------------------------------------------------------
void pythia_display()
{
const TString weh("pythia_display()");
if (g_pythia != 0)
{
Warning(weh, "Already initialized.");
return;
}
if (gSystem->Load("libPythia6") < 0)
{
Error(weh, "Could not load 'libPythia6', make sure it is available!");
return;
}
gSystem->Load("libEGPythia6");
if (gROOT->LoadMacro("MultiView.C+") != 0)
{
Error(weh, "Failed loading MultiView.C in compiled mode.");
return;
}
//========================================================================
//========================================================================
// Create an instance of the Pythia event generator ...
g_pythia = new TPythia6;
TPythia6& P = * g_pythia;
P.SetMSEL(0); // full user controll;
P.SetMSUB(102, 1); // g + g -> H0
//P.SetMSUB(123, 1); // f + f' -> f + f' + H0
//P.SetMSUB(124, 1); // f + f' -> f" + f"' + H0
P.SetPMAS(6, 1, 175); // mass of TOP
P.SetPMAS(25, 1, 180); // mass of Higgs
P.SetCKIN(1, 170.0); // range of allowed mass
P.SetCKIN(2, 190.0);
P.SetMSTP(61, 0); // switch off ISR
P.SetMSTP(71, 0); // switch off FSR
P.SetMSTP(81, 0); // switch off multiple interactions
P.SetMSTP(111, 0); // Switch off fragmentation
// Force h0 -> ZZ
for (Int_t i = 210; i <= 288; ++i)
P.SetMDME(i, 1, 0);
P.SetMDME(225, 1, 1);
// Force Z -> mumu
for (Int_t i = 174; i <= 189; ++i)
P.SetMDME(i, 1, 0);
P.SetMDME(184, 1, 1);
P.Initialize("cms", "p", "p", 14000);
//========================================================================
// Create views and containers.
//========================================================================
TEveManager::Create();
TEveElementList *fake_geom = new TEveElementList("Geometry");
TEveGeoShape *b;
b = new TEveGeoShape("Barell 1");
b->SetShape(new TGeoTube(kR_min, kR_max, kZ_d));
b->SetMainColor(kCyan);
b->SetMainTransparency(80);
fake_geom->AddElement(b);
b = new TEveGeoShape("Barell 2");
b->SetShape(new TGeoTube(2*kR_min, 2*kR_max, 2*kZ_d));
b->SetMainColor(kPink-3);
b->SetMainTransparency(80);
fake_geom->AddElement(b);
gEve->AddGlobalElement(fake_geom);
gMultiView = new MultiView;
gMultiView->ImportGeomRPhi(fake_geom);
gMultiView->ImportGeomRhoZ(fake_geom);
gEve->GetBrowser()->GetTabRight()->SetTab(1);
gTrackList = new TEveTrackList("Pythia Tracks");
gTrackList->SetMainColor(kYellow);
gTrackList->SetMarkerColor(kRed);
gTrackList->SetMarkerStyle(4);
gTrackList->SetMarkerSize(0.5);
gEve->AddElement(gTrackList);
TEveTrackPropagator* trkProp = gTrackList->GetPropagator();
trkProp->SetMagField(kMagField);
trkProp->SetMaxR(2*kR_max);
trkProp->SetMaxZ(2*kZ_d);
//========================================================================
//========================================================================
pythia_make_gui();
pythia_next_event();
gEve->Redraw3D(kTRUE);
}
//==============================================================================
// Next event
//------------------------------------------------------------------------------
void pythia_next_event()
{
gTrackList->DestroyElements();
TPythia6& P = * g_pythia;
P.GenerateEvent();
int nh = P.GetMSTU(72);
// printf("N = %d, Nhard = %d :: NumSec = %d, separators (%d,%d,%d,%d)\n",
// P.GetN(), nh, P.GetMSTU(70), P.GetMSTU(71), P.GetMSTU(72), P.GetMSTU(73), P.GetMSTU(74));
// 2->2 hard postfrag final
TEveTrackPropagator *trkProp = gTrackList->GetPropagator();
TClonesArray &MC = * (TClonesArray*) P.GetListOfParticles();
for (Int_t i = 0; i < 7; ++i)
{
TMCParticle& p = * MC[nh+i];
TParticle pb(p.GetKF(), p.GetKS(), 0, 0,
p.GetFirstChild()-nh-1, p.GetLastChild()-nh-1,
p.GetPx(), p.GetPy(), p.GetPz(), p.GetEnergy(),
p.GetVx(), p.GetVy(), p.GetVz(), p.GetTime());
TEveTrack* track = new TEveTrack(&pb, i, trkProp);
track->SetName(Form("%s [%d]", pb.GetName(), i));
track->SetStdTitle();
track->SetAttLineAttMarker(gTrackList);
if (i == 0)
track->SetLineColor(kColors[0]);
else if (i <= 2)
track->SetLineColor(kColors[1]);
gTrackList->AddElement(track);
/*
printf("%d - %d %d %d %d %d %d\n", i,
p.GetKF(), p.GetKS(), 0, 0,
p.GetFirstChild()-nh-1, p.GetLastChild()-nh-1);
printf("%d - %f %f %f %f\n", i,
p.GetPx(), p.GetPy(), p.GetPz(), p.GetEnergy(),
printf("%d - %f %f %f %f\n", i,
p.GetVx(), p.GetVy(), p.GetVz(), p.GetTime());
*/
}
gTrackList->MakeTracks();
TEveElement* top = gEve->GetCurrentEvent();
gMultiView->DestroyEventRPhi();
gMultiView->ImportEventRPhi(top);
gMultiView->DestroyEventRhoZ();
gMultiView->ImportEventRhoZ(top);
gEve->Redraw3D();
}
//==============================================================================
// GUI stuff
//------------------------------------------------------------------------------
class EvNavHandler
{
public:
void Fwd()
{
pythia_next_event();
}
void Bck()
{}
};
//______________________________________________________________________________
void pythia_make_gui()
{
// Create minimal GUI for event navigation.
TEveBrowser* browser = gEve->GetBrowser();
browser->StartEmbedding(TRootBrowser::kLeft);
TGMainFrame* frmMain = new TGMainFrame(gClient->GetRoot(), 1000, 600);
frmMain->SetWindowName("XX GUI");
frmMain->SetCleanup(kDeepCleanup);
TGHorizontalFrame* hf = new TGHorizontalFrame(frmMain);
{
TString icondir( Form("%s/icons/", gSystem->Getenv("ROOTSYS")) );
TGPictureButton* b = 0;
EvNavHandler *fh = new EvNavHandler;
b = new TGPictureButton(hf, gClient->GetPicture(icondir + "GoBack.gif"));
b->SetEnabled(kFALSE);
b->SetToolTipText("Go to previous event - not supported.");
hf->AddFrame(b);
b->Connect("Clicked()", "EvNavHandler", fh, "Bck()");
b = new TGPictureButton(hf, gClient->GetPicture(icondir + "GoForward.gif"));
b->SetToolTipText("Generate new event.");
hf->AddFrame(b);
b->Connect("Clicked()", "EvNavHandler", fh, "Fwd()");
}
frmMain->AddFrame(hf);
frmMain->MapSubwindows();
frmMain->Resize();
frmMain->MapWindow();
browser->StopEmbedding();
browser->SetTabTitle("Event Control", 0);
}
<commit_msg>From Bertrand: Do not try to load libPythia6, as it is a static library on Windoze.<commit_after>//
// Demo showing H -> ZZ -> 4 mu generated by Pythia.
// Requires libPythia6.
//==============================================================================
// Constants.
//------------------------------------------------------------------------------
const Double_t kR_min = 240;
const Double_t kR_max = 250;
const Double_t kZ_d = 300;
// Solenoid field along z, in Tesla.
const Double_t kMagField = 4;
// Color for Higgs, Zs and muons
const Color_t kColors[3] = { kRed, kGreen, kYellow };
//==============================================================================
// Global variables.
//------------------------------------------------------------------------------
class TPythia6;
TPythia6 *g_pythia = 0;
// Implemented in MultiView.C
class MultiView;
MultiView* gMultiView = 0;
TEveTrackList *gTrackList = 0;
//==============================================================================
// Forward decalarations of CINT functions.
//------------------------------------------------------------------------------
void pythia_next_event();
void pythia_make_gui();
//==============================================================================
// Main - pythia_display()
//------------------------------------------------------------------------------
void pythia_display()
{
const TString weh("pythia_display()");
if (g_pythia != 0)
{
Warning(weh, "Already initialized.");
return;
}
#ifndef G__WIN32 // libPythia6 is a static library on Windoze
if (gSystem->Load("libPythia6") < 0)
{
Error(weh, "Could not load 'libPythia6', make sure it is available!");
return;
}
#endif
gSystem->Load("libEGPythia6");
if (gROOT->LoadMacro("MultiView.C+") != 0)
{
Error(weh, "Failed loading MultiView.C in compiled mode.");
return;
}
//========================================================================
//========================================================================
// Create an instance of the Pythia event generator ...
g_pythia = new TPythia6;
TPythia6& P = * g_pythia;
P.SetMSEL(0); // full user controll;
P.SetMSUB(102, 1); // g + g -> H0
//P.SetMSUB(123, 1); // f + f' -> f + f' + H0
//P.SetMSUB(124, 1); // f + f' -> f" + f"' + H0
P.SetPMAS(6, 1, 175); // mass of TOP
P.SetPMAS(25, 1, 180); // mass of Higgs
P.SetCKIN(1, 170.0); // range of allowed mass
P.SetCKIN(2, 190.0);
P.SetMSTP(61, 0); // switch off ISR
P.SetMSTP(71, 0); // switch off FSR
P.SetMSTP(81, 0); // switch off multiple interactions
P.SetMSTP(111, 0); // Switch off fragmentation
// Force h0 -> ZZ
for (Int_t i = 210; i <= 288; ++i)
P.SetMDME(i, 1, 0);
P.SetMDME(225, 1, 1);
// Force Z -> mumu
for (Int_t i = 174; i <= 189; ++i)
P.SetMDME(i, 1, 0);
P.SetMDME(184, 1, 1);
P.Initialize("cms", "p", "p", 14000);
//========================================================================
// Create views and containers.
//========================================================================
TEveManager::Create();
TEveElementList *fake_geom = new TEveElementList("Geometry");
TEveGeoShape *b;
b = new TEveGeoShape("Barell 1");
b->SetShape(new TGeoTube(kR_min, kR_max, kZ_d));
b->SetMainColor(kCyan);
b->SetMainTransparency(80);
fake_geom->AddElement(b);
b = new TEveGeoShape("Barell 2");
b->SetShape(new TGeoTube(2*kR_min, 2*kR_max, 2*kZ_d));
b->SetMainColor(kPink-3);
b->SetMainTransparency(80);
fake_geom->AddElement(b);
gEve->AddGlobalElement(fake_geom);
gMultiView = new MultiView;
gMultiView->ImportGeomRPhi(fake_geom);
gMultiView->ImportGeomRhoZ(fake_geom);
gEve->GetBrowser()->GetTabRight()->SetTab(1);
gTrackList = new TEveTrackList("Pythia Tracks");
gTrackList->SetMainColor(kYellow);
gTrackList->SetMarkerColor(kRed);
gTrackList->SetMarkerStyle(4);
gTrackList->SetMarkerSize(0.5);
gEve->AddElement(gTrackList);
TEveTrackPropagator* trkProp = gTrackList->GetPropagator();
trkProp->SetMagField(kMagField);
trkProp->SetMaxR(2*kR_max);
trkProp->SetMaxZ(2*kZ_d);
//========================================================================
//========================================================================
pythia_make_gui();
pythia_next_event();
gEve->Redraw3D(kTRUE);
}
//==============================================================================
// Next event
//------------------------------------------------------------------------------
void pythia_next_event()
{
gTrackList->DestroyElements();
TPythia6& P = * g_pythia;
P.GenerateEvent();
int nh = P.GetMSTU(72);
// printf("N = %d, Nhard = %d :: NumSec = %d, separators (%d,%d,%d,%d)\n",
// P.GetN(), nh, P.GetMSTU(70), P.GetMSTU(71), P.GetMSTU(72), P.GetMSTU(73), P.GetMSTU(74));
// 2->2 hard postfrag final
TEveTrackPropagator *trkProp = gTrackList->GetPropagator();
TClonesArray &MC = * (TClonesArray*) P.GetListOfParticles();
for (Int_t i = 0; i < 7; ++i)
{
TMCParticle& p = * MC[nh+i];
TParticle pb(p.GetKF(), p.GetKS(), 0, 0,
p.GetFirstChild()-nh-1, p.GetLastChild()-nh-1,
p.GetPx(), p.GetPy(), p.GetPz(), p.GetEnergy(),
p.GetVx(), p.GetVy(), p.GetVz(), p.GetTime());
TEveTrack* track = new TEveTrack(&pb, i, trkProp);
track->SetName(Form("%s [%d]", pb.GetName(), i));
track->SetStdTitle();
track->SetAttLineAttMarker(gTrackList);
if (i == 0)
track->SetLineColor(kColors[0]);
else if (i <= 2)
track->SetLineColor(kColors[1]);
gTrackList->AddElement(track);
/*
printf("%d - %d %d %d %d %d %d\n", i,
p.GetKF(), p.GetKS(), 0, 0,
p.GetFirstChild()-nh-1, p.GetLastChild()-nh-1);
printf("%d - %f %f %f %f\n", i,
p.GetPx(), p.GetPy(), p.GetPz(), p.GetEnergy(),
printf("%d - %f %f %f %f\n", i,
p.GetVx(), p.GetVy(), p.GetVz(), p.GetTime());
*/
}
gTrackList->MakeTracks();
TEveElement* top = gEve->GetCurrentEvent();
gMultiView->DestroyEventRPhi();
gMultiView->ImportEventRPhi(top);
gMultiView->DestroyEventRhoZ();
gMultiView->ImportEventRhoZ(top);
gEve->Redraw3D();
}
//==============================================================================
// GUI stuff
//------------------------------------------------------------------------------
class EvNavHandler
{
public:
void Fwd()
{
pythia_next_event();
}
void Bck()
{}
};
//______________________________________________________________________________
void pythia_make_gui()
{
// Create minimal GUI for event navigation.
TEveBrowser* browser = gEve->GetBrowser();
browser->StartEmbedding(TRootBrowser::kLeft);
TGMainFrame* frmMain = new TGMainFrame(gClient->GetRoot(), 1000, 600);
frmMain->SetWindowName("XX GUI");
frmMain->SetCleanup(kDeepCleanup);
TGHorizontalFrame* hf = new TGHorizontalFrame(frmMain);
{
TString icondir( Form("%s/icons/", gSystem->Getenv("ROOTSYS")) );
TGPictureButton* b = 0;
EvNavHandler *fh = new EvNavHandler;
b = new TGPictureButton(hf, gClient->GetPicture(icondir + "GoBack.gif"));
b->SetEnabled(kFALSE);
b->SetToolTipText("Go to previous event - not supported.");
hf->AddFrame(b);
b->Connect("Clicked()", "EvNavHandler", fh, "Bck()");
b = new TGPictureButton(hf, gClient->GetPicture(icondir + "GoForward.gif"));
b->SetToolTipText("Generate new event.");
hf->AddFrame(b);
b->Connect("Clicked()", "EvNavHandler", fh, "Fwd()");
}
frmMain->AddFrame(hf);
frmMain->MapSubwindows();
frmMain->Resize();
frmMain->MapWindow();
browser->StopEmbedding();
browser->SetTabTitle("Event Control", 0);
}
<|endoftext|>
|
<commit_before>/*
Q Light Controller Plus
efxitem.cpp
Copyright (C) Massimo Callegari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <QApplication>
#include <QPainter>
#include <qmath.h>
#include <QDebug>
#include <QMenu>
#include <qmath.h>
#include "efxitem.h"
#include "trackitem.h"
#include "headeritems.h"
#include "audiodecoder.h"
EFXItem::EFXItem(EFX *efx, ShowFunction *func)
: ShowItem(func)
, m_efx(efx)
{
Q_ASSERT(efx != NULL);
if (func->color().isValid())
setColor(func->color());
else
setColor(ShowFunction::defaultColor(Function::EFX));
calculateWidth();
connect(m_efx, SIGNAL(changed(quint32)), this, SLOT(slotEFXChanged(quint32)));
}
void EFXItem::calculateWidth()
{
int newWidth = 0;
qint64 efx_duration = m_function->duration();
if (efx_duration != 0)
newWidth = ((50/(float)getTimeScale()) * (float)efx_duration) / 1000;
else
newWidth = 100;
if (newWidth < (50 / m_timeScale))
newWidth = 50 / m_timeScale;
setWidth(newWidth);
}
void EFXItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
float xpos = 0;
float timeScale = 50/(float)m_timeScale;
quint32 efxDuration = m_efx->totalDuration();
ShowItem::paint(painter, option, widget);
int loopCount = qFloor(m_function->duration() / efxDuration);
for (int i = 0; i < loopCount; i++)
{
xpos += ((timeScale * (float)efxDuration) / 1000);
// draw loop vertical delimiter
painter->setPen(QPen(Qt::white, 1));
painter->drawLine(xpos, 1, xpos, TRACK_HEIGHT - 5);
}
ShowItem::postPaint(painter);
}
void EFXItem::setTimeScale(int val)
{
ShowItem::setTimeScale(val);
calculateWidth();
}
void EFXItem::setDuration(quint32 msec, bool stretch)
{
if (stretch == true)
m_efx->setDuration(msec);
else
{
if (m_function)
m_function->setDuration(msec);
prepareGeometryChange();
calculateWidth();
updateTooltip();
}
}
QString EFXItem::functionName()
{
if (m_efx)
return m_efx->name();
return QString();
}
EFX *EFXItem::getEFX()
{
return m_efx;
}
void EFXItem::slotEFXChanged(quint32)
{
prepareGeometryChange();
if (m_function)
m_function->setDuration(m_efx->totalDuration());
calculateWidth();
updateTooltip();
}
void EFXItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *)
{
QMenu menu;
QFont menuFont = qApp->font();
menuFont.setPixelSize(14);
menu.setFont(menuFont);
foreach(QAction *action, getDefaultActions())
menu.addAction(action);
menu.exec(QCursor::pos());
}
<commit_msg>Fix crash reported in http://www.qlcplus.org/forum/viewtopic.php?f=5&t=9543<commit_after>/*
Q Light Controller Plus
efxitem.cpp
Copyright (C) Massimo Callegari
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <QApplication>
#include <QPainter>
#include <qmath.h>
#include <QDebug>
#include <QMenu>
#include <qmath.h>
#include "efxitem.h"
#include "trackitem.h"
#include "headeritems.h"
#include "audiodecoder.h"
EFXItem::EFXItem(EFX *efx, ShowFunction *func)
: ShowItem(func)
, m_efx(efx)
{
Q_ASSERT(efx != NULL);
if (func->color().isValid())
setColor(func->color());
else
setColor(ShowFunction::defaultColor(Function::EFX));
calculateWidth();
connect(m_efx, SIGNAL(changed(quint32)), this, SLOT(slotEFXChanged(quint32)));
}
void EFXItem::calculateWidth()
{
int newWidth = 0;
qint64 efx_duration = m_function->duration();
if (efx_duration != 0)
newWidth = ((50/(float)getTimeScale()) * (float)efx_duration) / 1000;
else
newWidth = 100;
if (newWidth < (50 / m_timeScale))
newWidth = 50 / m_timeScale;
setWidth(newWidth);
}
void EFXItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
float xpos = 0;
float timeScale = 50/(float)m_timeScale;
quint32 efxDuration = m_efx->totalDuration();
ShowItem::paint(painter, option, widget);
int loopCount = (efxDuration == 0) ? 0 : qFloor(m_function->duration() / efxDuration);
for (int i = 0; i < loopCount; i++)
{
xpos += ((timeScale * (float)efxDuration) / 1000);
// draw loop vertical delimiter
painter->setPen(QPen(Qt::white, 1));
painter->drawLine(xpos, 1, xpos, TRACK_HEIGHT - 5);
}
ShowItem::postPaint(painter);
}
void EFXItem::setTimeScale(int val)
{
ShowItem::setTimeScale(val);
calculateWidth();
}
void EFXItem::setDuration(quint32 msec, bool stretch)
{
if (stretch == true)
m_efx->setDuration(msec);
else
{
if (m_function)
m_function->setDuration(msec);
prepareGeometryChange();
calculateWidth();
updateTooltip();
}
}
QString EFXItem::functionName()
{
if (m_efx)
return m_efx->name();
return QString();
}
EFX *EFXItem::getEFX()
{
return m_efx;
}
void EFXItem::slotEFXChanged(quint32)
{
prepareGeometryChange();
if (m_function)
m_function->setDuration(m_efx->totalDuration());
calculateWidth();
updateTooltip();
}
void EFXItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *)
{
QMenu menu;
QFont menuFont = qApp->font();
menuFont.setPixelSize(14);
menu.setFont(menuFont);
foreach(QAction *action, getDefaultActions())
menu.addAction(action);
menu.exec(QCursor::pos());
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: salbmp.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: pluby $ $Date: 2000-12-31 20:54:10 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#define _SV_SALBMP_CXX
#ifndef _SV_SALBMP_HXX
#include <salbmp.hxx>
#endif
#ifndef _SV_SALBTYPE_HXX
#include <salbtype.hxx>
#endif
// ==================================================================
SalBitmap::SalBitmap() :
mhPixMap( 0 ),
mnBitCount( 0 )
{
}
// ------------------------------------------------------------------
SalBitmap::~SalBitmap()
{
Destroy();
}
// ------------------------------------------------------------------
BOOL SalBitmap::Create( const Size& rSize, USHORT nBitCount, const BitmapPalette& rPal )
{
maSize = rSize;
mnBitCount = nBitCount;
return TRUE;
}
// ------------------------------------------------------------------
BOOL SalBitmap::Create( const SalBitmap& rSalBitmap )
{
maSize = rSalBitmap.maSize;
mnBitCount = 1;
return TRUE;
}
// ------------------------------------------------------------------
BOOL SalBitmap::Create( const SalBitmap& rSalBmp, SalGraphics* pGraphics )
{
maSize = rSalBmp.maSize;
mnBitCount = rSalBmp.mnBitCount;
return TRUE;
}
// ------------------------------------------------------------------
BOOL SalBitmap::Create( const SalBitmap& rSalBmp, USHORT nNewBitCount )
{
maSize = rSalBmp.maSize;
mnBitCount = nNewBitCount;
return TRUE;
}
// ------------------------------------------------------------------
void SalBitmap::Destroy()
{
maSize = Size();
mnBitCount = 0;
}
// ------------------------------------------------------------------
BitmapBuffer* SalBitmap::AcquireBuffer( BOOL bReadOnly )
{
BitmapBuffer *pBuffer = new BitmapBuffer();
// Stub code: we have not yet written any interfaces to native bitmaps.
pBuffer->mnFormat = BMP_FORMAT_BOTTOM_UP | BMP_FORMAT_1BIT_MSB_PAL;
pBuffer->mnWidth = maSize.Width();
pBuffer->mnHeight = maSize.Height();
pBuffer->mnScanlineSize = AlignedWidth4Bytes( pBuffer->mnWidth * mnBitCount );
pBuffer->mnFormat |= BMP_FORMAT_16BIT_TC_MASK;
pBuffer->maColorMask = ColorMask( 0x7b00, 0x03e0, 0x001f);
pBuffer->mpBits = new BYTE[ pBuffer->mnScanlineSize * pBuffer->mnHeight ];
return pBuffer;
}
// ------------------------------------------------------------------
void SalBitmap::ReleaseBuffer( BitmapBuffer* pBuffer, BOOL bReadOnly )
{
delete pBuffer;
}
<commit_msg>Initial implementation of SalBitmap class. At this time, only 32 bit pixel depth is supported.<commit_after>/*************************************************************************
*
* $RCSfile: salbmp.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: pluby $ $Date: 2001-01-05 21:18:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#define _SV_SALBMP_CXX
#ifndef _SV_SALBMP_HXX
#include <salbmp.hxx>
#endif
#ifndef _SV_SALBTYPE_HXX
#include <salbtype.hxx>
#endif
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALVD_HXX
#include <salvd.hxx>
#endif
// ==================================================================
SalBitmap::SalBitmap() :
mpVirDev( 0 ),
mnBitCount( 0 )
{
}
// ------------------------------------------------------------------
SalBitmap::~SalBitmap()
{
Destroy();
}
// ------------------------------------------------------------------
BOOL SalBitmap::Create( const Size& rSize, USHORT nBitCount, const BitmapPalette& rPal )
{
ImplSVData* pSVData = ImplGetSVData();
BOOL bRet = FALSE;
// Stub code: we can only handle 32 bit pixel depth's right now
nBitCount = 32;
if ( rSize.Width() && rSize.Height() )
{
// Create a SalVirtualDevice
mpVirDev = pSVData->mpDefInst->CreateVirtualDevice( NULL,
rSize.Width(), rSize.Height(), nBitCount );
if ( mpVirDev )
{
mnBitCount = nBitCount;
maSize = rSize;
bRet = TRUE;
}
}
return bRet;
}
// ------------------------------------------------------------------
BOOL SalBitmap::Create( const SalBitmap& rSalBmp )
{
BOOL bRet = FALSE;
if ( Create( rSalBmp, rSalBmp.mnBitCount ) )
bRet = TRUE;
return bRet;
}
// ------------------------------------------------------------------
BOOL SalBitmap::Create( const SalBitmap& rSalBmp, SalGraphics* pGraphics )
{
return Create( rSalBmp );
}
// ------------------------------------------------------------------
BOOL SalBitmap::Create( const SalBitmap& rSalBmp, USHORT nNewBitCount )
{
BOOL bRet = FALSE;
if ( Create( rSalBmp.maSize, nNewBitCount, BitmapPalette() ) )
{
// Not yet implemented: Copy pixels from rSalBmp.mpVirDev to mpVirDev
bRet = TRUE;
}
return bRet;
}
// ------------------------------------------------------------------
void SalBitmap::Destroy()
{
ImplSVData* pSVData = ImplGetSVData();
if ( mpVirDev )
pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );
maSize = Size();
mnBitCount = 0;
}
// ------------------------------------------------------------------
BitmapBuffer* SalBitmap::AcquireBuffer( BOOL bReadOnly )
{
BitmapBuffer *pBuffer = NULL;
if ( mpVirDev )
{
// Get the SalGraphics which contains the GWorld we will draw to
SalGraphics *pGraphics = GetGraphics();
if ( pGraphics && pGraphics->maGraphicsData.mpCGrafPort )
{
PixMapHandle hPixMap = NULL;
hPixMap = GetPortPixMap( pGraphics->maGraphicsData.mpCGrafPort );
if ( hPixMap )
{
pBuffer = new BitmapBuffer();
// Lock the GWorld so that the calling functions can write to
// this buffer
LockPortBits( pGraphics->maGraphicsData.mpCGrafPort );
pBuffer->mnBitCount = (**hPixMap).pixelSize;
pBuffer->mnWidth = mpVirDev->maVirDevData.mnWidth;
pBuffer->mnHeight = mpVirDev->maVirDevData.mnHeight;
pBuffer->mnBitCount = (**hPixMap).pixelSize;
pBuffer->mnScanlineSize = GetPixRowBytes( hPixMap );
pBuffer->mpBits = (BYTE *)GetPixBaseAddr( hPixMap );
pBuffer->mnFormat = BMP_FORMAT_TOP_DOWN | BMP_FORMAT_32BIT_TC_MASK;
}
// Release the SalGraphics so that others can get a handle to it
// in future GetGraphics() calls
ReleaseGraphics( pGraphics );
}
}
return pBuffer;
}
// ------------------------------------------------------------------
void SalBitmap::ReleaseBuffer( BitmapBuffer* pBuffer, BOOL bReadOnly )
{
SalGraphics *pGraphics = NULL;
if ( mpVirDev )
{
// Get the SalGraphics which contains the GWorld we used as the buffer
SalGraphics *pGraphics = GetGraphics();
if ( pGraphics && pGraphics->maGraphicsData.mpCGrafPort )
{
// Unlock the GWorld so that this GWorld can be reused
UnlockPortBits( pGraphics->maGraphicsData.mpCGrafPort );
// Release the SalGraphics so that others can get a handle to it
// in future GetGraphics() calls
ReleaseGraphics( pGraphics );
}
}
if ( pBuffer )
delete pBuffer;
}
// ------------------------------------------------------------------
SalGraphics* SalBitmap::GetGraphics()
{
if ( mpVirDev )
return mpVirDev->GetGraphics();
else
return NULL;
}
// ------------------------------------------------------------------
void SalBitmap::ReleaseGraphics( SalGraphics* pGraphics )
{
if ( mpVirDev )
mpVirDev->ReleaseGraphics( pGraphics );
}
<|endoftext|>
|
<commit_before><commit_msg>Don't use uninitialized ImplSplitItem::mnPixSize<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: syschild.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-17 12:21:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#include <window.hxx>
#ifndef _SV_SALOBJ_HXX
#include <salobj.hxx>
#endif
#ifndef _SV_RC_H
#include <tools/rc.h>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_WIDNOW_H
#include <window.h>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_SYSCHILD_HXX
#include <syschild.hxx>
#endif
// =======================================================================
long ImplSysChildProc( void* pInst, SalObject* /* pObject */,
USHORT nEvent, const void* /* pEvent */ )
{
SystemChildWindow* pWindow = (SystemChildWindow*)pInst;
long nRet = 0;
ImplDelData aDogTag( pWindow );
switch ( nEvent )
{
case SALOBJ_EVENT_GETFOCUS:
// Focus holen und zwar so, das alle Handler gerufen
// werden, als ob dieses Fenster den Focus bekommt,
// ohne das der Frame den Focus wieder klaut
pWindow->ImplGetFrameData()->mbSysObjFocus = TRUE;
pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = TRUE;
pWindow->ToTop( TOTOP_NOGRABFOCUS );
if( aDogTag.IsDead() )
break;
pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = FALSE;
pWindow->ImplGetFrameData()->mbInSysObjFocusHdl = TRUE;
pWindow->GrabFocus();
if( aDogTag.IsDead() )
break;
pWindow->ImplGetFrameData()->mbInSysObjFocusHdl = FALSE;
break;
case SALOBJ_EVENT_LOSEFOCUS:
// Hintenrum einen LoseFocus ausloesen, das der Status
// der Fenster dem entsprechenden Activate-Status
// entspricht
pWindow->ImplGetFrameData()->mbSysObjFocus = FALSE;
if ( !pWindow->ImplGetFrameData()->mnFocusId )
{
pWindow->ImplGetFrameData()->mbStartFocusState = TRUE;
Application::PostUserEvent( pWindow->ImplGetFrameData()->mnFocusId, LINK( pWindow->ImplGetFrameWindow(), Window, ImplAsyncFocusHdl ) );
}
break;
case SALOBJ_EVENT_TOTOP:
pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = TRUE;
if ( !Application::GetFocusWindow() || pWindow->HasChildPathFocus() )
pWindow->ToTop( TOTOP_NOGRABFOCUS );
else
pWindow->ToTop();
if( aDogTag.IsDead() )
break;
pWindow->GrabFocus();
if( aDogTag.IsDead() )
break;
pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = FALSE;
break;
}
return nRet;
}
// =======================================================================
void SystemChildWindow::ImplInitSysChild( Window* pParent, WinBits nStyle, SystemWindowData *pData )
{
mpWindowImpl->mpSysObj = ImplGetSVData()->mpDefInst->CreateObject( pParent->ImplGetFrame(), pData );
Window::ImplInit( pParent, nStyle, NULL );
// Wenn es ein richtiges SysChild ist, dann painten wir auch nicht
if ( GetSystemData() )
{
mpWindowImpl->mpSysObj->SetCallback( this, ImplSysChildProc );
SetParentClipMode( PARENTCLIPMODE_CLIP );
SetBackground();
}
}
// -----------------------------------------------------------------------
SystemChildWindow::SystemChildWindow( Window* pParent, WinBits nStyle ) :
Window( WINDOW_SYSTEMCHILDWINDOW )
{
ImplInitSysChild( pParent, nStyle, NULL );
}
// -----------------------------------------------------------------------
SystemChildWindow::SystemChildWindow( Window* pParent, WinBits nStyle, SystemWindowData *pData ) :
Window( WINDOW_SYSTEMCHILDWINDOW )
{
ImplInitSysChild( pParent, nStyle, pData );
}
// -----------------------------------------------------------------------
SystemChildWindow::SystemChildWindow( Window* pParent, const ResId& rResId ) :
Window( WINDOW_SYSTEMCHILDWINDOW )
{
rResId.SetRT( RSC_WINDOW );
WinBits nStyle = ImplInitRes( rResId );
ImplInitSysChild( pParent, nStyle, NULL );
ImplLoadRes( rResId );
if ( !(nStyle & WB_HIDE) )
Show();
}
// -----------------------------------------------------------------------
SystemChildWindow::~SystemChildWindow()
{
Hide();
if ( mpWindowImpl->mpSysObj )
{
ImplGetSVData()->mpDefInst->DestroyObject( mpWindowImpl->mpSysObj );
mpWindowImpl->mpSysObj = NULL;
}
}
// -----------------------------------------------------------------------
const SystemEnvData* SystemChildWindow::GetSystemData() const
{
if ( mpWindowImpl->mpSysObj )
return mpWindowImpl->mpSysObj->GetSystemData();
else
return NULL;
}
// -----------------------------------------------------------------------
void SystemChildWindow::EnableEraseBackground( BOOL bEnable )
{
if ( mpWindowImpl->mpSysObj )
mpWindowImpl->mpSysObj->EnableEraseBackground( bEnable );
}
BOOL SystemChildWindow::IsEraseBackgroundEnabled()
{
if ( mpWindowImpl->mpSysObj )
return mpWindowImpl->mpSysObj->IsEraseBackgroundEnabled();
else
return FALSE;
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.9.240); FILE MERGED 2007/06/04 13:29:48 vg 1.9.240.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: syschild.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2007-06-27 20:34:11 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALINST_HXX
#include <vcl/salinst.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <vcl/salframe.hxx>
#endif
#include <vcl/window.hxx>
#ifndef _SV_SALOBJ_HXX
#include <vcl/salobj.hxx>
#endif
#ifndef _SV_RC_H
#include <tools/rc.h>
#endif
#ifndef _SV_SVDATA_HXX
#include <vcl/svdata.hxx>
#endif
#ifndef _SV_WIDNOW_H
#include <window.h>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_SYSCHILD_HXX
#include <vcl/syschild.hxx>
#endif
// =======================================================================
long ImplSysChildProc( void* pInst, SalObject* /* pObject */,
USHORT nEvent, const void* /* pEvent */ )
{
SystemChildWindow* pWindow = (SystemChildWindow*)pInst;
long nRet = 0;
ImplDelData aDogTag( pWindow );
switch ( nEvent )
{
case SALOBJ_EVENT_GETFOCUS:
// Focus holen und zwar so, das alle Handler gerufen
// werden, als ob dieses Fenster den Focus bekommt,
// ohne das der Frame den Focus wieder klaut
pWindow->ImplGetFrameData()->mbSysObjFocus = TRUE;
pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = TRUE;
pWindow->ToTop( TOTOP_NOGRABFOCUS );
if( aDogTag.IsDead() )
break;
pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = FALSE;
pWindow->ImplGetFrameData()->mbInSysObjFocusHdl = TRUE;
pWindow->GrabFocus();
if( aDogTag.IsDead() )
break;
pWindow->ImplGetFrameData()->mbInSysObjFocusHdl = FALSE;
break;
case SALOBJ_EVENT_LOSEFOCUS:
// Hintenrum einen LoseFocus ausloesen, das der Status
// der Fenster dem entsprechenden Activate-Status
// entspricht
pWindow->ImplGetFrameData()->mbSysObjFocus = FALSE;
if ( !pWindow->ImplGetFrameData()->mnFocusId )
{
pWindow->ImplGetFrameData()->mbStartFocusState = TRUE;
Application::PostUserEvent( pWindow->ImplGetFrameData()->mnFocusId, LINK( pWindow->ImplGetFrameWindow(), Window, ImplAsyncFocusHdl ) );
}
break;
case SALOBJ_EVENT_TOTOP:
pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = TRUE;
if ( !Application::GetFocusWindow() || pWindow->HasChildPathFocus() )
pWindow->ToTop( TOTOP_NOGRABFOCUS );
else
pWindow->ToTop();
if( aDogTag.IsDead() )
break;
pWindow->GrabFocus();
if( aDogTag.IsDead() )
break;
pWindow->ImplGetFrameData()->mbInSysObjToTopHdl = FALSE;
break;
}
return nRet;
}
// =======================================================================
void SystemChildWindow::ImplInitSysChild( Window* pParent, WinBits nStyle, SystemWindowData *pData )
{
mpWindowImpl->mpSysObj = ImplGetSVData()->mpDefInst->CreateObject( pParent->ImplGetFrame(), pData );
Window::ImplInit( pParent, nStyle, NULL );
// Wenn es ein richtiges SysChild ist, dann painten wir auch nicht
if ( GetSystemData() )
{
mpWindowImpl->mpSysObj->SetCallback( this, ImplSysChildProc );
SetParentClipMode( PARENTCLIPMODE_CLIP );
SetBackground();
}
}
// -----------------------------------------------------------------------
SystemChildWindow::SystemChildWindow( Window* pParent, WinBits nStyle ) :
Window( WINDOW_SYSTEMCHILDWINDOW )
{
ImplInitSysChild( pParent, nStyle, NULL );
}
// -----------------------------------------------------------------------
SystemChildWindow::SystemChildWindow( Window* pParent, WinBits nStyle, SystemWindowData *pData ) :
Window( WINDOW_SYSTEMCHILDWINDOW )
{
ImplInitSysChild( pParent, nStyle, pData );
}
// -----------------------------------------------------------------------
SystemChildWindow::SystemChildWindow( Window* pParent, const ResId& rResId ) :
Window( WINDOW_SYSTEMCHILDWINDOW )
{
rResId.SetRT( RSC_WINDOW );
WinBits nStyle = ImplInitRes( rResId );
ImplInitSysChild( pParent, nStyle, NULL );
ImplLoadRes( rResId );
if ( !(nStyle & WB_HIDE) )
Show();
}
// -----------------------------------------------------------------------
SystemChildWindow::~SystemChildWindow()
{
Hide();
if ( mpWindowImpl->mpSysObj )
{
ImplGetSVData()->mpDefInst->DestroyObject( mpWindowImpl->mpSysObj );
mpWindowImpl->mpSysObj = NULL;
}
}
// -----------------------------------------------------------------------
const SystemEnvData* SystemChildWindow::GetSystemData() const
{
if ( mpWindowImpl->mpSysObj )
return mpWindowImpl->mpSysObj->GetSystemData();
else
return NULL;
}
// -----------------------------------------------------------------------
void SystemChildWindow::EnableEraseBackground( BOOL bEnable )
{
if ( mpWindowImpl->mpSysObj )
mpWindowImpl->mpSysObj->EnableEraseBackground( bEnable );
}
BOOL SystemChildWindow::IsEraseBackgroundEnabled()
{
if ( mpWindowImpl->mpSysObj )
return mpWindowImpl->mpSysObj->IsEraseBackgroundEnabled();
else
return FALSE;
}
<|endoftext|>
|
<commit_before>#include <sstream>
#include <string>
#include "codegen.hpp"
//
// NOTE: This file is autogenerated based on the tac-definition.
// You should therefore not edit it manually.
//
using namespace std;
using namespace bohrium::core;
namespace bohrium{
namespace engine{
namespace cpu{
namespace codegen{
string Walker::oper_neutral_element(OPERATOR oper, ETYPE etype)
{
switch(oper) {
case ADD: return "0";
case MULTIPLY: return "1";
case MAXIMUM:
switch(etype) {
case BOOL: return "0";
case INT8: return "INT8_MIN";
case INT16: return "INT16_MIN";
case INT32: return "INT32_MIN";
case INT64: return "INT64_MIN";
case UINT8: return "UINT8_MIN";
case UINT16: return "UINT16_MIN";
case UINT32: return "UINT32_MIN";
case UINT64: return "UINT64_MIN";
case FLOAT32: return "FLT_MIN";
case FLOAT64: return "DBL_MIN";
default: return "UNKNOWN_NEUTRAL_FOR_MAXIMUM_OF_GIVEN_TYPE";
}
case MINIMUM:
switch(etype) {
case BOOL: return "1";
case INT8: return "INT8_MAX";
case INT16: return "INT16_MAX";
case INT32: return "INT32_MAX";
case INT64: return "INT64_MAX";
case UINT8: return "UINT8_MAX";
case UINT16: return "UINT16_MAX";
case UINT32: return "UINT32_MAX";
case UINT64: return "UINT64_MAX";
case FLOAT32: return "FLT_MAX";
case FLOAT64: return "DBL_MAX";
default: return "UNKNOWN_NEUTRAL_FOR_MINIMUM_OF_GIVEN_TYPE";
}
case LOGICAL_AND: return "1";
case LOGICAL_OR: return "0";
case LOGICAL_XOR: return "0";
case BITWISE_AND: return "1";
switch(etype) {
case BOOL: return "1";
case INT8: return "-1";
case INT16: return "-1";
case INT32: return "-1";
case INT64: return "-1";
case UINT8: return "UINT8_MAX";
case UINT16: return "UINT16_MAX";
case UINT32: return "UINT32_MAX";
case UINT64: return "UINT64_MAX";
default: return "UNKNOWN_NEUTRAL_FOR_BITWISE_AND_OF_GIVEN_TYPE";
}
case BITWISE_OR: return "0";
case BITWISE_XOR: return "0";
default: return "UNKNOWN_NEUTRAL_FOR_OPERATOR";
}
}
string Walker::oper_description(tac_t tac)
{
stringstream ss;
ss << operator_text(tac.oper) << " (";
switch(core::tac_noperands(tac)) {
case 3:
ss << layout_text(kernel_.operand_glb(tac.out).meta().layout);
ss << ", ";
ss << layout_text(kernel_.operand_glb(tac.in1).meta().layout);
ss << ", ";
ss << layout_text(kernel_.operand_glb(tac.in2).meta().layout);
break;
case 2:
ss << layout_text(kernel_.operand_glb(tac.out).meta().layout);
ss << ", ";
ss << layout_text(kernel_.operand_glb(tac.in1).meta().layout);
break;
case 1:
ss << layout_text(kernel_.operand_glb(tac.out).meta().layout);
break;
default:
break;
}
ss << ")";
return ss.str();
}
string Walker::oper(OPERATOR oper, ETYPE etype, string in1, string in2)
{
switch(oper) {
case ABSOLUTE:
switch(etype) {
case COMPLEX128: return _cabs(in1);
case COMPLEX64: return _cabsf(in1);
default: return _abs(in1);
}
case ADD: return _add(in1, in2);
case ARCCOS:
switch(etype) {
case COMPLEX128: return _cacos(in1);
case COMPLEX64: return _cacosf(in1);
default: return _acos(in1);
}
case ARCCOSH:
switch(etype) {
case COMPLEX128: return _cacosh(in1);
case COMPLEX64: return _cacosf(in1);
default: return _acosh(in1);
}
case ARCSIN:
switch(etype) {
case COMPLEX128: return _casin(in1);
case COMPLEX64: return _casinf(in1);
default: return _asin(in1);
}
case ARCSINH:
switch(etype) {
case COMPLEX128: return _casinh(in1);
case COMPLEX64: return _casinhf(in1);
default: return _asinh(in1);
}
case ARCTAN:
switch(etype) {
case COMPLEX128: return _catan(in1);
case COMPLEX64: return _catanf(in1);
default: return _atan(in1);
}
case ARCTAN2: return _atan2(in1, in2);
case ARCTANH:
switch(etype) {
case COMPLEX128: return _catanh(in1);
case COMPLEX64: return _catanhf(in1);
default: return _atanh(in1);
}
case BITWISE_AND: return _bitw_and(in1, in2);
case BITWISE_OR: return _bitw_or(in1, in2);
case BITWISE_XOR: return _bitw_xor(in1, in2);
case CEIL: return _ceil(in1);
case COS:
switch(etype) {
case COMPLEX128: return _ccos(in1);
case COMPLEX64: return _ccosf(in1);
default: return _cos(in1);
}
case COSH:
switch(etype) {
case COMPLEX128: return _ccosh(in1);
case COMPLEX64: return _ccoshf(in1);
default: return _cosh(in1);
}
case DISCARD: break; // TODO: Raise exception
case DIVIDE: return _div(in1, in2);
case EQUAL: return _eq(in1, in2);
case EXP:
switch(etype) {
case COMPLEX128: return _cexp(in1);
case COMPLEX64: return _cexpf(in1);
default: return _exp(in1);
}
case EXP2:
switch(etype) {
case COMPLEX128: return _cexp2(in1);
case COMPLEX64: return _cexp2f(in1);
default: return _exp2(in1);
}
case EXPM1: return _expm1(in1);
case EXTENSION_OPERATOR: break; // TODO: Raise exception
case FLOOD: break; // TODO: Raise exception
case FLOOR: return _floor(in1);
case FREE: break; // TODO: Raise exception
case GREATER: return _gt(in1, in2);
case GREATER_EQUAL: return _gteq(in1, in2);
case IDENTITY: return in1;
case IMAG:
switch(etype) {
case FLOAT32: return _cimagf(in1);
default: return _cimag(in1);
}
case INVERT:
switch(etype) {
case BOOL: return _invertb(in1);
default: return _invert(in1);
}
case ISINF: return _isinf(in1);
case ISNAN: return _isnan(in1);
case LEFT_SHIFT: return _bitw_leftshift(in1, in2);
case LESS: return _lt(in1, in2);
case LESS_EQUAL: return _lteq(in1, in2);
case LOG:
switch(etype) {
case COMPLEX128: return _clog(in1);
case COMPLEX64: return _clogf(in1);
default: return _log(in1);
}
case LOG10:
switch(etype) {
case COMPLEX128: return _clog10(in1);
case COMPLEX64: return _clog10f(in1);
default: return _log10(in1);
}
case LOG1P: return _log1p(in1);
case LOG2: return _log2(in1);
case LOGICAL_AND: return _logic_and(in1, in2);
case LOGICAL_NOT: return _logic_not(in1);
case LOGICAL_OR: return _logic_or(in1, in2);
case LOGICAL_XOR: return _logic_xor(in1, in2);
case MAXIMUM: return _max(in1, in2);
case MINIMUM: return _min(in1, in2);
case MOD: return _mod(in1, in2);
case MULTIPLY: return _mul(in1, in2);
case NONE: break; // TODO: Raise exception
case NOT_EQUAL: return _neq(in1, in2);
case POWER:
switch(etype) {
case COMPLEX128: return _cpow(in1, in2);
case COMPLEX64: return _cpowf(in1, in2);
default: return _pow(in1, in2);
}
case RANDOM: return _random(in1, in2);
case RANGE: return _range();
case REAL:
switch(etype) {
case FLOAT32: return _crealf(in1);
default: return _creal(in1);
}
case RIGHT_SHIFT: return _bitw_rightshift(in1, in2);
case RINT: return _rint(in1);
case SIN:
switch(etype) {
case COMPLEX128: return _csin(in1);
case COMPLEX64: return _csinf(in1);
default: return _sin(in1);
}
case SIGN:
switch(etype) {
case COMPLEX128: return _div(in1, _cabs(in1));
case COMPLEX64: return _div(in1, _cabsf(in1));
default: return _sub(
_parens(_gt(in1, "0")),
_parens(_lt(in1, "0"))
);
}
case SINH:
switch(etype) {
case COMPLEX128: return _csinh(in1);
case COMPLEX64: return _csinhf(in1);
default: return _sinh(in1);
}
case SQRT:
switch(etype) {
case COMPLEX128: return _csqrt(in1);
case COMPLEX64: return _csqrtf(in1);
default: return _sqrt(in1);
}
case SUBTRACT: return _sub(in1, in2);
case SYNC: break; // TODO: Raise exception
case TAN:
switch(etype) {
case COMPLEX128: return _ctan(in1);
case COMPLEX64: return _ctanf(in1);
default: return _tan(in1);
}
case TANH:
switch(etype) {
case COMPLEX128: return _ctanh(in1);
case COMPLEX64: return _ctanhf(in1);
default: return _tanh(in1);
}
case TRUNC: return _trunc(in1);
default: return "NOT_IMPLEMENTED_YET";
}
return "NO NO< NO NO NO NO NONO NO NO NO NOTHERES NO LIMITS";
}
string Walker::synced_oper(OPERATOR operation, ETYPE etype, string out, string in1, string in2)
{
stringstream ss;
switch(operation) {
case MAXIMUM:
case MINIMUM:
case LOGICAL_AND:
case LOGICAL_OR:
case LOGICAL_XOR:
ss << _omp_critical(_assign(out, oper(operation, etype, in1, in2)), "accusync");
break;
default:
switch(etype) {
case COMPLEX64:
case COMPLEX128:
ss << _omp_critical(_assign(out, oper(operation, etype, in1, in2)), "accusync");
break;
default:
ss << _omp_atomic(_assign(out, oper(operation, etype, in1, in2)));
break;
}
break;
}
return ss.str();
}
}}}}
<commit_msg>cpu: Fixed csign(0).<commit_after>#include <sstream>
#include <string>
#include "codegen.hpp"
//
// NOTE: This file is autogenerated based on the tac-definition.
// You should therefore not edit it manually.
//
using namespace std;
using namespace bohrium::core;
namespace bohrium{
namespace engine{
namespace cpu{
namespace codegen{
string Walker::oper_neutral_element(OPERATOR oper, ETYPE etype)
{
switch(oper) {
case ADD: return "0";
case MULTIPLY: return "1";
case MAXIMUM:
switch(etype) {
case BOOL: return "0";
case INT8: return "INT8_MIN";
case INT16: return "INT16_MIN";
case INT32: return "INT32_MIN";
case INT64: return "INT64_MIN";
case UINT8: return "UINT8_MIN";
case UINT16: return "UINT16_MIN";
case UINT32: return "UINT32_MIN";
case UINT64: return "UINT64_MIN";
case FLOAT32: return "FLT_MIN";
case FLOAT64: return "DBL_MIN";
default: return "UNKNOWN_NEUTRAL_FOR_MAXIMUM_OF_GIVEN_TYPE";
}
case MINIMUM:
switch(etype) {
case BOOL: return "1";
case INT8: return "INT8_MAX";
case INT16: return "INT16_MAX";
case INT32: return "INT32_MAX";
case INT64: return "INT64_MAX";
case UINT8: return "UINT8_MAX";
case UINT16: return "UINT16_MAX";
case UINT32: return "UINT32_MAX";
case UINT64: return "UINT64_MAX";
case FLOAT32: return "FLT_MAX";
case FLOAT64: return "DBL_MAX";
default: return "UNKNOWN_NEUTRAL_FOR_MINIMUM_OF_GIVEN_TYPE";
}
case LOGICAL_AND: return "1";
case LOGICAL_OR: return "0";
case LOGICAL_XOR: return "0";
case BITWISE_AND: return "1";
switch(etype) {
case BOOL: return "1";
case INT8: return "-1";
case INT16: return "-1";
case INT32: return "-1";
case INT64: return "-1";
case UINT8: return "UINT8_MAX";
case UINT16: return "UINT16_MAX";
case UINT32: return "UINT32_MAX";
case UINT64: return "UINT64_MAX";
default: return "UNKNOWN_NEUTRAL_FOR_BITWISE_AND_OF_GIVEN_TYPE";
}
case BITWISE_OR: return "0";
case BITWISE_XOR: return "0";
default: return "UNKNOWN_NEUTRAL_FOR_OPERATOR";
}
}
string Walker::oper_description(tac_t tac)
{
stringstream ss;
ss << operator_text(tac.oper) << " (";
switch(core::tac_noperands(tac)) {
case 3:
ss << layout_text(kernel_.operand_glb(tac.out).meta().layout);
ss << ", ";
ss << layout_text(kernel_.operand_glb(tac.in1).meta().layout);
ss << ", ";
ss << layout_text(kernel_.operand_glb(tac.in2).meta().layout);
break;
case 2:
ss << layout_text(kernel_.operand_glb(tac.out).meta().layout);
ss << ", ";
ss << layout_text(kernel_.operand_glb(tac.in1).meta().layout);
break;
case 1:
ss << layout_text(kernel_.operand_glb(tac.out).meta().layout);
break;
default:
break;
}
ss << ")";
return ss.str();
}
string Walker::oper(OPERATOR oper, ETYPE etype, string in1, string in2)
{
switch(oper) {
case ABSOLUTE:
switch(etype) {
case COMPLEX128: return _cabs(in1);
case COMPLEX64: return _cabsf(in1);
default: return _abs(in1);
}
case ADD: return _add(in1, in2);
case ARCCOS:
switch(etype) {
case COMPLEX128: return _cacos(in1);
case COMPLEX64: return _cacosf(in1);
default: return _acos(in1);
}
case ARCCOSH:
switch(etype) {
case COMPLEX128: return _cacosh(in1);
case COMPLEX64: return _cacosf(in1);
default: return _acosh(in1);
}
case ARCSIN:
switch(etype) {
case COMPLEX128: return _casin(in1);
case COMPLEX64: return _casinf(in1);
default: return _asin(in1);
}
case ARCSINH:
switch(etype) {
case COMPLEX128: return _casinh(in1);
case COMPLEX64: return _casinhf(in1);
default: return _asinh(in1);
}
case ARCTAN:
switch(etype) {
case COMPLEX128: return _catan(in1);
case COMPLEX64: return _catanf(in1);
default: return _atan(in1);
}
case ARCTAN2: return _atan2(in1, in2);
case ARCTANH:
switch(etype) {
case COMPLEX128: return _catanh(in1);
case COMPLEX64: return _catanhf(in1);
default: return _atanh(in1);
}
case BITWISE_AND: return _bitw_and(in1, in2);
case BITWISE_OR: return _bitw_or(in1, in2);
case BITWISE_XOR: return _bitw_xor(in1, in2);
case CEIL: return _ceil(in1);
case COS:
switch(etype) {
case COMPLEX128: return _ccos(in1);
case COMPLEX64: return _ccosf(in1);
default: return _cos(in1);
}
case COSH:
switch(etype) {
case COMPLEX128: return _ccosh(in1);
case COMPLEX64: return _ccoshf(in1);
default: return _cosh(in1);
}
case DISCARD: break; // TODO: Raise exception
case DIVIDE: return _div(in1, in2);
case EQUAL: return _eq(in1, in2);
case EXP:
switch(etype) {
case COMPLEX128: return _cexp(in1);
case COMPLEX64: return _cexpf(in1);
default: return _exp(in1);
}
case EXP2:
switch(etype) {
case COMPLEX128: return _cexp2(in1);
case COMPLEX64: return _cexp2f(in1);
default: return _exp2(in1);
}
case EXPM1: return _expm1(in1);
case EXTENSION_OPERATOR: break; // TODO: Raise exception
case FLOOD: break; // TODO: Raise exception
case FLOOR: return _floor(in1);
case FREE: break; // TODO: Raise exception
case GREATER: return _gt(in1, in2);
case GREATER_EQUAL: return _gteq(in1, in2);
case IDENTITY: return in1;
case IMAG:
switch(etype) {
case FLOAT32: return _cimagf(in1);
default: return _cimag(in1);
}
case INVERT:
switch(etype) {
case BOOL: return _invertb(in1);
default: return _invert(in1);
}
case ISINF: return _isinf(in1);
case ISNAN: return _isnan(in1);
case LEFT_SHIFT: return _bitw_leftshift(in1, in2);
case LESS: return _lt(in1, in2);
case LESS_EQUAL: return _lteq(in1, in2);
case LOG:
switch(etype) {
case COMPLEX128: return _clog(in1);
case COMPLEX64: return _clogf(in1);
default: return _log(in1);
}
case LOG10:
switch(etype) {
case COMPLEX128: return _clog10(in1);
case COMPLEX64: return _clog10f(in1);
default: return _log10(in1);
}
case LOG1P: return _log1p(in1);
case LOG2: return _log2(in1);
case LOGICAL_AND: return _logic_and(in1, in2);
case LOGICAL_NOT: return _logic_not(in1);
case LOGICAL_OR: return _logic_or(in1, in2);
case LOGICAL_XOR: return _logic_xor(in1, in2);
case MAXIMUM: return _max(in1, in2);
case MINIMUM: return _min(in1, in2);
case MOD: return _mod(in1, in2);
case MULTIPLY: return _mul(in1, in2);
case NONE: break; // TODO: Raise exception
case NOT_EQUAL: return _neq(in1, in2);
case POWER:
switch(etype) {
case COMPLEX128: return _cpow(in1, in2);
case COMPLEX64: return _cpowf(in1, in2);
default: return _pow(in1, in2);
}
case RANDOM: return _random(in1, in2);
case RANGE: return _range();
case REAL:
switch(etype) {
case FLOAT32: return _crealf(in1);
default: return _creal(in1);
}
case RIGHT_SHIFT: return _bitw_rightshift(in1, in2);
case RINT: return _rint(in1);
case SIN:
switch(etype) {
case COMPLEX128: return _csin(in1);
case COMPLEX64: return _csinf(in1);
default: return _sin(in1);
}
case SIGN:
switch(etype) {
case COMPLEX128: return _div(in1, _parens(_add(_cabs(in1), _parens(_eq(in1, "0")))));
case COMPLEX64: return _div(in1, _parens(_add(_cabsf(in1), _parens(_eq(in1, "0")))));
default: return _sub(
_parens(_gt(in1, "0")),
_parens(_lt(in1, "0"))
);
}
case SINH:
switch(etype) {
case COMPLEX128: return _csinh(in1);
case COMPLEX64: return _csinhf(in1);
default: return _sinh(in1);
}
case SQRT:
switch(etype) {
case COMPLEX128: return _csqrt(in1);
case COMPLEX64: return _csqrtf(in1);
default: return _sqrt(in1);
}
case SUBTRACT: return _sub(in1, in2);
case SYNC: break; // TODO: Raise exception
case TAN:
switch(etype) {
case COMPLEX128: return _ctan(in1);
case COMPLEX64: return _ctanf(in1);
default: return _tan(in1);
}
case TANH:
switch(etype) {
case COMPLEX128: return _ctanh(in1);
case COMPLEX64: return _ctanhf(in1);
default: return _tanh(in1);
}
case TRUNC: return _trunc(in1);
default: return "NOT_IMPLEMENTED_YET";
}
return "NO NO< NO NO NO NO NONO NO NO NO NOTHERES NO LIMITS";
}
string Walker::synced_oper(OPERATOR operation, ETYPE etype, string out, string in1, string in2)
{
stringstream ss;
switch(operation) {
case MAXIMUM:
case MINIMUM:
case LOGICAL_AND:
case LOGICAL_OR:
case LOGICAL_XOR:
ss << _omp_critical(_assign(out, oper(operation, etype, in1, in2)), "accusync");
break;
default:
switch(etype) {
case COMPLEX64:
case COMPLEX128:
ss << _omp_critical(_assign(out, oper(operation, etype, in1, in2)), "accusync");
break;
default:
ss << _omp_atomic(_assign(out, oper(operation, etype, in1, in2)));
break;
}
break;
}
return ss.str();
}
}}}}
<|endoftext|>
|
<commit_before>#pragma once
#include "../base/type.h"
#include "../base/check.h"
#include "../utils/type_traits.hpp"
#include <boost/callable_traits.hpp>
#include "../brigand.hpp"
#ifdef AUTOCXXPY_INCLUDED_PYBIND11
#include <pybind11/stl.h>
#endif
#include <iostream>
#include <type_traits>
#include "./utils.hpp"
#include <functional>
namespace c2py
{
template <class method_constant, class ret_t, class base_t, class ... Ls, class ... Rs>
inline constexpr auto wrap_pointer_argument_as_inout_impl(brigand::list<Ls...>, brigand::list <Rs...>)
{
namespace ct = boost::callable_traits;
return [](Ls ... ls, base_t &arg, Rs ... rs)
{
constexpr auto method = method_constant::value;
//using func_t = ct::function_type_t<decltype(method)>;
//using args_t = ct::args_t<func_t, list>;
//using ret_t = ct::return_type_t<func_t>;
auto stdmethod = std::function<ct::function_type_t<decltype(method)>>(method);
if constexpr (std::is_void_v<ret_t>)
{
stdmethod(std::forward<Ls>(ls)..., &arg, std::forward<Rs>(rs)...);
return std::move(arg);
}
else
{
return append_as_tuple(stdmethod(
std::forward<Ls>(ls)...,
&arg,
std::forward<Rs>(rs)...
), std::move(arg));
}
};
}
template <class method_constant, class ret_t, class base_t, class ... Ls, class ... Rs>
inline constexpr auto wrap_reference_argument_as_inout_impl(brigand::list<Ls...>, brigand::list <Rs...>)
{
namespace ct = boost::callable_traits;
return [](Ls ... ls, base_t arg, Rs ... rs)
{
constexpr auto method = method_constant::value;
auto stdmethod = std::function<ct::function_type_t<decltype(method)>>(method);
if constexpr (std::is_void_v<ret_t>)
{
stdmethod(std::forward<Ls>(ls)..., arg, std::forward<Rs>(rs)...);
return arg;
}
else
{
return append_as_tuple(stdmethod(
std::forward<Ls>(ls)...,
arg,
std::forward<Rs>(rs)...
), arg);
}
};
}
template <class method_constant, size_t index>
inline constexpr auto wrap_argument_as_inout()
{
using namespace brigand;
namespace ct = boost::callable_traits;
constexpr auto method = method_constant::value;
using func_t = ct::function_type_t<decltype(method)>;
using args_t = ct::args_t<func_t, list>;
if constexpr (check_not_out_of_bound<index, size<args_t>::value>())
{
using s = split_at<args_t, std::integral_constant<int, index>>;
using ls = front<s>;
using rs = pop_front<back<s>>;
using arg_t = at<args_t, std::integral_constant<int, index>>;
using ret_t = ct::return_type_t<func_t>;
if constexpr (std::is_pointer_v<arg_t>)
{
using base_t = std::remove_pointer_t<arg_t>;
return wrap_pointer_argument_as_inout_impl<method_constant, ret_t, base_t>(ls{}, rs{});
}
else
{
using base_t = std::remove_reference_t<arg_t>;
return wrap_reference_argument_as_inout_impl<method_constant, ret_t, base_t>(ls{}, rs{});
}
}
}
template <class method_constant, class integral_constant>
struct inout_argument_transform
{
using type = inout_argument_transform;
using value_type = decltype(wrap_argument_as_inout<method_constant, integral_constant::value>());
static constexpr value_type value = wrap_argument_as_inout<method_constant, integral_constant::value>();
};
}
<commit_msg>Delete inout_argument.hpp<commit_after><|endoftext|>
|
<commit_before>/*
* #%L
* %%
* Copyright (C) 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <string>
#include <unordered_map>
#include <numeric>
#include <gtest/gtest.h>
#include "libjoynrclustercontroller/access-control/RadixTree.h"
class RadixTreeTest : public ::testing::Test
{
public:
RadixTreeTest()
{
/*
* the tree has the following internal structure:
*
* "" (root)
* |
* 01 (i)
* ______|______
* / \
* 2 3
* ___|___
* / \
* 4 7
* ___|___
* / \
* 5 6
*
* '(i)' depicts an internal node
*/
data["012"] = "2";
data["013"] = "3";
data["0134"] = "4";
data["01345"] = "5";
data["01346"] = "6";
data["0137"] = "7";
for (auto& entry : data) {
tree.insert(entry.first, entry.second);
}
}
protected:
void validateParents(const std::string& key, const std::vector<std::string>& expectedParents)
{
Node* node = tree.longestMatch(key);
ASSERT_TRUE(node);
auto parents = node->parents();
auto expectedIt = expectedParents.begin();
for (auto parentIt = parents.begin(); parentIt != parents.end(); ++parentIt) {
ASSERT_NE(expectedIt, expectedParents.end());
Node* parentNode = *parentIt;
EXPECT_EQ(*expectedIt, parentNode->getValue());
++expectedIt;
}
}
using Tree = joynr::RadixTree<std::string, std::string>;
using Node = typename Tree::Node;
Tree tree;
std::unordered_map<std::string, std::string> data;
};
TEST_F(RadixTreeTest, insertReturnsNode)
{
const std::string key = "key";
const std::string value = "value";
Node* node = tree.insert(key, value);
EXPECT_EQ(value, node->getValue());
}
TEST_F(RadixTreeTest, insertReturnsNodeWithEmptyKey)
{
const std::string key = "";
const std::string value = "value";
Node* node = tree.insert(key, value);
EXPECT_EQ(value, node->getValue());
}
TEST_F(RadixTreeTest, longestMatchRetrievesCorrectValues)
{
// find the entries by their original key
for (auto& entry : data) {
Node* node = tree.longestMatch(entry.first);
ASSERT_TRUE(node) << "queried value (entry.first): " << entry.first;
EXPECT_EQ(entry.second, node->getValue());
}
// add some more characters to each key
// then retrieve the corresponding entry
for (auto& entry : data) {
Node* node = tree.longestMatch(entry.first + "####");
ASSERT_TRUE(node);
EXPECT_EQ(entry.second, node->getValue());
}
}
TEST_F(RadixTreeTest, longestMatchDoesNotFindEntryForNonExistingKey)
{
Node* node = tree.longestMatch("non-existing-key");
EXPECT_FALSE(node);
}
TEST_F(RadixTreeTest, longestMatchDoesNotFindEntryForInternalNodeKey)
{
Node* node = tree.longestMatch("01");
EXPECT_FALSE(node);
}
TEST_F(RadixTreeTest, parentsAreValidWithRootValue)
{
tree.insert(std::string(""), "root");
validateParents("01346", {"4", "3", "root"});
validateParents("01345", {"4", "3", "root"});
validateParents("0134", {"3", "root"});
validateParents("0137", {"3", "root"});
validateParents("013", {"root"});
validateParents("012", {"root"});
}
TEST_F(RadixTreeTest, parentsAreValidWithoutRootValue)
{
validateParents("01346", {"4", "3"});
validateParents("01345", {"4", "3"});
validateParents("0134", {"3"});
validateParents("0137", {"3"});
validateParents("013", {});
validateParents("012", {});
}
TEST_F(RadixTreeTest, eraseLeaf)
{
const std::string leafKey = "0137";
Node* leaf = tree.longestMatch(leafKey);
ASSERT_TRUE(leaf);
ASSERT_EQ("7", leaf->getValue());
leaf->erase();
Node* node = tree.longestMatch(leafKey);
ASSERT_EQ("3", node->getValue());
}
TEST_F(RadixTreeTest, eraseMidNodeRestructuresTree)
{
const std::string midNodeKey = "013";
Node* midNode = tree.longestMatch(midNodeKey);
ASSERT_TRUE(midNode);
midNode->erase();
Node* node = tree.longestMatch(midNodeKey);
EXPECT_FALSE(node);
validateParents("01346", {"4"});
validateParents("01345", {"4"});
validateParents("0134", {});
validateParents("0137", {});
}
TEST_F(RadixTreeTest, eraseRoot)
{
const std::string rootKey = "";
tree.insert(rootKey, "root");
Node* rootNode = tree.longestMatch(rootKey);
ASSERT_TRUE(rootNode);
rootNode->erase();
Node* node = tree.longestMatch(rootKey);
EXPECT_FALSE(node);
validateParents("01346", {"4", "3"});
validateParents("01345", {"4", "3"});
validateParents("0134", {"3"});
validateParents("0137", {"3"});
validateParents("013", {});
validateParents("012", {});
}
TEST_F(RadixTreeTest, callParentsOnRoot)
{
const std::string rootKey = "";
tree.insert(rootKey, "root");
Node* rootNode = tree.longestMatch(rootKey);
ASSERT_TRUE(rootNode);
auto parents = rootNode->parents();
EXPECT_EQ(parents.begin(), parents.end());
}
TEST_F(RadixTreeTest, visit)
{
std::size_t nodeCount = 0;
auto fun = [&nodeCount, data = data ](const auto& node, const auto& keyVector)
{
const std::string key = std::accumulate(keyVector.begin(), keyVector.end(), std::string(), [](std::string& s, const auto& i) {
return s+i.get();
});
ASSERT_EQ(data.at(key), node.getValue());
nodeCount++;
};
tree.visit(fun);
EXPECT_EQ(nodeCount, data.size());
}
<commit_msg>[C++] Added RadixTreeTest to check longestMatch() does not return wrong node<commit_after>/*
* #%L
* %%
* Copyright (C) 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <string>
#include <unordered_map>
#include <numeric>
#include <gtest/gtest.h>
#include "libjoynrclustercontroller/access-control/RadixTree.h"
class RadixTreeTest : public ::testing::Test
{
public:
RadixTreeTest()
{
/*
* the tree has the following internal structure:
*
* "" (root)
* |
* 01 (i)
* ______|______
* / \
* 2 3
* ___|___
* / \
* 4 7
* ___|___
* / \
* 5 6
*
* '(i)' depicts an internal node
*/
data["012"] = "2";
data["013"] = "3";
data["0134"] = "4";
data["01345"] = "5";
data["01346"] = "6";
data["0137"] = "7";
for (auto& entry : data) {
tree.insert(entry.first, entry.second);
}
}
protected:
void validateParents(const std::string& key, const std::vector<std::string>& expectedParents)
{
Node* node = tree.longestMatch(key);
ASSERT_TRUE(node);
auto parents = node->parents();
auto expectedIt = expectedParents.begin();
for (auto parentIt = parents.begin(); parentIt != parents.end(); ++parentIt) {
ASSERT_NE(expectedIt, expectedParents.end());
Node* parentNode = *parentIt;
EXPECT_EQ(*expectedIt, parentNode->getValue());
++expectedIt;
}
}
using Tree = joynr::RadixTree<std::string, std::string>;
using Node = typename Tree::Node;
Tree tree;
std::unordered_map<std::string, std::string> data;
};
TEST_F(RadixTreeTest, insertReturnsNode)
{
const std::string key = "key";
const std::string value = "value";
Node* node = tree.insert(key, value);
EXPECT_EQ(value, node->getValue());
}
TEST_F(RadixTreeTest, insertReturnsNodeWithEmptyKey)
{
const std::string key = "";
const std::string value = "value";
Node* node = tree.insert(key, value);
EXPECT_EQ(value, node->getValue());
}
TEST_F(RadixTreeTest, longestMatchRetrievesCorrectValues)
{
// find the entries by their original key
for (auto& entry : data) {
Node* node = tree.longestMatch(entry.first);
ASSERT_TRUE(node) << "queried value (entry.first): " << entry.first;
EXPECT_EQ(entry.second, node->getValue());
}
// add some more characters to each key
// then retrieve the corresponding entry
for (auto& entry : data) {
Node* node = tree.longestMatch(entry.first + "####");
ASSERT_TRUE(node);
EXPECT_EQ(entry.second, node->getValue());
}
}
TEST_F(RadixTreeTest, longestMatchDoesNotFindEntryForNonExistingKey)
{
Node* node = tree.longestMatch("non-existing-key");
EXPECT_FALSE(node);
}
TEST_F(RadixTreeTest, longestMatchDoesNotFindEntryForInternalNodeKey)
{
Node* node = tree.longestMatch("01");
EXPECT_FALSE(node);
}
TEST(RadixTreeTest2, longestMatchDoesNotReturnNonPrefixEntry)
{
using Tree = joynr::RadixTree<std::string, std::string>;
using Node = typename Tree::Node;
Tree longestMatchTestTree;
const std::string rootKey = "";
longestMatchTestTree.insert(rootKey, "rootvalue");
const std::string secondKey = "abc";
longestMatchTestTree.insert(secondKey, "value1");
const std::string searchKey = "abxyz";
Node* resultNode = longestMatchTestTree.longestMatch(searchKey);
EXPECT_EQ(resultNode->getKey(), rootKey);
}
TEST_F(RadixTreeTest, parentsAreValidWithRootValue)
{
tree.insert(std::string(""), "root");
validateParents("01346", {"4", "3", "root"});
validateParents("01345", {"4", "3", "root"});
validateParents("0134", {"3", "root"});
validateParents("0137", {"3", "root"});
validateParents("013", {"root"});
validateParents("012", {"root"});
}
TEST_F(RadixTreeTest, parentsAreValidWithoutRootValue)
{
validateParents("01346", {"4", "3"});
validateParents("01345", {"4", "3"});
validateParents("0134", {"3"});
validateParents("0137", {"3"});
validateParents("013", {});
validateParents("012", {});
}
TEST_F(RadixTreeTest, eraseLeaf)
{
const std::string leafKey = "0137";
Node* leaf = tree.longestMatch(leafKey);
ASSERT_TRUE(leaf);
ASSERT_EQ("7", leaf->getValue());
leaf->erase();
Node* node = tree.longestMatch(leafKey);
ASSERT_EQ("3", node->getValue());
}
TEST_F(RadixTreeTest, eraseMidNodeRestructuresTree)
{
const std::string midNodeKey = "013";
Node* midNode = tree.longestMatch(midNodeKey);
ASSERT_TRUE(midNode);
midNode->erase();
Node* node = tree.longestMatch(midNodeKey);
EXPECT_FALSE(node);
validateParents("01346", {"4"});
validateParents("01345", {"4"});
validateParents("0134", {});
validateParents("0137", {});
}
TEST_F(RadixTreeTest, eraseRoot)
{
const std::string rootKey = "";
tree.insert(rootKey, "root");
Node* rootNode = tree.longestMatch(rootKey);
ASSERT_TRUE(rootNode);
rootNode->erase();
Node* node = tree.longestMatch(rootKey);
EXPECT_FALSE(node);
validateParents("01346", {"4", "3"});
validateParents("01345", {"4", "3"});
validateParents("0134", {"3"});
validateParents("0137", {"3"});
validateParents("013", {});
validateParents("012", {});
}
TEST_F(RadixTreeTest, callParentsOnRoot)
{
const std::string rootKey = "";
tree.insert(rootKey, "root");
Node* rootNode = tree.longestMatch(rootKey);
ASSERT_TRUE(rootNode);
auto parents = rootNode->parents();
EXPECT_EQ(parents.begin(), parents.end());
}
TEST_F(RadixTreeTest, visit)
{
std::size_t nodeCount = 0;
auto fun = [&nodeCount, data = data ](const auto& node, const auto& keyVector)
{
const std::string key = std::accumulate(keyVector.begin(), keyVector.end(), std::string(), [](std::string& s, const auto& i) {
return s+i.get();
});
ASSERT_EQ(data.at(key), node.getValue());
nodeCount++;
};
tree.visit(fun);
EXPECT_EQ(nodeCount, data.size());
}
<|endoftext|>
|
<commit_before>#include "test_precomp.hpp"
using namespace cv;
using namespace std;
TEST(Core_Drawing, _914)
{
const int rows = 256;
const int cols = 256;
Mat img(rows, cols, CV_8UC1, Scalar(255));
line(img, Point(0, 10), Point(255, 10), Scalar(0), 2, 4);
line(img, Point(-5, 20), Point(260, 20), Scalar(0), 2, 4);
line(img, Point(10, 0), Point(10, 255), Scalar(0), 2, 4);
double x0 = 0.0/pow(2.0, -2.0);
double x1 = 255.0/pow(2.0, -2.0);
double y = 30.5/pow(2.0, -2.0);
line(img, Point(int(x0), int(y)), Point(int(x1), int(y)), Scalar(0), 2, 4, 2);
int pixelsDrawn = rows*cols - countNonZero(img);
ASSERT_EQ( (3*rows + cols)*3 - 3*9, pixelsDrawn);
}
TEST(Core_OutputArraySreate, _1997)
{
struct local {
static void create(OutputArray arr, Size submatSize, int type)
{
int sizes[] = {submatSize.width, submatSize.height};
arr.create(sizeof(sizes)/sizeof(sizes[0]), sizes, type);
}
};
Mat mat(Size(512, 512), CV_8U);
Size submatSize = Size(256, 256);
ASSERT_NO_THROW(local::create( mat(Rect(Point(), submatSize)), submatSize, mat.type() ));
}<commit_msg>Added a test that documents that negative numbers are not clipped by cv::saturate_cast<commit_after>#include "test_precomp.hpp"
using namespace cv;
using namespace std;
TEST(Core_Drawing, _914)
{
const int rows = 256;
const int cols = 256;
Mat img(rows, cols, CV_8UC1, Scalar(255));
line(img, Point(0, 10), Point(255, 10), Scalar(0), 2, 4);
line(img, Point(-5, 20), Point(260, 20), Scalar(0), 2, 4);
line(img, Point(10, 0), Point(10, 255), Scalar(0), 2, 4);
double x0 = 0.0/pow(2.0, -2.0);
double x1 = 255.0/pow(2.0, -2.0);
double y = 30.5/pow(2.0, -2.0);
line(img, Point(int(x0), int(y)), Point(int(x1), int(y)), Scalar(0), 2, 4, 2);
int pixelsDrawn = rows*cols - countNonZero(img);
ASSERT_EQ( (3*rows + cols)*3 - 3*9, pixelsDrawn);
}
TEST(Core_OutputArraySreate, _1997)
{
struct local {
static void create(OutputArray arr, Size submatSize, int type)
{
int sizes[] = {submatSize.width, submatSize.height};
arr.create(sizeof(sizes)/sizeof(sizes[0]), sizes, type);
}
};
Mat mat(Size(512, 512), CV_8U);
Size submatSize = Size(256, 256);
ASSERT_NO_THROW(local::create( mat(Rect(Point(), submatSize)), submatSize, mat.type() ));
}
TEST(Core_SaturateCast, NegativeNotClipped)
{
double d = -1.0;
unsigned int val = cv::saturate_cast<unsigned int>(d);
ASSERT_EQ(0xffffffff, val);
}
<|endoftext|>
|
<commit_before>#include <GL/glut.h>
#include <stdio.h>
#include <vector>
#include <floppy.h>
using namespace std;
vector<char> inputKey;
double g,v,tmp2;
int cnt;
void gameoverAnimation()
{
inputKey.push_back('U');
v=1.0;
}
void movePhysics()
{
int ii;
g=10;
for(ii=0;ii<inputKey.size();ii++)
{
if(inputKey[ii]=='U')
{
if((movementY+(resY/2)+50)<resY)
movementY+=4;
cnt++;
}
if(cnt>=7)
{
cnt=0;
inputKey.erase(inputKey.begin()+ii);
}
}
//...GRAVITY
if(inputKey.size()==0)
{
// 0.021125
if(gameover==0)
{
tmp2=resY/2;
v=0.61+(abs(movementY)/tmp2)/6;
}
else
{
if( (inputKey.size()==0 ) && (movementY <- (resY/2) ) )
{
gameover=0;
resetFunc();
}
}
movementY-= v*v/2*g;
}
}
void processSpecialKeys(int key, int xx, int yy)
{
switch (key)
{
case GLUT_KEY_UP :
if(gameover==0)
inputKey.push_back('U');
break;
}
}
<commit_msg>tweaked movements<commit_after>#include <GL/glut.h>
#include <stdio.h>
#include <vector>
#include <floppy.h>
using namespace std;
vector<char> inputKey;
double g,v,tmp2;
int cnt;
void gameoverAnimation()
{
inputKey.push_back('U');
v=1.1;
}
void movePhysics()
{
int ii;
g=10;
for(ii=0;ii<inputKey.size();ii++)
{
if(inputKey[ii]=='U')
{
if((movementY+(resY/2)+50)<resY)
movementY+=4;
cnt++;
}
if(cnt>=7)
{
cnt=0;
inputKey.erase(inputKey.begin()+ii);
}
}
//...GRAVITY
if(inputKey.size()==0)
{
// 0.021125
if(gameover==0)
{
tmp2=resY/2;
v=0.65+(abs(movementY)/tmp2)/5;
}
else
{
if( (inputKey.size()==0 ) && (movementY <- (resY/2) ) )
{
gameover=0;
resetFunc();
}
}
movementY-= v*v/2*g;
}
}
void processSpecialKeys(int key, int xx, int yy)
{
switch (key)
{
case GLUT_KEY_UP :
if(gameover==0)
inputKey.push_back('U');
break;
}
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH
#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH
#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING
#include <boost/numeric/conversion/cast.hpp>
#include <dune/fem/misc/mpimanager.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/functions/expression.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/prolongations.hh>
#include <dune/gdt/playground/products/elliptic-swipdg.hh>
#include <dune/hdd/linearelliptic/testcases/spe10.hh>
#include <dune/hdd/linearelliptic/discretizations/block-swipdg.hh>
#include <dune/hdd/linearelliptic/estimators/block-swipdg.hh>
namespace internal {
class Initializer
{
public:
Initializer(const ssize_t info_log_levels,
const ssize_t debug_log_levels,
const bool enable_warnings,
const bool enable_colors,
const std::string info_color,
const std::string debug_color,
const std::string warn_color)
{
try {
int argc = 0;
char** argv = new char* [0];
Dune::Fem::MPIManager::initialize(argc, argv);
} catch (...) {}
DSC::TimedLogger().create(info_log_levels,
debug_log_levels,
enable_warnings,
enable_colors,
info_color,
debug_color,
warn_color);
DSC::TimedLogger().get("OS2014.spe10model1example").info() << "creating grid and problem... " << std::endl;
}
}; // class Initializer
} // namespace internal
template< class GridType >
class OS2014Spe10Model1Example
: internal::Initializer
{
static_assert(GridType::dimension == 2, "Only available in 2d!");
public:
typedef Dune::HDD::LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridType > TestCaseType;
typedef double RangeFieldType;
typedef Dune::HDD::LinearElliptic::Discretizations::BlockSWIPDG< GridType, RangeFieldType, 1 > DiscretizationType;
typedef typename DiscretizationType::VectorType VectorType;
private:
typedef Dune::HDD::LinearElliptic::Estimators::BlockSWIPDG< typename DiscretizationType::AnsatzSpaceType,
VectorType,
typename DiscretizationType::ProblemType,
GridType > Estimator;
public:
OS2014Spe10Model1Example(const std::string partitioning = "[1 1 1]",
const DUNE_STUFF_SSIZE_T num_refinements = 0,
const ssize_t info_log_levels = 0,
const ssize_t debug_log_levels = -1,
const bool enable_warnings = true,
const bool enable_colors = true,
const std::string info_color = DSC::TimedLogging::default_info_color(),
const std::string debug_color = DSC::TimedLogging::default_debug_color(),
const std::string warn_color = DSC::TimedLogging::default_warning_color())
: internal::Initializer(info_log_levels,
debug_log_levels,
enable_warnings,
enable_colors,
info_color,
debug_color,
warn_color)
, test_case_({{"mu", Dune::Pymor::Parameter("mu", 1)}, // <- it does not matter which parameters we give to the
{"mu_hat", Dune::Pymor::Parameter("mu", 1)}, // test case here, since we use test_case_.problem()
{"mu_bar", Dune::Pymor::Parameter("mu", 1)}, // (which is the parametric problem) anyway
{"mu_minimizing", Dune::Pymor::Parameter("mu", 1)}},
partitioning,
boost::numeric_cast< size_t >(num_refinements))
, reference_test_case_({{"mu", Dune::Pymor::Parameter("mu", 1)},
{"mu_hat", Dune::Pymor::Parameter("mu", 1)},
{"mu_bar", Dune::Pymor::Parameter("mu", 1)},
{"mu_minimizing", Dune::Pymor::Parameter("mu", 1)}},
partitioning,
boost::numeric_cast< size_t >(num_refinements + 1))
, discretization_(*test_case_./*reference*/level_provider(0),
test_case_.boundary_info(),
test_case_.problem())
, reference_discretization_(*reference_test_case_.reference_provider(),
reference_test_case_.boundary_info(),
reference_test_case_.problem())
{
auto logger = DSC::TimedLogger().get("OS2014.spe10model1example");
logger.info() << "initializing discretization... " << std::flush;
discretization_.init();
reference_discretization_.init();
logger.info() << "done (grid has " << discretization_.grid_view()->indexSet().size(0)
<< " elements, discretization has " << discretization_.ansatz_space()->mapper().size() << " DoFs)"
<< std::endl;
} // ... OS2014Spe10Model1Example(...)
const TestCaseType& test_case() const
{
return test_case_;
}
DiscretizationType& discretization()
{
return discretization_;
}
DiscretizationType* discretization_and_return_ptr() const
{
return new DiscretizationType(discretization_);
}
VectorType project(const std::string expression) const
{
using namespace Dune;
typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;
typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;
DiscreteFunctionType discrete_function(*discretization_.ansatz_space());
typedef Stuff::Functions::Expression< typename DiscreteFunctionType::EntityType,
typename DiscreteFunctionType::DomainFieldType,
DiscreteFunctionType::dimDomain,
typename DiscreteFunctionType::RangeFieldType,
DiscreteFunctionType::dimRange > ExpressionFunctionType;
ExpressionFunctionType func("x", expression);
GDT::Operators::Projection< typename DiscretizationType::GridViewType > projection(*discretization_.grid_view());
projection.apply(func, discrete_function);
return discrete_function.vector();
} // ... project(...)
RangeFieldType compute_error(const VectorType& solution,
const std::string product_type = "",
const Dune::Pymor::Parameter mu = Dune::Pymor::Parameter(),
const Dune::Pymor::Parameter mu_product = Dune::Pymor::Parameter())
{
const std::string type = (product_type.empty() && reference_discretization_.available_products().size() == 1)
? reference_discretization_.available_products()[0]
: product_type;
// wrap solution into a discrete function
using namespace Dune;
typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;
typedef GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType > ConstDiscreteFunctionType;
ConstDiscreteFunctionType coarse_solution(*discretization_.ansatz_space(), solution);
// prolong to reference grid view
typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;
DiscreteFunctionType fine_solution(*reference_discretization_.ansatz_space());
GDT::Operators::Prolongation< typename DiscretizationType::GridViewType >
prolongation_operator(*reference_discretization_.grid_view());
prolongation_operator.apply(coarse_solution, fine_solution);
// compute reference solution
DiscreteFunctionType reference_solution(*reference_discretization_.ansatz_space());
reference_discretization_.solve(reference_solution.vector(), mu);
// compute error
const auto product = reference_discretization_.get_product(type).freeze_parameter(mu_product);
const auto difference = reference_solution.vector() - fine_solution.vector();
return std::sqrt(product.apply2(difference, difference));
} // ... compute_error(...)
RangeFieldType compute_jump_norm(const VectorType& solution_vector,
const Dune::Pymor::Parameter mu_product = Dune::Pymor::Parameter())
{
using namespace Dune;
typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;
typedef GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType > ConstDiscreteFunctionType;
ConstDiscreteFunctionType solution(*discretization_.ansatz_space(), solution_vector);
const auto diffusion_factor = discretization_.problem().diffusion_factor()->with_mu(mu_product);
const auto diffusion_tensor = discretization_.problem().diffusion_tensor()->with_mu(mu_product);
typedef GDT::Products::EllipticSWIPDGPenaltyLocalizable
< typename DiscretizationType::GridViewType,
typename DiscretizationType::ProblemType::DiffusionFactorType::NonparametricType,
ConstDiscreteFunctionType,
ConstDiscreteFunctionType,
RangeFieldType,
typename DiscretizationType::ProblemType::DiffusionTensorType::NonparametricType > ProductType;
ProductType penalty_product(*discretization_.grid_view(),
solution,
solution,
*diffusion_factor,
*diffusion_tensor,
2);
return std::sqrt(penalty_product.apply2());
} // ... compute_jump_norm(...)
std::vector< std::string > available_estimators() const
{
return Estimator::available();
}
RangeFieldType estimate(const VectorType& vector,
const std::string type,
const Dune::Pymor::Parameter mu_hat = Dune::Pymor::Parameter(),
const Dune::Pymor::Parameter mu_bar = Dune::Pymor::Parameter(),
const Dune::Pymor::Parameter mu = Dune::Pymor::Parameter())
{
return Estimator::estimate(*discretization_.ansatz_space(),
vector,
discretization_.problem(),
type,
{{"mu_hat", mu_hat},
{"mu_bar", mu_bar},
{"mu", mu},
{"mu_minimizing", Dune::Pymor::Parameter("mu", 0.1)}});
} // ... estimate(...)
public:
TestCaseType test_case_;
TestCaseType reference_test_case_;
DiscretizationType discretization_;
DiscretizationType reference_discretization_;
}; // class OS2014Spe10Model1Example
#endif // DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH
<commit_msg>[examples.linearelliptic.OS2014] update grid view usage<commit_after>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH
#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH
#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING
#include <boost/numeric/conversion/cast.hpp>
#include <dune/fem/misc/mpimanager.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/functions/expression.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/prolongations.hh>
#include <dune/gdt/playground/products/elliptic-swipdg.hh>
#include <dune/hdd/linearelliptic/testcases/spe10.hh>
#include <dune/hdd/linearelliptic/discretizations/block-swipdg.hh>
#include <dune/hdd/linearelliptic/estimators/block-swipdg.hh>
namespace internal {
class Initializer
{
public:
Initializer(const ssize_t info_log_levels,
const ssize_t debug_log_levels,
const bool enable_warnings,
const bool enable_colors,
const std::string info_color,
const std::string debug_color,
const std::string warn_color)
{
try {
int argc = 0;
char** argv = new char* [0];
Dune::Fem::MPIManager::initialize(argc, argv);
} catch (...) {}
DSC::TimedLogger().create(info_log_levels,
debug_log_levels,
enable_warnings,
enable_colors,
info_color,
debug_color,
warn_color);
DSC::TimedLogger().get("OS2014.spe10model1example").info() << "creating grid and problem... " << std::endl;
}
}; // class Initializer
} // namespace internal
template< class GridType >
class OS2014Spe10Model1Example
: internal::Initializer
{
static_assert(GridType::dimension == 2, "Only available in 2d!");
public:
typedef Dune::HDD::LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridType > TestCaseType;
typedef double RangeFieldType;
typedef Dune::HDD::LinearElliptic::Discretizations::BlockSWIPDG< GridType, RangeFieldType, 1 > DiscretizationType;
typedef typename DiscretizationType::VectorType VectorType;
private:
typedef Dune::HDD::LinearElliptic::Estimators::BlockSWIPDG< typename DiscretizationType::AnsatzSpaceType,
VectorType,
typename DiscretizationType::ProblemType,
GridType > Estimator;
public:
OS2014Spe10Model1Example(const std::string partitioning = "[1 1 1]",
const DUNE_STUFF_SSIZE_T num_refinements = 0,
const ssize_t info_log_levels = 0,
const ssize_t debug_log_levels = -1,
const bool enable_warnings = true,
const bool enable_colors = true,
const std::string info_color = DSC::TimedLogging::default_info_color(),
const std::string debug_color = DSC::TimedLogging::default_debug_color(),
const std::string warn_color = DSC::TimedLogging::default_warning_color())
: internal::Initializer(info_log_levels,
debug_log_levels,
enable_warnings,
enable_colors,
info_color,
debug_color,
warn_color)
, test_case_({{"mu", Dune::Pymor::Parameter("mu", 1)}, // <- it does not matter which parameters we give to the
{"mu_hat", Dune::Pymor::Parameter("mu", 1)}, // test case here, since we use test_case_.problem()
{"mu_bar", Dune::Pymor::Parameter("mu", 1)}, // (which is the parametric problem) anyway
{"mu_minimizing", Dune::Pymor::Parameter("mu", 1)}},
partitioning,
boost::numeric_cast< size_t >(num_refinements))
, reference_test_case_({{"mu", Dune::Pymor::Parameter("mu", 1)},
{"mu_hat", Dune::Pymor::Parameter("mu", 1)},
{"mu_bar", Dune::Pymor::Parameter("mu", 1)},
{"mu_minimizing", Dune::Pymor::Parameter("mu", 1)}},
partitioning,
boost::numeric_cast< size_t >(num_refinements + 1))
, discretization_(*test_case_./*reference*/level_provider(0),
test_case_.boundary_info(),
test_case_.problem())
, reference_discretization_(*reference_test_case_.reference_provider(),
reference_test_case_.boundary_info(),
reference_test_case_.problem())
{
auto logger = DSC::TimedLogger().get("OS2014.spe10model1example");
logger.info() << "initializing discretization... " << std::flush;
discretization_.init();
reference_discretization_.init();
logger.info() << "done (grid has " << discretization_.grid_view().indexSet().size(0)
<< " elements, discretization has " << discretization_.ansatz_space()->mapper().size() << " DoFs)"
<< std::endl;
} // ... OS2014Spe10Model1Example(...)
const TestCaseType& test_case() const
{
return test_case_;
}
DiscretizationType& discretization()
{
return discretization_;
}
DiscretizationType* discretization_and_return_ptr() const
{
return new DiscretizationType(discretization_);
}
VectorType project(const std::string expression) const
{
using namespace Dune;
typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;
typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;
DiscreteFunctionType discrete_function(*discretization_.ansatz_space());
typedef Stuff::Functions::Expression< typename DiscreteFunctionType::EntityType,
typename DiscreteFunctionType::DomainFieldType,
DiscreteFunctionType::dimDomain,
typename DiscreteFunctionType::RangeFieldType,
DiscreteFunctionType::dimRange > ExpressionFunctionType;
ExpressionFunctionType func("x", expression);
GDT::Operators::Projection< typename DiscretizationType::GridViewType > projection(discretization_.grid_view());
projection.apply(func, discrete_function);
return discrete_function.vector();
} // ... project(...)
RangeFieldType compute_error(const VectorType& solution,
const std::string product_type = "",
const Dune::Pymor::Parameter mu = Dune::Pymor::Parameter(),
const Dune::Pymor::Parameter mu_product = Dune::Pymor::Parameter())
{
const std::string type = (product_type.empty() && reference_discretization_.available_products().size() == 1)
? reference_discretization_.available_products()[0]
: product_type;
// wrap solution into a discrete function
using namespace Dune;
typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;
typedef GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType > ConstDiscreteFunctionType;
ConstDiscreteFunctionType coarse_solution(*discretization_.ansatz_space(), solution);
// prolong to reference grid view
typedef GDT::DiscreteFunction< AnsatzSpaceType, VectorType > DiscreteFunctionType;
DiscreteFunctionType fine_solution(*reference_discretization_.ansatz_space());
GDT::Operators::Prolongation< typename DiscretizationType::GridViewType >
prolongation_operator(reference_discretization_.grid_view());
prolongation_operator.apply(coarse_solution, fine_solution);
// compute reference solution
DiscreteFunctionType reference_solution(*reference_discretization_.ansatz_space());
reference_discretization_.solve(reference_solution.vector(), mu);
// compute error
const auto product = reference_discretization_.get_product(type).freeze_parameter(mu_product);
const auto difference = reference_solution.vector() - fine_solution.vector();
return std::sqrt(product.apply2(difference, difference));
} // ... compute_error(...)
RangeFieldType compute_jump_norm(const VectorType& solution_vector,
const Dune::Pymor::Parameter mu_product = Dune::Pymor::Parameter())
{
using namespace Dune;
typedef typename DiscretizationType::AnsatzSpaceType AnsatzSpaceType;
typedef GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType > ConstDiscreteFunctionType;
ConstDiscreteFunctionType solution(*discretization_.ansatz_space(), solution_vector);
const auto diffusion_factor = discretization_.problem().diffusion_factor()->with_mu(mu_product);
const auto diffusion_tensor = discretization_.problem().diffusion_tensor()->with_mu(mu_product);
typedef GDT::Products::EllipticSWIPDGPenaltyLocalizable
< typename DiscretizationType::GridViewType,
typename DiscretizationType::ProblemType::DiffusionFactorType::NonparametricType,
ConstDiscreteFunctionType,
ConstDiscreteFunctionType,
RangeFieldType,
typename DiscretizationType::ProblemType::DiffusionTensorType::NonparametricType > ProductType;
ProductType penalty_product(discretization_.grid_view(),
solution,
solution,
*diffusion_factor,
*diffusion_tensor,
2);
return std::sqrt(penalty_product.apply2());
} // ... compute_jump_norm(...)
std::vector< std::string > available_estimators() const
{
return Estimator::available();
}
RangeFieldType estimate(const VectorType& vector,
const std::string type,
const Dune::Pymor::Parameter mu_hat = Dune::Pymor::Parameter(),
const Dune::Pymor::Parameter mu_bar = Dune::Pymor::Parameter(),
const Dune::Pymor::Parameter mu = Dune::Pymor::Parameter())
{
return Estimator::estimate(*discretization_.ansatz_space(),
vector,
discretization_.problem(),
type,
{{"mu_hat", mu_hat},
{"mu_bar", mu_bar},
{"mu", mu},
{"mu_minimizing", Dune::Pymor::Parameter("mu", 0.1)}});
} // ... estimate(...)
public:
TestCaseType test_case_;
TestCaseType reference_test_case_;
DiscretizationType discretization_;
DiscretizationType reference_discretization_;
}; // class OS2014Spe10Model1Example
#endif // DUNE_HDD_EXAMPLES_LINEARELLIPTIC_OS2014_HH
<|endoftext|>
|
<commit_before>/**
* \file
* \brief SignalsReceiverControlBlock class header
*
* \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALSRECEIVERCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALSRECEIVERCONTROLBLOCK_HPP_
#include "distortos/SignalSet.hpp"
#include <cstdint>
union sigval;
namespace distortos
{
class SignalAction;
class SignalInformation;
class SignalInformationQueueWrapper;
class SignalsCatcher;
namespace internal
{
class SignalInformationQueue;
class SignalsCatcherControlBlock;
class ThreadControlBlock;
/// SignalsReceiverControlBlock class is a structure required by threads for "receiving" of signals
class SignalsReceiverControlBlock
{
public:
/**
* \brief SignalsReceiverControlBlock's constructor
*
* \param [in] signalInformationQueueWrapper is a pointer to SignalInformationQueueWrapper for this receiver,
* nullptr to disable queuing of signals for this receiver
* \param [in] signalsCatcher is a pointer to SignalsCatcher for this receiver, nullptr if this receiver cannot
* catch/handle signals
*/
explicit SignalsReceiverControlBlock(SignalInformationQueueWrapper* signalInformationQueueWrapper,
SignalsCatcher* signalsCatcher);
/**
* \brief Accepts (clears) one of signals that are pending.
*
* This should be called when the signal is "accepted".
*
* \param [in] signalNumber is the signal that will be accepted, [0; 31]
*
* \return pair with return code (0 on success, error code otherwise) and SignalInformation object for accepted
* signal; error codes:
* - EAGAIN - no signal specified by \a signalNumber was pending;
* - EINVAL - \a signalNumber value is invalid;
*/
std::pair<int, SignalInformation> acceptPendingSignal(uint8_t signalNumber);
/**
* \brief Hook function executed when delivery of signals is started.
*
* Calls SignalsCatcherControlBlock::deliveryOfSignalsStartedHook().
*
* \attention This function should be called only by the function that delivers signals (<em>deliverSignals()</em>).
*
* \return 0 on success, error code otherwise:
* - ENOTSUP - catching/handling of signals is disabled for this receiver;
*/
int deliveryOfSignalsStartedHook() const;
/**
* \brief Generates signal for associated thread.
*
* Similar to pthread_kill() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html
*
* Adds the signalNumber to set of pending signals. If associated thread is currently waiting for this signal, it
* will be unblocked.
*
* \param [in] signalNumber is the signal that will be generated, [0; 31]
* \param [in] threadControlBlock is a reference to associated ThreadControlBlock
*
* \return 0 on success, error code otherwise:
* - EINVAL - \a signalNumber value is invalid;
* - ENOMEM - amount of free stack is too small to request delivery of signals;
*/
int generateSignal(uint8_t signalNumber, ThreadControlBlock& threadControlBlock);
/**
* \return set of currently pending signals
*/
SignalSet getPendingSignalSet() const;
/**
* \brief Gets SignalAction associated with given signal number.
*
* Similar to sigaction() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html
*
* \param [in] signalNumber is the signal for which the association is requested, [0; 31]
*
* \return pair with return code (0 on success, error code otherwise) and SignalAction that is associated with
* \a signalNumber, default-constructed object if no association was found;
* error codes:
* - EINVAL - \a signalNumber value is invalid;
* - ENOTSUP - catching/handling of signals is disabled for this receiver;
*/
std::pair<int, SignalAction> getSignalAction(uint8_t signalNumber) const;
/**
* \brief Gets signal mask for associated thread.
*
* Similar to pthread_sigmask() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_sigmask.html#
*
* \return SignalSet with signal mask for associated thread
*/
SignalSet getSignalMask() const;
/**
* \brief Queues signal for associated thread.
*
* Similar to sigqueue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigqueue.html
*
* Queues the signalNumber and signal value (sigval union) in associated SignalInformationQueue object. If
* associated thread is currently waiting for this signal, it will be unblocked.
*
* \param [in] signalNumber is the signal that will be queued, [0; 31]
* \param [in] value is the signal value
* \param [in] threadControlBlock is a reference to associated ThreadControlBlock
*
* \return 0 on success, error code otherwise:
* - EAGAIN - no resources are available to queue the signal, maximal number of signals is already queued in
* associated SignalInformationQueue object;
* - EINVAL - \a signalNumber value is invalid;
* - ENOMEM - amount of free stack is too small to request delivery of signals;
* - ENOTSUP - queuing of signals is disabled for this receiver;
*/
int queueSignal(uint8_t signalNumber, sigval value, ThreadControlBlock& threadControlBlock) const;
/**
* \brief Sets association for given signal number.
*
* Similar to sigaction() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html
*
* \param [in] signalNumber is the signal for which the association will be set, [0; 31]
* \param [in] signalAction is a reference to SignalAction that will be associated with given signal number, object
* in internal storage is copy-constructed
*
* \return pair with return code (0 on success, error code otherwise) and SignalAction that was associated with
* \a signalNumber, default-constructed object if no association was found;
* error codes:
* - EAGAIN - no resources are available to associate \a signalNumber with \a signalAction;
* - EINVAL - \a signalNumber value is invalid;
* - ENOTSUP - catching/handling of signals is disabled for this receiver;
*/
std::pair<int, SignalAction> setSignalAction(uint8_t signalNumber, const SignalAction& signalAction);
/**
* \brief Sets signal mask for associated thread.
*
* Similar to pthread_sigmask() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_sigmask.html#
*
* \param [in] signalMask is the SignalSet with new signal mask for associated thread
* \param [in] requestDelivery selects whether delivery of signals will be requested if any pending signal is
* unblocked (true) or not (false)
*
* \return 0 on success, error code otherwise:
* - ENOMEM - amount of free stack is too small to request delivery of signals;
* - ENOTSUP - catching/handling of signals is disabled for this receiver;
*/
int setSignalMask(SignalSet signalMask, bool requestDelivery);
/**
* \param [in] signalSet is a pointer to set of signals that will be "waited for", nullptr when wait was terminated
*/
void setWaitingSignalSet(const SignalSet* const signalSet)
{
waitingSignalSet_ = signalSet;
}
private:
/**
* \brief Checks whether signal is ignored.
*
* Signal is ignored if it has no SignalAction object associated. Signal is never ignored if catching/handling of
* signals is disabled for this receiver.
*
* \param [in] signalNumber is the signal for which the check will be performed, [0; 31]
*
* \return pair with return code (0 on success, error code otherwise) and boolean telling whether the signal is
* ignored (true) or not (false);
* error codes:
* - EINVAL - \a signalNumber value is invalid;
*/
std::pair<int, bool> isSignalIgnored(uint8_t signalNumber) const;
/**
* \brief Actions executed after signal is "generated" with generateSignal() or queueSignal().
*
* If associated thread is currently waiting for the signal that was generated, it will be unblocked.
*
* \param [in] signalNumber is the signal that was generated, [0; 31]
* \param [in] threadControlBlock is a reference to associated ThreadControlBlock
*
* \return 0 on success, error code otherwise:
* - EINVAL - \a signalNumber value is invalid;
* - ENOMEM - amount of free stack is too small to request delivery of signals;
*/
int postGenerate(uint8_t signalNumber, ThreadControlBlock& threadControlBlock) const;
/// set of pending signals
SignalSet pendingSignalSet_;
/// pointer to set of "waited for" signals, nullptr if associated thread is not waiting for any signals
const SignalSet* waitingSignalSet_;
/// pointer to SignalsCatcherControlBlock for this receiver, nullptr if this receiver cannot catch/handle signals
SignalsCatcherControlBlock* signalsCatcherControlBlock_;
/// pointer to SignalInformationQueue for this receiver, nullptr if this receiver cannot queue signals
SignalInformationQueue* signalInformationQueue_;
};
} // namespace internal
} // namespace distortos
#endif // INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALSRECEIVERCONTROLBLOCK_HPP_
<commit_msg>Simplify comments in SignalsReceiverControlBlock.hpp<commit_after>/**
* \file
* \brief SignalsReceiverControlBlock class header
*
* \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALSRECEIVERCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALSRECEIVERCONTROLBLOCK_HPP_
#include "distortos/SignalSet.hpp"
#include <cstdint>
union sigval;
namespace distortos
{
class SignalAction;
class SignalInformation;
class SignalInformationQueueWrapper;
class SignalsCatcher;
namespace internal
{
class SignalInformationQueue;
class SignalsCatcherControlBlock;
class ThreadControlBlock;
/// SignalsReceiverControlBlock class is a structure required by threads for "receiving" of signals
class SignalsReceiverControlBlock
{
public:
/**
* \brief SignalsReceiverControlBlock's constructor
*
* \param [in] signalInformationQueueWrapper is a pointer to SignalInformationQueueWrapper for this receiver,
* nullptr to disable queuing of signals for this receiver
* \param [in] signalsCatcher is a pointer to SignalsCatcher for this receiver, nullptr if this receiver cannot
* catch/handle signals
*/
explicit SignalsReceiverControlBlock(SignalInformationQueueWrapper* signalInformationQueueWrapper,
SignalsCatcher* signalsCatcher);
/**
* \brief Accepts (clears) one of signals that are pending.
*
* This should be called when the signal is "accepted".
*
* \param [in] signalNumber is the signal that will be accepted, [0; 31]
*
* \return pair with return code (0 on success, error code otherwise) and SignalInformation object for accepted
* signal; error codes:
* - EAGAIN - no signal specified by \a signalNumber was pending;
* - error codes returned by SignalInformationQueue::acceptQueuedSignal() (except EAGAIN);
* - error codes returned by SignalSet::remove();
* - error codes returned by SignalSet::test();
*/
std::pair<int, SignalInformation> acceptPendingSignal(uint8_t signalNumber);
/**
* \brief Hook function executed when delivery of signals is started.
*
* Calls SignalsCatcherControlBlock::deliveryOfSignalsStartedHook().
*
* \attention This function should be called only by the function that delivers signals (<em>deliverSignals()</em>).
*
* \return 0 on success, error code otherwise:
* - ENOTSUP - catching/handling of signals is disabled for this receiver;
*/
int deliveryOfSignalsStartedHook() const;
/**
* \brief Generates signal for associated thread.
*
* Similar to pthread_kill() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html
*
* Adds the signalNumber to set of pending signals. If associated thread is currently waiting for this signal, it
* will be unblocked.
*
* \param [in] signalNumber is the signal that will be generated, [0; 31]
* \param [in] threadControlBlock is a reference to associated ThreadControlBlock
*
* \return 0 on success, error code otherwise:
* - error codes returned by isSignalIgnored();
* - error codes returned by postGenerate();
*/
int generateSignal(uint8_t signalNumber, ThreadControlBlock& threadControlBlock);
/**
* \return set of currently pending signals
*/
SignalSet getPendingSignalSet() const;
/**
* \brief Gets SignalAction associated with given signal number.
*
* Similar to sigaction() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html
*
* \param [in] signalNumber is the signal for which the association is requested, [0; 31]
*
* \return pair with return code (0 on success, error code otherwise) and SignalAction that is associated with
* \a signalNumber, default-constructed object if no association was found; error codes:
* - ENOTSUP - catching/handling of signals is disabled for this receiver;
* - error codes returned by SignalsCatcherControlBlock::getAssociation();
*/
std::pair<int, SignalAction> getSignalAction(uint8_t signalNumber) const;
/**
* \brief Gets signal mask for associated thread.
*
* Similar to pthread_sigmask() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_sigmask.html#
*
* \return SignalSet with signal mask for associated thread
*/
SignalSet getSignalMask() const;
/**
* \brief Queues signal for associated thread.
*
* Similar to sigqueue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigqueue.html
*
* Queues the signalNumber and signal value (sigval union) in associated SignalInformationQueue object. If
* associated thread is currently waiting for this signal, it will be unblocked.
*
* \param [in] signalNumber is the signal that will be queued, [0; 31]
* \param [in] value is the signal value
* \param [in] threadControlBlock is a reference to associated ThreadControlBlock
*
* \return 0 on success, error code otherwise:
* - ENOTSUP - queuing of signals is disabled for this receiver;
* - error codes returned by isSignalIgnored();
* - error codes returned by postGenerate();
* - error codes returned by SignalInformationQueue::queueSignal();
*/
int queueSignal(uint8_t signalNumber, sigval value, ThreadControlBlock& threadControlBlock) const;
/**
* \brief Sets association for given signal number.
*
* Similar to sigaction() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html
*
* \param [in] signalNumber is the signal for which the association will be set, [0; 31]
* \param [in] signalAction is a reference to SignalAction that will be associated with given signal number, object
* in internal storage is copy-constructed
*
* \return pair with return code (0 on success, error code otherwise) and SignalAction that was associated with
* \a signalNumber, default-constructed object if no association was found; error codes:
* - ENOTSUP - catching/handling of signals is disabled for this receiver;
* - error codes returned by acceptPendingSignal() (except EAGAIN);
* - error codes returned by SignalsCatcherControlBlock::setAssociation();
*/
std::pair<int, SignalAction> setSignalAction(uint8_t signalNumber, const SignalAction& signalAction);
/**
* \brief Sets signal mask for associated thread.
*
* Similar to pthread_sigmask() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_sigmask.html#
*
* \param [in] signalMask is the SignalSet with new signal mask for associated thread
* \param [in] requestDelivery selects whether delivery of signals will be requested if any pending signal is
* unblocked (true) or not (false)
*
* \return 0 on success, error code otherwise:
* - ENOTSUP - catching/handling of signals is disabled for this receiver;
* - error codes returned by SignalsCatcherControlBlock::setSignalMask();
*/
int setSignalMask(SignalSet signalMask, bool requestDelivery);
/**
* \param [in] signalSet is a pointer to set of signals that will be "waited for", nullptr when wait was terminated
*/
void setWaitingSignalSet(const SignalSet* const signalSet)
{
waitingSignalSet_ = signalSet;
}
private:
/**
* \brief Checks whether signal is ignored.
*
* Signal is ignored if it has no SignalAction object associated. Signal is never ignored if catching/handling of
* signals is disabled for this receiver.
*
* \param [in] signalNumber is the signal for which the check will be performed, [0; 31]
*
* \return pair with return code (0 on success, error code otherwise) and boolean telling whether the signal is
* ignored (true) or not (false); error codes:
* - EINVAL - \a signalNumber value is invalid;
*/
std::pair<int, bool> isSignalIgnored(uint8_t signalNumber) const;
/**
* \brief Actions executed after signal is "generated" with generateSignal() or queueSignal().
*
* If associated thread is currently waiting for the signal that was generated, it will be unblocked.
*
* \param [in] signalNumber is the signal that was generated, [0; 31]
* \param [in] threadControlBlock is a reference to associated ThreadControlBlock
*
* \return 0 on success, error code otherwise:
* - error codes returned by SignalsCatcherControlBlock::postGenerate();
*/
int postGenerate(uint8_t signalNumber, ThreadControlBlock& threadControlBlock) const;
/// set of pending signals
SignalSet pendingSignalSet_;
/// pointer to set of "waited for" signals, nullptr if associated thread is not waiting for any signals
const SignalSet* waitingSignalSet_;
/// pointer to SignalsCatcherControlBlock for this receiver, nullptr if this receiver cannot catch/handle signals
SignalsCatcherControlBlock* signalsCatcherControlBlock_;
/// pointer to SignalInformationQueue for this receiver, nullptr if this receiver cannot queue signals
SignalInformationQueue* signalInformationQueue_;
};
} // namespace internal
} // namespace distortos
#endif // INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALSRECEIVERCONTROLBLOCK_HPP_
<|endoftext|>
|
<commit_before>/************************************************
* libgo sample12
************************************************
* 这是一个协程监听器的例子
* 使用协程监听器 co_listener 可以监听协程的
* 创建销毁等事件,也可以进行异常处理
************************************************/
#include "coroutine.h"
#include <iostream>
using namespace std;
//协程监听器的调用过程:
// (正常运行完成)
// ---> onCompleted -->
// | |
// onCreated --> onStart ---> onFinished
// | |
// ---> onException -->
// (运行时抛出未捕获的异常)
//
//!!注意协程监听器回调方法均不能抛出异常,如果可能有异常抛出,请在回调方法内自行 try...catch 消化掉
//覆盖 co::co_listener 的虚函数实现回调方法
class CoListenerSample: public co_listener {
public:
/**
* 协程被创建时被调用
* (注意此时并未运行在协程中)
*
* @prarm task_id 协程ID
* @prarm eptr
*/
virtual void onCreated(uint64_t task_id) noexcept {
cout << "onCreated task_id=" << task_id << endl;
}
/**
* 协程开始运行
* (本方法运行在协程中)
*
* @prarm task_id 协程ID
* @prarm eptr
*/
virtual void onStart(uint64_t task_id) noexcept {
cout << "onStart task_id=" << task_id << endl;
}
/**
* 协程切入后(包括协程首次运行的时候)调用
* 协程首次运行会在onStart之前调用。
* (本方法运行在协程中)
*
* @prarm task_id 协程ID
* @prarm eptr
*/
virtual void onSwapIn(uint64_t task_id) noexcept {
cout << "onSwapIn task_id=" << task_id << endl;
}
/**
* 协程切出前调用
* (本方法运行在协程中)
*
* @prarm task_id 协程ID
* @prarm eptr
*/
virtual void onSwapOut(uint64_t task_id) noexcept {
cout << "onSwapOut task_id=" << task_id << endl;
}
/**
* 协程正常运行结束(无异常抛出)
* (本方法运行在协程中)
*
* @prarm task_id 协程ID
*/
virtual void onCompleted(uint64_t task_id) noexcept {
cout << "onCompleted task_id=" << task_id << endl;
}
/**
* 协程抛出未被捕获的异常(本方法运行在协程中)
* @prarm task_id 协程ID
* @prarm eptr 抛出的异常对象指针,可对本指针赋值以修改异常对象,
* 异常将使用 CoroutineOptions.exception_handle 中
* 配置的方式处理;赋值为nullptr则表示忽略此异常
* !!注意:当 exception_handle 配置为 immedaitely_throw 时本事件
* !!与 onFinished() 均失效,异常发生时将直接抛出并中断程序的运行,同时生成coredump
*/
virtual void onException(uint64_t task_id, std::exception_ptr& eptr) noexcept {
cout << "onException task_id=" << task_id << " ";
try {
rethrow_exception(eptr);
} catch (exception& e) {
cout << "onException e=" << e.what() << endl;
} catch (...) {
cout << "unknow exception." << endl;
}
//替换掉异常:
//eptr = make_exception_ptr(runtime_error("runtime_error task_id=" + to_string(task_id)));
//包装异常:
//try {
// std::rethrow_exception(eptr);
//} catch (...) {
// try {
// std::throw_with_nested(std::runtime_error("wrap exception"));
// } catch (...) {
// eptr = std::current_exception();
// }
//}
//如果使用以下赋值,就能忽略异常:
//eptr = nullptr;
}
/**
* 协程运行完成,if(eptr) 为false说明协程正常结束,为true说明协程抛出了了异常
*
* @prarm task_id 协程ID
* @prarm eptr 抛出的异常对象指针,此处只能读取不允许修改其值
*/
virtual void onFinished(uint64_t task_id, const std::exception_ptr eptr) noexcept {
cout << "onFinished task_id=" << task_id << " ";
if (eptr) {
try {
rethrow_exception(eptr);
} catch (exception& e) {
cout << "e=" << e.what() << endl;
} catch (...) {
cout << "unknow exception." << endl;
}
} else {
cout << " completed." << endl;
}
}
};
int main(int argc, char** argv) {
CoListenerSample listener;
//设置协程监听器,如果设置为NULL则为取消监听
set_co_listener(&listener);
//将异常的处理方式置为输出日志
co_sched.GetOptions().debug |= co::dbg_exception;
co_sched.GetOptions().exception_handle = co::eCoExHandle::debugger_only;
go[] {
cout << "i am task=" << co_sched.GetCurrentTaskID() << endl;
cout << "task " << co_sched.GetCurrentTaskID() << " going to sleep for a while" << endl;
co_sleep(1);
cout << "task " << co_sched.GetCurrentTaskID() << " returns" << endl;
};
go[] {
cout << "i am task=" << co_sched.GetCurrentTaskID() << endl;
cout << "task " << co_sched.GetCurrentTaskID() << " going to sleep for a while" << endl;
co_sleep(1);
throw logic_error("wtf!!??");
cout << "task " << co_sched.GetCurrentTaskID() << " returns" << endl;
};
co_sched.RunUntilNoTask();
return 0;
}
<commit_msg>sample12_listener.cpp: comment change<commit_after>/************************************************
* libgo sample12
************************************************
* 这是一个协程监听器的例子
* 使用协程监听器 co_listener 可以监听协程的
* 创建销毁等事件,也可以进行异常处理
************************************************/
#include "coroutine.h"
#include <iostream>
using namespace std;
//协程监听器的调用过程:
// s: Scheduler,表示该方法运行在调度器上下文中
// c: Coroutine,表示该方法运行在协程上下文中
// (正常运行完成)
// -->[c]onCompleted->
// | |
// [s]onCreated-->[s]onSwapIn-->[c]onStart->*--->[c]onSwapOut-- -->[c]onFinished-->[c]onSwapOut
// |\ | |
// | \<-[s]onSwapIn--V |
// | |
// -->[c]onException->
//
//!!注意协程监听器回调方法均不能抛出异常,如果可能有异常抛出,请在回调方法内自行 try...catch 消化掉
//覆盖 co::co_listener 的虚函数实现回调方法
class CoListenerSample: public co_listener {
public:
/**
* 协程被创建时被调用
* (注意此时并未运行在协程中)
*
* @prarm task_id 协程ID
* @prarm eptr
*/
virtual void onCreated(uint64_t task_id) noexcept {
cout << "onCreated task_id=" << task_id << endl;
}
/**
* 每次协程切入前调用
* (注意此时并未运行在协程中)
*
* @prarm task_id 协程ID
* @prarm eptr
*/
virtual void onSwapIn(uint64_t task_id) noexcept {
cout << "onSwapIn task_id=" << task_id << endl;
}
/**
* 协程开始运行
* (本方法运行在协程中)
*
* @prarm task_id 协程ID
* @prarm eptr
*/
virtual void onStart(uint64_t task_id) noexcept {
cout << "onStart task_id=" << task_id << endl;
}
/**
* 每次协程切出前调用
* (本方法运行在协程中)
*
* @prarm task_id 协程ID
* @prarm eptr
*/
virtual void onSwapOut(uint64_t task_id) noexcept {
cout << "onSwapOut task_id=" << task_id << endl;
}
/**
* 协程正常运行结束(无异常抛出)
* (本方法运行在协程中)
*
* @prarm task_id 协程ID
*/
virtual void onCompleted(uint64_t task_id) noexcept {
cout << "onCompleted task_id=" << task_id << endl;
}
/**
* 协程抛出未被捕获的异常(本方法运行在协程中)
* @prarm task_id 协程ID
* @prarm eptr 抛出的异常对象指针,可对本指针赋值以修改异常对象,
* 异常将使用 CoroutineOptions.exception_handle 中
* 配置的方式处理;赋值为nullptr则表示忽略此异常
* !!注意:当 exception_handle 配置为 immedaitely_throw 时本事件
* !!与 onFinished() 均失效,异常发生时将直接抛出并中断程序的运行,同时生成coredump
*/
virtual void onException(uint64_t task_id, std::exception_ptr& eptr) noexcept {
cout << "onException task_id=" << task_id << " ";
try {
rethrow_exception(eptr);
} catch (exception& e) {
cout << "onException e=" << e.what() << endl;
} catch (...) {
cout << "unknow exception." << endl;
}
//替换掉异常:
//eptr = make_exception_ptr(runtime_error("runtime_error task_id=" + to_string(task_id)));
//包装异常:
//try {
// std::rethrow_exception(eptr);
//} catch (...) {
// try {
// std::throw_with_nested(std::runtime_error("wrap exception"));
// } catch (...) {
// eptr = std::current_exception();
// }
//}
//如果使用以下赋值,就能忽略异常:
//eptr = nullptr;
}
/**
* 协程运行完成,if(eptr) 为false说明协程正常结束,为true说明协程抛出了了异常
*
* @prarm task_id 协程ID
* @prarm eptr 抛出的异常对象指针,此处只能读取不允许修改其值
*/
virtual void onFinished(uint64_t task_id, const std::exception_ptr eptr) noexcept {
cout << "onFinished task_id=" << task_id << " ";
if (eptr) {
try {
rethrow_exception(eptr);
} catch (exception& e) {
cout << "e=" << e.what() << endl;
} catch (...) {
cout << "unknow exception." << endl;
}
} else {
cout << " completed." << endl;
}
}
};
int main(int argc, char** argv) {
CoListenerSample listener;
//设置协程监听器,如果设置为NULL则为取消监听
set_co_listener(&listener);
//将异常的处理方式置为输出日志
co_sched.GetOptions().debug |= co::dbg_exception;
co_sched.GetOptions().exception_handle = co::eCoExHandle::debugger_only;
go[] {
cout << "i am task=" << co_sched.GetCurrentTaskID() << endl;
cout << "task " << co_sched.GetCurrentTaskID() << " going to sleep for a while" << endl;
co_sleep(1);
cout << "task " << co_sched.GetCurrentTaskID() << " returns" << endl;
};
go[] {
cout << "i am task=" << co_sched.GetCurrentTaskID() << endl;
cout << "task " << co_sched.GetCurrentTaskID() << " going to sleep for a while" << endl;
co_sleep(1);
throw logic_error("wtf!!??");
cout << "task " << co_sched.GetCurrentTaskID() << " returns" << endl;
};
co_sched.RunUntilNoTask();
return 0;
}
<|endoftext|>
|
<commit_before>#include <agency/execution_policy.hpp>
#include <mutex>
#include <iostream>
#include <thread>
#include <cassert>
// this is just like std::mutex, except it has a move constructor
// the move constructor just acts like the default constructor
class movable_mutex
{
public:
constexpr movable_mutex() = default;
movable_mutex(const movable_mutex&) = delete;
movable_mutex(movable_mutex&&)
: mut_()
{}
void lock()
{
mut_.lock();
}
void unlock()
{
mut_.unlock();
}
private:
std::mutex mut_;
};
// this function implements a single concurrent ping pong match
size_t ping_pong_match(agency::concurrent_agent& self, const std::vector<std::string>& names, int num_volleys, movable_mutex& mut, int& ball)
{
auto name = names[self.index()];
for(int next_state = self.index();
(next_state < num_volleys) && (ball >= 0);
next_state += 2)
{
// wait for the next volley
while(ball >= 0 && ball != next_state)
{
mut.lock();
std::cout << name << " waiting for return" << std::endl;
mut.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
mut.lock();
if(ball == -1)
{
std::cout << name << " wins!" << std::endl;
}
else
{
// try to return the ball
if(std::rand() % 10 == 0)
{
// whiff -- declare outself the loser
ball = -self.index() - 1;
std::cout << "whiff... " << name << " loses!" << std::endl;
}
else
{
// successful return
ball += 1;
std::cout << name << "! ball is now " << ball << std::endl;
}
}
mut.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// decode who lost the match
int loser = (ball > 0) ? 1 : -(ball + 1);
// return the winner
return loser ^ 1;
}
// this function implements a two concurrent semifinals ping pong matches
// followed by a single final ping pong match
void ping_pong_tournament(agency::concurrent_group<agency::concurrent_agent>& self,
const std::vector<std::vector<std::string>>& semifinal_contestants,
int num_volleys,
movable_mutex& mut,
int& ball,
std::vector<std::string>& final_contestants)
{
if(self.inner().index() == 0)
{
if(self.outer().index() == 0)
{
std::cout << "Starting semifinal matches..." << std::endl;
}
self.outer().wait();
}
self.inner().wait();
// play the semifinals matches
auto semifinal_winner_idx = ping_pong_match(self.inner(), semifinal_contestants[self.outer().index()], num_volleys, mut, ball);
if(self.inner().index() == 0)
{
// the first agent of each group reports who won the semifinal match
auto semifinal_winner = semifinal_contestants[self.outer().index()][semifinal_winner_idx];
final_contestants[self.outer().index()] = semifinal_winner;
// have the first player of each group wait for the other group
self.outer().wait();
}
// have each inner group wait for each other
self.inner().wait();
// group 0 plays the final match
// group 1 sits it out
if(self.outer().index() == 0)
{
// agent 0 initialzes the shared variables for the final match
if(self.inner().index() == 0)
{
ball = 0;
std::cout << std::endl << final_contestants[0] << " and " << final_contestants[1] << " starting the final match..." << std::endl;
}
// wait until agent 0 initializes the shared variables before starting the final match
self.inner().wait();
// play the final match
auto final_winner_idx = ping_pong_match(self.inner(), final_contestants, num_volleys, mut, ball);
// have agent 0 of group 0 report the winner
if(self.inner().index() == 0)
{
std::cout << std::endl << final_contestants[final_winner_idx] << " is the champion!" << std::endl;
}
}
}
int main()
{
using namespace agency;
using namespace std;
size_t num_volleys = 20;
vector<vector<string>> names = {{"ping", "pong"}, {"foo", "bar"}};
bulk_invoke(con(2, con(2)), ping_pong_tournament, names, 20, share<0,movable_mutex>(), share<1,int>(), share<0,vector<string>>(2));
return 0;
}
<commit_msg>change the names of some variables<commit_after>#include <agency/execution_policy.hpp>
#include <mutex>
#include <iostream>
#include <thread>
#include <cassert>
// this is just like std::mutex, except it has a move constructor
// the move constructor just acts like the default constructor
class movable_mutex
{
public:
constexpr movable_mutex() = default;
movable_mutex(const movable_mutex&) = delete;
movable_mutex(movable_mutex&&)
: mut_()
{}
void lock()
{
mut_.lock();
}
void unlock()
{
mut_.unlock();
}
private:
std::mutex mut_;
};
// this function implements a single concurrent ping pong match
size_t ping_pong_match(agency::concurrent_agent& self, const std::vector<std::string>& names, int num_volleys, movable_mutex& mut, int& ball)
{
// agent 0 initializes the ball
if(self.index() == 0)
{
ball = 0;
}
self.wait();
auto name = names[self.index()];
for(int next_state = self.index();
(next_state < num_volleys) && (ball >= 0);
next_state += 2)
{
// wait for the next volley
while(ball >= 0 && ball != next_state)
{
mut.lock();
std::cout << name << " waiting for return" << std::endl;
mut.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
mut.lock();
if(ball == -1)
{
std::cout << name << " wins!" << std::endl;
}
else
{
// try to return the ball
if(std::rand() % 10 == 0)
{
// whiff -- declare outself the loser
ball = -self.index() - 1;
std::cout << "whiff... " << name << " loses!" << std::endl;
}
else
{
// successful return
ball += 1;
std::cout << name << "! ball is now " << ball << std::endl;
}
}
mut.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// decode who lost the match
int loser = (ball > 0) ? 1 : -(ball + 1);
// return the winner
return loser ^ 1;
}
// this function implements a two concurrent semifinals ping pong matches
// followed by a single final ping pong match
void ping_pong_tournament(agency::concurrent_group<agency::concurrent_agent>& self,
const std::vector<std::vector<std::string>>& semifinalists,
int num_volleys,
movable_mutex& mut,
int& ball,
std::vector<std::string>& finalists)
{
if(self.inner().index() == 0)
{
if(self.outer().index() == 0)
{
std::cout << "Starting semifinal matches..." << std::endl;
}
self.outer().wait();
}
self.inner().wait();
// play the semifinals matches
auto semifinal_winner_idx = ping_pong_match(self.inner(), semifinalists[self.outer().index()], num_volleys, mut, ball);
if(self.inner().index() == 0)
{
// the first agent of each group reports who won the semifinal match
auto semifinal_winner = semifinalists[self.outer().index()][semifinal_winner_idx];
finalists[self.outer().index()] = semifinal_winner;
// have the first player of each group wait for the other group
self.outer().wait();
}
// have each inner group wait for each other
self.inner().wait();
// group 0 plays the final match while group 1 sits it out
if(self.outer().index() == 0)
{
// agent 0 initializes the contestant names for the final match
if(self.inner().index() == 0)
{
std::cout << std::endl << finalists[0] << " and " << finalists[1] << " starting the final match..." << std::endl;
}
// wait until agent 0 initializes the contestant names before starting the final match
self.inner().wait();
// play the final match
auto final_winner_idx = ping_pong_match(self.inner(), finalists, num_volleys, mut, ball);
// have agent 0 of group 0 report the winner
if(self.inner().index() == 0)
{
std::cout << std::endl << finalists[final_winner_idx] << " is the tournament champion!" << std::endl;
}
}
}
int main()
{
using namespace agency;
using namespace std;
size_t num_volleys = 20;
vector<vector<string>> semifinalists = {{"ping", "pong"}, {"foo", "bar"}};
bulk_invoke(con(2, con(2)), ping_pong_tournament, semifinalists, num_volleys, share<0,movable_mutex>(), share<1,int>(), share<0,vector<string>>(2));
return 0;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "playlistmodel.h"
#include <QtCore/qfileinfo.h>
#include <QtCore/qurl.h>
#include <qmediaplaylist.h>
PlaylistModel::PlaylistModel(QObject *parent)
: QAbstractItemModel(parent)
, m_playlist(0)
{
}
int PlaylistModel::rowCount(const QModelIndex &parent) const
{
return m_playlist && !parent.isValid() ? m_playlist->mediaCount() : 0;
}
int PlaylistModel::columnCount(const QModelIndex &parent) const
{
return !parent.isValid() ? ColumnCount : 0;
}
QModelIndex PlaylistModel::index(int row, int column, const QModelIndex &parent) const
{
return m_playlist && !parent.isValid()
&& row >= 0 && row < m_playlist->mediaCount()
&& column >= 0 && column < ColumnCount
? createIndex(row, column)
: QModelIndex();
}
QModelIndex PlaylistModel::parent(const QModelIndex &child) const
{
Q_UNUSED(child);
return QModelIndex();
}
QVariant PlaylistModel::data(const QModelIndex &index, int role) const
{
if (index.isValid() && role == Qt::DisplayRole) {
QVariant value = m_data[index];
if (!value.isValid() && index.column() == Title) {
QUrl location = m_playlist->media(index.row()).canonicalUrl();
return QFileInfo(location.path()).fileName();
}
return value;
}
return QVariant();
}
QMediaPlaylist *PlaylistModel::playlist() const
{
return m_playlist;
}
void PlaylistModel::setPlaylist(QMediaPlaylist *playlist)
{
if (m_playlist) {
disconnect(m_playlist, SIGNAL(mediaAboutToBeInserted(int,int)), this, SLOT(beginInsertItems(int,int)));
disconnect(m_playlist, SIGNAL(mediaInserted(int,int)), this, SLOT(endInsertItems()));
disconnect(m_playlist, SIGNAL(mediaAboutToBeRemoved(int,int)), this, SLOT(beginRemoveItems(int,int)));
disconnect(m_playlist, SIGNAL(mediaRemoved(int,int)), this, SLOT(endRemoveItems()));
disconnect(m_playlist, SIGNAL(mediaChanged(int,int)), this, SLOT(changeItems(int,int)));
}
m_playlist = playlist;
if (m_playlist) {
connect(m_playlist, SIGNAL(mediaAboutToBeInserted(int,int)), this, SLOT(beginInsertItems(int,int)));
connect(m_playlist, SIGNAL(mediaInserted(int,int)), this, SLOT(endInsertItems()));
connect(m_playlist, SIGNAL(mediaAboutToBeRemoved(int,int)), this, SLOT(beginRemoveItems(int,int)));
connect(m_playlist, SIGNAL(mediaRemoved(int,int)), this, SLOT(endRemoveItems()));
connect(m_playlist, SIGNAL(mediaChanged(int,int)), this, SLOT(changeItems(int,int)));
}
reset();
}
bool PlaylistModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
Q_UNUSED(role);
m_data[index] = value;
emit dataChanged(index, index);
return true;
}
void PlaylistModel::beginInsertItems(int start, int end)
{
m_data.clear();
beginInsertRows(QModelIndex(), start, end);
}
void PlaylistModel::endInsertItems()
{
endInsertRows();
}
void PlaylistModel::beginRemoveItems(int start, int end)
{
m_data.clear();
beginRemoveRows(QModelIndex(), start, end);
}
void PlaylistModel::endRemoveItems()
{
endInsertRows();
}
void PlaylistModel::changeItems(int start, int end)
{
m_data.clear();
emit dataChanged(index(start,0), index(end,ColumnCount));
}
<commit_msg>QAbstractItemMode::reset() is deprecated, don't use it<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "playlistmodel.h"
#include <QtCore/qfileinfo.h>
#include <QtCore/qurl.h>
#include <qmediaplaylist.h>
PlaylistModel::PlaylistModel(QObject *parent)
: QAbstractItemModel(parent)
, m_playlist(0)
{
}
int PlaylistModel::rowCount(const QModelIndex &parent) const
{
return m_playlist && !parent.isValid() ? m_playlist->mediaCount() : 0;
}
int PlaylistModel::columnCount(const QModelIndex &parent) const
{
return !parent.isValid() ? ColumnCount : 0;
}
QModelIndex PlaylistModel::index(int row, int column, const QModelIndex &parent) const
{
return m_playlist && !parent.isValid()
&& row >= 0 && row < m_playlist->mediaCount()
&& column >= 0 && column < ColumnCount
? createIndex(row, column)
: QModelIndex();
}
QModelIndex PlaylistModel::parent(const QModelIndex &child) const
{
Q_UNUSED(child);
return QModelIndex();
}
QVariant PlaylistModel::data(const QModelIndex &index, int role) const
{
if (index.isValid() && role == Qt::DisplayRole) {
QVariant value = m_data[index];
if (!value.isValid() && index.column() == Title) {
QUrl location = m_playlist->media(index.row()).canonicalUrl();
return QFileInfo(location.path()).fileName();
}
return value;
}
return QVariant();
}
QMediaPlaylist *PlaylistModel::playlist() const
{
return m_playlist;
}
void PlaylistModel::setPlaylist(QMediaPlaylist *playlist)
{
if (m_playlist) {
disconnect(m_playlist, SIGNAL(mediaAboutToBeInserted(int,int)), this, SLOT(beginInsertItems(int,int)));
disconnect(m_playlist, SIGNAL(mediaInserted(int,int)), this, SLOT(endInsertItems()));
disconnect(m_playlist, SIGNAL(mediaAboutToBeRemoved(int,int)), this, SLOT(beginRemoveItems(int,int)));
disconnect(m_playlist, SIGNAL(mediaRemoved(int,int)), this, SLOT(endRemoveItems()));
disconnect(m_playlist, SIGNAL(mediaChanged(int,int)), this, SLOT(changeItems(int,int)));
}
beginResetModel();
m_playlist = playlist;
if (m_playlist) {
connect(m_playlist, SIGNAL(mediaAboutToBeInserted(int,int)), this, SLOT(beginInsertItems(int,int)));
connect(m_playlist, SIGNAL(mediaInserted(int,int)), this, SLOT(endInsertItems()));
connect(m_playlist, SIGNAL(mediaAboutToBeRemoved(int,int)), this, SLOT(beginRemoveItems(int,int)));
connect(m_playlist, SIGNAL(mediaRemoved(int,int)), this, SLOT(endRemoveItems()));
connect(m_playlist, SIGNAL(mediaChanged(int,int)), this, SLOT(changeItems(int,int)));
}
endResetModel();
}
bool PlaylistModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
Q_UNUSED(role);
m_data[index] = value;
emit dataChanged(index, index);
return true;
}
void PlaylistModel::beginInsertItems(int start, int end)
{
m_data.clear();
beginInsertRows(QModelIndex(), start, end);
}
void PlaylistModel::endInsertItems()
{
endInsertRows();
}
void PlaylistModel::beginRemoveItems(int start, int end)
{
m_data.clear();
beginRemoveRows(QModelIndex(), start, end);
}
void PlaylistModel::endRemoveItems()
{
endInsertRows();
}
void PlaylistModel::changeItems(int start, int end)
{
m_data.clear();
emit dataChanged(index(start,0), index(end,ColumnCount));
}
<|endoftext|>
|
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This pass optimizes tf_saved_model.global_tensor ops.
#include <map>
#include <set>
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "mlir/IR/Builders.h" // TF:llvm-project
#include "mlir/IR/Module.h" // TF:llvm-project
#include "mlir/Pass/Pass.h" // TF:llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.h"
namespace mlir {
namespace tf_saved_model {
namespace {
struct OptimizeGlobalTensorsPass
: public ModulePass<OptimizeGlobalTensorsPass> {
void runOnModule() override;
};
// A global tensor is bound to arguments of multiple funcs.
// This struct tracks which funcs (and which argument to that func) the global
// tensor is bound to.
struct GlobalTensorUse {
mutable FuncOp func;
size_t arg_index;
};
using GlobalTensorUsesMap =
std::map<GlobalTensorOp, std::vector<GlobalTensorUse>>;
// TODO(silvasean): Are there other read-only variable ops?
// It would be nice if we eventually had an interface that we could use
// to determine if an op is read-only and how to rewrite it.
// For now, IsReadOnlyVariableOp and RewriteReadOnlyVariableOpToTensorOp need to
// be keep in sync.
bool IsReadOnlyVariableOp(Operation* op) { return isa<TF::ReadVariableOp>(op); }
void RewriteReadOnlyVariableOpToTensorOp(Operation* op, Value tensor_value) {
auto read_variable = cast<TF::ReadVariableOp>(op);
read_variable.value().replaceAllUsesWith(tensor_value);
}
bool IsFreezable(GlobalTensorOp global_tensor,
ArrayRef<GlobalTensorUse> global_tensor_uses) {
// If this tensor is already immutable, don't freeze it.
if (!global_tensor.is_mutable()) {
return false;
}
// Can't freeze if exported.
if (IsExported(global_tensor)) {
return false;
}
// Can't freeze if it is used by anything that we aren't sure is read-only.
// Right now, this uses a very simple algorithm that only checks the top-level
// func for tf.ReadVariableOp. If the resource is passed into other functions
// or control flow, we fail to prove it is freezable even though we could.
for (auto& global_tensor_use : global_tensor_uses) {
auto arg = global_tensor_use.func.getArgument(global_tensor_use.arg_index);
for (auto user : arg.getUsers()) {
if (!IsReadOnlyVariableOp(user)) {
return false;
}
}
}
return true;
}
static GlobalTensorUsesMap CreateGlobalTensorUsesMap(ModuleOp module) {
GlobalTensorUsesMap global_tensor_uses;
SymbolTable symbol_table(module);
for (auto func : module.getOps<FuncOp>()) {
for (size_t i = 0, e = func.getNumArguments(); i < e; i++) {
auto sym =
func.getArgAttrOfType<SymbolRefAttr>(i, "tf_saved_model.bound_input");
if (!sym) {
continue;
}
auto global_tensor = symbol_table.lookup<GlobalTensorOp>(
sym.cast<FlatSymbolRefAttr>().getValue());
global_tensor_uses[global_tensor].push_back({func, i});
}
}
return global_tensor_uses;
}
void FreezeGlobalTensors(ModuleOp module,
const GlobalTensorUsesMap& global_tensor_uses_map) {
SmallVector<GlobalTensorOp, 4> freezable_global_tensors;
for (auto& kv : global_tensor_uses_map) {
auto global_tensor = kv.first;
const auto& global_tensor_uses = kv.second;
if (IsFreezable(global_tensor, global_tensor_uses)) {
freezable_global_tensors.push_back(global_tensor);
}
}
// Remove `is_mutable` attribute from tf_saved_model.global_tensor
// and update func arguments to match.
//
// This amounts to changing the type of the argument to a tensor type, and
// replacing all the tf.ReadVariableOp's with the new tensor argument value.
OpBuilder builder(module.getBodyRegion());
for (const auto& kv : global_tensor_uses_map) {
auto global_tensor = kv.first;
const auto& global_tensor_uses = kv.second;
if (!IsFreezable(global_tensor, global_tensor_uses)) {
continue;
}
for (auto global_tensor_use : global_tensor_uses) {
auto func = global_tensor_use.func;
auto arg_index = global_tensor_use.arg_index;
Value arg = func.getArgument(arg_index);
for (Operation* user : llvm::make_early_inc_range(arg.getUsers())) {
RewriteReadOnlyVariableOpToTensorOp(user, arg);
user->erase();
}
Type new_type = global_tensor.value().Attribute::getType();
arg.setType(new_type);
auto old_ftype = func.getType();
auto input_types = old_ftype.getInputs().vec();
input_types[arg_index] = new_type;
func.setType(
builder.getFunctionType(input_types, old_ftype.getResults()));
}
global_tensor.removeAttr("is_mutable");
}
}
void EraseUnusedGlobalTensors(ModuleOp module,
const GlobalTensorUsesMap& global_tensor_uses) {
for (auto global_tensor :
llvm::make_early_inc_range(module.getOps<GlobalTensorOp>())) {
// If the tensor is exported, then it is used.
if (IsExported(global_tensor)) {
continue;
}
// If the tensor is bound to an argument, then it is used.
if (global_tensor_uses.find(global_tensor) != global_tensor_uses.end()) {
continue;
}
// Erase it.
global_tensor.erase();
}
}
void EraseUnusedBoundInputs(ModuleOp module) {
for (auto func : module.getOps<FuncOp>()) {
SmallVector<unsigned, 4> args_to_erase;
for (int i = 0, e = func.getNumArguments(); i < e; i++) {
if (func.getArgAttr(i, "tf_saved_model.bound_input") &&
func.getArgument(i).use_empty()) {
args_to_erase.push_back(i);
}
}
func.eraseArguments(args_to_erase);
}
}
void OptimizeGlobalTensorsPass::runOnModule() {
// This analysis could be much more elaborate, including tracking global
// tensors interprocedurally and uses in a wide variety of ops. But I don't
// know if we need that complexity.
auto module = getModule();
EraseUnusedBoundInputs(module);
// Figure out which func's use each tf_saved_model.global_tensor.
GlobalTensorUsesMap global_tensor_uses = CreateGlobalTensorUsesMap(module);
FreezeGlobalTensors(module, global_tensor_uses);
EraseUnusedGlobalTensors(module, global_tensor_uses);
}
} // namespace
// For "opt" to pick up this pass.
static PassRegistration<OptimizeGlobalTensorsPass> pass(
"tf-saved-model-optimize-global-tensors",
"Optimize tf_saved_model.global_tensor's.");
std::unique_ptr<OpPassBase<ModuleOp>> CreateOptimizeGlobalTensorsPass() {
return std::make_unique<OptimizeGlobalTensorsPass>();
}
} // namespace tf_saved_model
} // namespace mlir
<commit_msg>Remove dead-code in saved model optimize global tensors pass<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This pass optimizes tf_saved_model.global_tensor ops.
#include <map>
#include <set>
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "mlir/IR/Builders.h" // TF:llvm-project
#include "mlir/IR/Module.h" // TF:llvm-project
#include "mlir/Pass/Pass.h" // TF:llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.h"
namespace mlir {
namespace tf_saved_model {
namespace {
struct OptimizeGlobalTensorsPass
: public ModulePass<OptimizeGlobalTensorsPass> {
void runOnModule() override;
};
// A global tensor is bound to arguments of multiple funcs.
// This struct tracks which funcs (and which argument to that func) the global
// tensor is bound to.
struct GlobalTensorUse {
mutable FuncOp func;
size_t arg_index;
};
using GlobalTensorUsesMap =
std::map<GlobalTensorOp, std::vector<GlobalTensorUse>>;
// TODO(silvasean): Are there other read-only variable ops?
// It would be nice if we eventually had an interface that we could use
// to determine if an op is read-only and how to rewrite it.
// For now, IsReadOnlyVariableOp and RewriteReadOnlyVariableOpToTensorOp need to
// be keep in sync.
bool IsReadOnlyVariableOp(Operation* op) { return isa<TF::ReadVariableOp>(op); }
void RewriteReadOnlyVariableOpToTensorOp(Operation* op, Value tensor_value) {
auto read_variable = cast<TF::ReadVariableOp>(op);
read_variable.value().replaceAllUsesWith(tensor_value);
}
bool IsFreezable(GlobalTensorOp global_tensor,
ArrayRef<GlobalTensorUse> global_tensor_uses) {
// If this tensor is already immutable, don't freeze it.
if (!global_tensor.is_mutable()) {
return false;
}
// Can't freeze if exported.
if (IsExported(global_tensor)) {
return false;
}
// Can't freeze if it is used by anything that we aren't sure is read-only.
// Right now, this uses a very simple algorithm that only checks the top-level
// func for tf.ReadVariableOp. If the resource is passed into other functions
// or control flow, we fail to prove it is freezable even though we could.
for (auto& global_tensor_use : global_tensor_uses) {
auto arg = global_tensor_use.func.getArgument(global_tensor_use.arg_index);
for (auto user : arg.getUsers()) {
if (!IsReadOnlyVariableOp(user)) {
return false;
}
}
}
return true;
}
static GlobalTensorUsesMap CreateGlobalTensorUsesMap(ModuleOp module) {
GlobalTensorUsesMap global_tensor_uses;
SymbolTable symbol_table(module);
for (auto func : module.getOps<FuncOp>()) {
for (size_t i = 0, e = func.getNumArguments(); i < e; i++) {
auto sym =
func.getArgAttrOfType<SymbolRefAttr>(i, "tf_saved_model.bound_input");
if (!sym) {
continue;
}
auto global_tensor = symbol_table.lookup<GlobalTensorOp>(
sym.cast<FlatSymbolRefAttr>().getValue());
global_tensor_uses[global_tensor].push_back({func, i});
}
}
return global_tensor_uses;
}
void FreezeGlobalTensors(ModuleOp module,
const GlobalTensorUsesMap& global_tensor_uses_map) {
// Remove `is_mutable` attribute from tf_saved_model.global_tensor
// and update func arguments to match.
//
// This amounts to changing the type of the argument to a tensor type, and
// replacing all the tf.ReadVariableOp's with the new tensor argument value.
OpBuilder builder(module.getBodyRegion());
for (const auto& kv : global_tensor_uses_map) {
auto global_tensor = kv.first;
const auto& global_tensor_uses = kv.second;
if (!IsFreezable(global_tensor, global_tensor_uses)) {
continue;
}
for (auto global_tensor_use : global_tensor_uses) {
auto func = global_tensor_use.func;
auto arg_index = global_tensor_use.arg_index;
Value arg = func.getArgument(arg_index);
for (Operation* user : llvm::make_early_inc_range(arg.getUsers())) {
RewriteReadOnlyVariableOpToTensorOp(user, arg);
user->erase();
}
Type new_type = global_tensor.value().Attribute::getType();
arg.setType(new_type);
auto old_ftype = func.getType();
auto input_types = old_ftype.getInputs().vec();
input_types[arg_index] = new_type;
func.setType(
builder.getFunctionType(input_types, old_ftype.getResults()));
}
global_tensor.removeAttr("is_mutable");
}
}
void EraseUnusedGlobalTensors(ModuleOp module,
const GlobalTensorUsesMap& global_tensor_uses) {
for (auto global_tensor :
llvm::make_early_inc_range(module.getOps<GlobalTensorOp>())) {
// If the tensor is exported, then it is used.
if (IsExported(global_tensor)) {
continue;
}
// If the tensor is bound to an argument, then it is used.
if (global_tensor_uses.find(global_tensor) != global_tensor_uses.end()) {
continue;
}
// Erase it.
global_tensor.erase();
}
}
void EraseUnusedBoundInputs(ModuleOp module) {
for (auto func : module.getOps<FuncOp>()) {
SmallVector<unsigned, 4> args_to_erase;
for (int i = 0, e = func.getNumArguments(); i < e; i++) {
if (func.getArgAttr(i, "tf_saved_model.bound_input") &&
func.getArgument(i).use_empty()) {
args_to_erase.push_back(i);
}
}
func.eraseArguments(args_to_erase);
}
}
void OptimizeGlobalTensorsPass::runOnModule() {
// This analysis could be much more elaborate, including tracking global
// tensors interprocedurally and uses in a wide variety of ops. But I don't
// know if we need that complexity.
auto module = getModule();
EraseUnusedBoundInputs(module);
// Figure out which func's use each tf_saved_model.global_tensor.
GlobalTensorUsesMap global_tensor_uses = CreateGlobalTensorUsesMap(module);
FreezeGlobalTensors(module, global_tensor_uses);
EraseUnusedGlobalTensors(module, global_tensor_uses);
}
} // namespace
// For "opt" to pick up this pass.
static PassRegistration<OptimizeGlobalTensorsPass> pass(
"tf-saved-model-optimize-global-tensors",
"Optimize tf_saved_model.global_tensor's.");
std::unique_ptr<OpPassBase<ModuleOp>> CreateOptimizeGlobalTensorsPass() {
return std::make_unique<OptimizeGlobalTensorsPass>();
}
} // namespace tf_saved_model
} // namespace mlir
<|endoftext|>
|
<commit_before>#include <string>
#include <utility>
#include <QMessageBox>
#include <QInputDialog>
#include "chatwidget.hpp"
#include "caf/all.hpp"
#include "caf/detail/scope_guard.hpp"
using namespace std;
using namespace caf;
ChatWidget::ChatWidget(QWidget* parent, Qt::WindowFlags f)
: super(parent, f), m_input(nullptr), m_output(nullptr) {
set_message_handler ([=](local_actor* self) -> message_handler {
return {
on(atom("join"), arg_match) >> [=](const group& what) {
if (m_chatroom) {
self->send(m_chatroom, m_name + " has left the chatroom");
self->leave(m_chatroom);
}
self->join(what);
print(("*** joined " + to_string(what)).c_str());
m_chatroom = what;
self->send(what, m_name + " has entered the chatroom");
},
on(atom("setName"), arg_match) >> [=](string& name) {
self->send(m_chatroom, m_name + " is now known as " + name);
m_name = std::move(name);
print("*** changed name to "
+ QString::fromUtf8(m_name.c_str()));
},
on(atom("quit")) >> [=] {
close(); // close widget
},
[=](const string& txt) {
// don't print own messages
if (self != self->current_sender()) {
print(QString::fromUtf8(txt.c_str()));
}
},
[=](const group_down_msg& gdm) {
print("*** chatroom offline: "
+ QString::fromUtf8(to_string(gdm.source).c_str()));
}
};
});
}
void ChatWidget::sendChatMessage() {
auto cleanup = detail::make_scope_guard([=] {
input()->setText(QString());
});
QString line = input()->text();
if (line.startsWith('/')) {
vector<string> words;
split(words, line.midRef(1).toUtf8().constData(), is_any_of(" "));
message_builder(words.begin(), words.end()).apply({
on("join", arg_match) >> [=](const string& mod, const string& g) {
group gptr;
try { gptr = group::get(mod, g); }
catch (exception& e) {
print("*** exception: " + QString::fromUtf8((e.what())));
}
if (gptr) {
send_as(as_actor(), as_actor(), atom("join"), gptr);
}
},
on("setName", arg_match) >> [=](const string& str) {
send_as(as_actor(), as_actor(), atom("setName"), str);
},
others() >> [=] {
print("*** list of commands:\n"
"/join <module> <group id>\n"
"/setName <new name>\n");
}
});
return;
}
if (m_name.empty()) {
print("*** please set a name before sending messages");
return;
}
if (!m_chatroom) {
print("*** no one is listening... please join a group");
return;
}
string msg = m_name;
msg += ": ";
msg += line.toUtf8().constData();
print("<you>: " + input()->text());
// NOTE: we have to use send_as(as_actor(), ...) outside of our
// message handler, because `self` is *not* set properly
// in this context
send_as(as_actor(), m_chatroom, std::move(msg));
}
void ChatWidget::joinGroup() {
if (m_name.empty()) {
QMessageBox::information(this,
"No Name, No Chat",
"Please set a name first.");
return;
}
auto gname = QInputDialog::getText(this,
"Join Group",
"Please enter a group as <module>:<id>",
QLineEdit::Normal,
"remote:chatroom@localhost:4242");
int pos = gname.indexOf(':');
if (pos < 0) {
QMessageBox::warning(this, "Not a Group", "Invalid format");
return;
}
string mod = gname.left(pos).toUtf8().constData();
string gid = gname.midRef(pos+1).toUtf8().constData();
try {
auto gptr = group::get(mod, gid);
send_as(as_actor(), as_actor(), atom("join"), gptr);
}
catch (exception& e) {
QMessageBox::critical(this, "Exception", e.what());
}
}
void ChatWidget::changeName() {
auto name = QInputDialog::getText(this, "Change Name", "Please enter a new name");
if (!name.isEmpty()) {
send_as(as_actor(), as_actor(), atom("setName"), name.toUtf8().constData());
}
}
<commit_msg>Remove outdated comment<commit_after>#include <string>
#include <utility>
#include <QMessageBox>
#include <QInputDialog>
#include "chatwidget.hpp"
#include "caf/all.hpp"
#include "caf/detail/scope_guard.hpp"
using namespace std;
using namespace caf;
ChatWidget::ChatWidget(QWidget* parent, Qt::WindowFlags f)
: super(parent, f), m_input(nullptr), m_output(nullptr) {
set_message_handler ([=](local_actor* self) -> message_handler {
return {
on(atom("join"), arg_match) >> [=](const group& what) {
if (m_chatroom) {
self->send(m_chatroom, m_name + " has left the chatroom");
self->leave(m_chatroom);
}
self->join(what);
print(("*** joined " + to_string(what)).c_str());
m_chatroom = what;
self->send(what, m_name + " has entered the chatroom");
},
on(atom("setName"), arg_match) >> [=](string& name) {
self->send(m_chatroom, m_name + " is now known as " + name);
m_name = std::move(name);
print("*** changed name to "
+ QString::fromUtf8(m_name.c_str()));
},
on(atom("quit")) >> [=] {
close(); // close widget
},
[=](const string& txt) {
// don't print own messages
if (self != self->current_sender()) {
print(QString::fromUtf8(txt.c_str()));
}
},
[=](const group_down_msg& gdm) {
print("*** chatroom offline: "
+ QString::fromUtf8(to_string(gdm.source).c_str()));
}
};
});
}
void ChatWidget::sendChatMessage() {
auto cleanup = detail::make_scope_guard([=] {
input()->setText(QString());
});
QString line = input()->text();
if (line.startsWith('/')) {
vector<string> words;
split(words, line.midRef(1).toUtf8().constData(), is_any_of(" "));
message_builder(words.begin(), words.end()).apply({
on("join", arg_match) >> [=](const string& mod, const string& g) {
group gptr;
try { gptr = group::get(mod, g); }
catch (exception& e) {
print("*** exception: " + QString::fromUtf8((e.what())));
}
if (gptr) {
send_as(as_actor(), as_actor(), atom("join"), gptr);
}
},
on("setName", arg_match) >> [=](const string& str) {
send_as(as_actor(), as_actor(), atom("setName"), str);
},
others() >> [=] {
print("*** list of commands:\n"
"/join <module> <group id>\n"
"/setName <new name>\n");
}
});
return;
}
if (m_name.empty()) {
print("*** please set a name before sending messages");
return;
}
if (!m_chatroom) {
print("*** no one is listening... please join a group");
return;
}
string msg = m_name;
msg += ": ";
msg += line.toUtf8().constData();
print("<you>: " + input()->text());
send_as(as_actor(), m_chatroom, std::move(msg));
}
void ChatWidget::joinGroup() {
if (m_name.empty()) {
QMessageBox::information(this,
"No Name, No Chat",
"Please set a name first.");
return;
}
auto gname = QInputDialog::getText(this,
"Join Group",
"Please enter a group as <module>:<id>",
QLineEdit::Normal,
"remote:chatroom@localhost:4242");
int pos = gname.indexOf(':');
if (pos < 0) {
QMessageBox::warning(this, "Not a Group", "Invalid format");
return;
}
string mod = gname.left(pos).toUtf8().constData();
string gid = gname.midRef(pos+1).toUtf8().constData();
try {
auto gptr = group::get(mod, gid);
send_as(as_actor(), as_actor(), atom("join"), gptr);
}
catch (exception& e) {
QMessageBox::critical(this, "Exception", e.what());
}
}
void ChatWidget::changeName() {
auto name = QInputDialog::getText(this, "Change Name", "Please enter a new name");
if (!name.isEmpty()) {
send_as(as_actor(), as_actor(), atom("setName"), name.toUtf8().constData());
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/instants_table.h"
#include "src/trace_processor/counters_table.h"
namespace perfetto {
namespace trace_processor {
InstantsTable::InstantsTable(sqlite3*, const TraceStorage* storage)
: storage_(storage) {
ref_types_.resize(RefType::kRefMax);
ref_types_[RefType::kRefNoRef] = "";
ref_types_[RefType::kRefUtid] = "utid";
ref_types_[RefType::kRefCpuId] = "cpu";
ref_types_[RefType::kRefIrq] = "irq";
ref_types_[RefType::kRefSoftIrq] = "softirq";
ref_types_[RefType::kRefUpid] = "upid";
};
void InstantsTable::RegisterTable(sqlite3* db, const TraceStorage* storage) {
Table::Register<InstantsTable>(db, storage, "instants");
}
StorageSchema InstantsTable::CreateStorageSchema() {
const auto& instants = storage_->instants();
return StorageSchema::Builder()
.AddColumn<IdColumn>("id", TableId::kInstants)
.AddOrderedNumericColumn("ts", &instants.timestamps())
.AddStringColumn("name", &instants.name_ids(), &storage_->string_pool())
.AddNumericColumn("value", &instants.values())
.AddColumn<CountersTable::RefColumn>("ref", &instants.refs(),
&instants.types(), storage_)
.AddStringColumn("ref_type", &instants.types(), &ref_types_)
.AddNumericColumn("arg_set_id", &instants.arg_set_ids())
.Build({"name", "ts", "ref"});
}
uint32_t InstantsTable::RowCount() {
return static_cast<uint32_t>(storage_->instants().instant_count());
}
int InstantsTable::BestIndex(const QueryConstraints& qc, BestIndexInfo* info) {
info->estimated_cost =
static_cast<uint32_t>(storage_->instants().instant_count());
// Only the string columns are handled by SQLite
info->order_by_consumed = true;
size_t name_index = schema().ColumnIndexFromName("name");
size_t ref_type_index = schema().ColumnIndexFromName("ref_type");
for (size_t i = 0; i < qc.constraints().size(); i++) {
info->omit[i] =
qc.constraints()[i].iColumn != static_cast<int>(name_index) &&
qc.constraints()[i].iColumn != static_cast<int>(ref_type_index);
}
return SQLITE_OK;
}
} // namespace trace_processor
} // namespace perfetto
<commit_msg>trace_processor: add missing ref type on instants table am: 116dd318a6 am: 3e455e726e<commit_after>/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/instants_table.h"
#include "src/trace_processor/counters_table.h"
namespace perfetto {
namespace trace_processor {
InstantsTable::InstantsTable(sqlite3*, const TraceStorage* storage)
: storage_(storage) {
ref_types_.resize(RefType::kRefMax);
ref_types_[RefType::kRefNoRef] = "";
ref_types_[RefType::kRefUtid] = "utid";
ref_types_[RefType::kRefUpid] = "upid";
ref_types_[RefType::kRefCpuId] = "cpu";
ref_types_[RefType::kRefIrq] = "irq";
ref_types_[RefType::kRefSoftIrq] = "softirq";
ref_types_[RefType::kRefUtidLookupUpid] = "upid";
};
void InstantsTable::RegisterTable(sqlite3* db, const TraceStorage* storage) {
Table::Register<InstantsTable>(db, storage, "instants");
}
StorageSchema InstantsTable::CreateStorageSchema() {
const auto& instants = storage_->instants();
return StorageSchema::Builder()
.AddColumn<IdColumn>("id", TableId::kInstants)
.AddOrderedNumericColumn("ts", &instants.timestamps())
.AddStringColumn("name", &instants.name_ids(), &storage_->string_pool())
.AddNumericColumn("value", &instants.values())
.AddColumn<CountersTable::RefColumn>("ref", &instants.refs(),
&instants.types(), storage_)
.AddStringColumn("ref_type", &instants.types(), &ref_types_)
.AddNumericColumn("arg_set_id", &instants.arg_set_ids())
.Build({"name", "ts", "ref"});
}
uint32_t InstantsTable::RowCount() {
return static_cast<uint32_t>(storage_->instants().instant_count());
}
int InstantsTable::BestIndex(const QueryConstraints& qc, BestIndexInfo* info) {
info->estimated_cost =
static_cast<uint32_t>(storage_->instants().instant_count());
// Only the string columns are handled by SQLite
info->order_by_consumed = true;
size_t name_index = schema().ColumnIndexFromName("name");
size_t ref_type_index = schema().ColumnIndexFromName("ref_type");
for (size_t i = 0; i < qc.constraints().size(); i++) {
info->omit[i] =
qc.constraints()[i].iColumn != static_cast<int>(name_index) &&
qc.constraints()[i].iColumn != static_cast<int>(ref_type_index);
}
return SQLITE_OK;
}
} // namespace trace_processor
} // namespace perfetto
<|endoftext|>
|
<commit_before>// -*- mode: c++; coding: utf-8 -*-
/*! @file simulation.cpp
@brief Inplementation of Simulation class
*/
#include "simulation.h"
#include "cxxwtils/iostr.hpp"
#include "cxxwtils/getopt.hpp"
#include "cxxwtils/prandom.hpp"
#include "cxxwtils/os.hpp"
#include "cxxwtils/gz.hpp"
#include "cxxwtils/multiprocessing.hpp"
#include "individual.h"
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// functions
//! Symbols for the program options can be different from those in equations
/*! @ingroup biol_param
@return Program options description
Command line option | Symbol | Variable
------------------- | -------- | ------------------------------------------
`--row,--col` | - | Simulation::NUM_COLS, Simulation::NUM_ROWS
`-T,--time` | - | Simulation::ENTIRE_PERIOD
`-I,--interval` | - | Simulation::OBSERVATION_CYCLE
*/
boost::program_options::options_description& Simulation::opt_description() {HERE;
namespace po = boost::program_options;
static po::options_description description("Simulation");
description.add_options()
("help,h", po::value<bool>()->default_value(false)->implicit_value(true), "produce help")
("verbose,v", po::value<bool>(&VERBOSE)
->default_value(VERBOSE)->implicit_value(true), "verbose output")
("test", po::value<int>()->default_value(0)->implicit_value(1))
("mode", po::value<int>(&MODE)->default_value(MODE))
("ppn", po::value<size_t>(&PPN)->default_value(wtl::num_threads()))
("label", po::value<std::string>(&LABEL)->default_value("default"))
("top_dir", po::value<std::string>()->default_value(OUT_DIR.string()))
("row", po::value<size_t>(&NUM_ROWS)->default_value(NUM_ROWS))
("col", po::value<size_t>(&NUM_COLS)->default_value(NUM_COLS))
("dimensions,D", po::value<size_t>(&DIMENSIONS)->default_value(DIMENSIONS))
("time,T", po::value<size_t>(&ENTIRE_PERIOD)->default_value(ENTIRE_PERIOD))
("interval,I", po::value<size_t>(&OBSERVATION_CYCLE)->default_value(OBSERVATION_CYCLE))
("seed", po::value<unsigned int>(&SEED)->default_value(SEED))
;
return description;
}
//! Unit test for each class
inline void test() {HERE;
Individual::unit_test();
Patch::unit_test();
}
Simulation::Simulation(int argc, char* argv[]) {HERE;
std::vector<std::string> arguments(argv, argv + argc);
std::cout << wtl::str_join(arguments, " ") << std::endl;
std::cout << wtl::iso8601datetime() << std::endl;
namespace po = boost::program_options;
po::options_description description;
description.add(opt_description());
description.add(Individual::opt_description());
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, description), vm);
po::notify(vm);
if (vm["help"].as<bool>()) {
description.print(std::cout);
exit(0);
}
OUT_DIR = fs::path(vm["top_dir"].as<std::string>());
const std::string CONFIG_STRING = wtl::flags_into_string(description, vm);
prandom().seed(SEED); // TODO: want to read seed?
if (VERBOSE) {
std::cout << CONFIG_STRING << std::endl;
}
if (ENTIRE_PERIOD % OBSERVATION_CYCLE > 0) {
std::cerr << wtl::strprintf(
"T=%d is not a multiple of I=%d",
ENTIRE_PERIOD, OBSERVATION_CYCLE) << std::endl;
exit(1);
}
if (DIMENSIONS == 1) {
std::ostringstream ost;
ost << "diameter_pref = 0\n"
<< "limb_select = 0\n"
<< "diameter_compe = 0\n"
<< "limb_compe = 0\n"
<< "mutation_mask = 10\n";
std::istringstream ist(ost.str());
po::store(po::parse_config_file(ist, description, false), vm);
}
switch (vm["test"].as<int>()) {
case 0:
break;
case 1:
test();
exit(0);
default:
exit(1);
}
const std::string now(wtl::strftime("%Y%m%d_%H%M%S"));
std::ostringstream pid_at_host;
pid_at_host << ::getpid() << "@" << wtl::gethostname();
WORK_DIR = TMP_DIR / (now + "_" + LABEL + "_" + pid_at_host.str());
derr("mkdir && cd to " << WORK_DIR << std::endl);
fs::create_directory(WORK_DIR);
wtl::cd(WORK_DIR.string());
fs::create_directory(OUT_DIR);
OUT_DIR /= (LABEL + "_" + now + "_" + pid_at_host.str());
wtl::Fout{"program_options.conf"} << CONFIG_STRING;
}
void Simulation::run() {HERE;
switch (MODE) {
case 0:
evolve();
break;
case 1:
Individual::write_resource_abundance();
break;
case 2:
wtl::gzip{wtl::Fout{"possible_geographic.csv.gz"}} << Individual::possible_geographic();
wtl::gzip{wtl::Fout{"possible_phenotypes.csv.gz"}} << Individual::possible_phenotypes();
break;
default:
exit(1);
}
derr("mv results to " << OUT_DIR << std::endl);
fs::rename(WORK_DIR, OUT_DIR);
std::cout << wtl::iso8601datetime() << std::endl;
}
void Simulation::evolve() {HERE;
assert(ENTIRE_PERIOD % OBSERVATION_CYCLE == 0);
population.assign(NUM_ROWS, std::vector<Patch>(NUM_COLS));
if (DIMENSIONS == 1) {
population[0][0] = Patch(INITIAL_PATCH_SIZE, Individual{{15, 0, 15, 0}});
} else {
population[0][0] = Patch(INITIAL_PATCH_SIZE);
}
std::ostringstream ost;
for (size_t t=0; t<=ENTIRE_PERIOD; ++t) {
if (VERBOSE) {
std::cout << "\nT = " << t << "\n"
<< str_population([](const Patch& p) {return p.size();});
}
if (t % OBSERVATION_CYCLE == 0) {
write_snapshot(t, ost);
}
if (t < ENTIRE_PERIOD) {
life_cycle();
}
}
wtl::gzip{wtl::Fout{"evolution.csv.gz"}} << ost.str();
}
void Simulation::life_cycle() {
std::vector<std::vector<Patch> > parents(population);
wtl::Semaphore sem(PPN);
std::mutex mtx;
auto patch_task = [&](const size_t row, const size_t col) {
auto offsprings = parents[row][col].mate_and_reproduce();
std::lock_guard<std::mutex> lck(mtx);
for (auto& child: offsprings) {
size_t dest_row = row;
size_t dest_col = col;
choose_patch(&dest_row, &dest_col);
population[dest_row][dest_col].append(std::move(child));
}
sem.unlock();
};
std::vector<std::thread> threads;
for (size_t row=0; row<NUM_ROWS; ++row) {
for (size_t col=0; col<NUM_COLS; ++col) {
sem.lock();
threads.emplace_back(patch_task, row, col);
}
}
for (auto& th: threads) {th.join();}
threads.clear();
for (size_t row=0; row<NUM_ROWS; ++row) {
for (size_t col=0; col<NUM_COLS; ++col) {
sem.lock();
threads.emplace_back([row, col, &sem, this] {
population[row][col].viability_selection();
sem.unlock();
});
}
}
for (auto& th: threads) {th.join();}
}
void Simulation::choose_patch(size_t* row, size_t* col) const {
if (!prandom().bernoulli(Individual::MIGRATION_RATE())) {return;}
size_t r = *row;
size_t c = *col;
switch (prandom().randrange(8)) {
case 0: ++c; break;
case 1: ++r; ++c; break;
case 2: ++r; break;
case 3: ++r; --c; break;
case 4: --c; break;
case 5: --r; --c; break;
case 6: --r; break;
case 7: --r; ++c; break;
}
// size_t(-1) also makes true
if ((r >= NUM_ROWS) | (c >= NUM_COLS)) {return;}
*row = r; *col = c;
}
void Simulation::write_snapshot(const size_t time, std::ostream& ost) const {
const std::string sep{","};
if (time == 0) {
ost << "time" << sep << "row" << sep << "col" << sep
<< "n" << sep << Individual::header() << "\n";
}
std::size_t popsize = 0;
for (size_t row=0; row<population.size(); ++row) {
for (size_t col=0; col<population[row].size(); ++col) {
for (const auto& item: population[row][col].summarize()) {
ost << time << sep << row << sep << col << sep
<< item.second << sep << item.first << "\n";
popsize += item.second;
}
}
}
derr("N = " << popsize << std::endl);
}
<commit_msg>Add vm.notify() to let -D1 be effective. #1<commit_after>// -*- mode: c++; coding: utf-8 -*-
/*! @file simulation.cpp
@brief Inplementation of Simulation class
*/
#include "simulation.h"
#include "cxxwtils/iostr.hpp"
#include "cxxwtils/getopt.hpp"
#include "cxxwtils/prandom.hpp"
#include "cxxwtils/os.hpp"
#include "cxxwtils/gz.hpp"
#include "cxxwtils/multiprocessing.hpp"
#include "individual.h"
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// functions
//! Symbols for the program options can be different from those in equations
/*! @ingroup biol_param
@return Program options description
Command line option | Symbol | Variable
------------------- | -------- | ------------------------------------------
`--row,--col` | - | Simulation::NUM_COLS, Simulation::NUM_ROWS
`-T,--time` | - | Simulation::ENTIRE_PERIOD
`-I,--interval` | - | Simulation::OBSERVATION_CYCLE
*/
boost::program_options::options_description& Simulation::opt_description() {HERE;
namespace po = boost::program_options;
static po::options_description description("Simulation");
description.add_options()
("help,h", po::value<bool>()->default_value(false)->implicit_value(true), "produce help")
("verbose,v", po::value<bool>(&VERBOSE)
->default_value(VERBOSE)->implicit_value(true), "verbose output")
("test", po::value<int>()->default_value(0)->implicit_value(1))
("mode", po::value<int>(&MODE)->default_value(MODE))
("ppn", po::value<size_t>(&PPN)->default_value(wtl::num_threads()))
("label", po::value<std::string>(&LABEL)->default_value("default"))
("top_dir", po::value<std::string>()->default_value(OUT_DIR.string()))
("row", po::value<size_t>(&NUM_ROWS)->default_value(NUM_ROWS))
("col", po::value<size_t>(&NUM_COLS)->default_value(NUM_COLS))
("dimensions,D", po::value<size_t>(&DIMENSIONS)->default_value(DIMENSIONS))
("time,T", po::value<size_t>(&ENTIRE_PERIOD)->default_value(ENTIRE_PERIOD))
("interval,I", po::value<size_t>(&OBSERVATION_CYCLE)->default_value(OBSERVATION_CYCLE))
("seed", po::value<unsigned int>(&SEED)->default_value(SEED))
;
return description;
}
//! Unit test for each class
inline void test() {HERE;
Individual::unit_test();
Patch::unit_test();
}
Simulation::Simulation(int argc, char* argv[]) {HERE;
std::vector<std::string> arguments(argv, argv + argc);
std::cout << wtl::str_join(arguments, " ") << std::endl;
std::cout << wtl::iso8601datetime() << std::endl;
namespace po = boost::program_options;
po::options_description description;
description.add(opt_description());
description.add(Individual::opt_description());
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, description), vm);
po::notify(vm);
if (vm["help"].as<bool>()) {
description.print(std::cout);
exit(0);
}
OUT_DIR = fs::path(vm["top_dir"].as<std::string>());
const std::string CONFIG_STRING = wtl::flags_into_string(description, vm);
prandom().seed(SEED); // TODO: want to read seed?
if (VERBOSE) {
std::cout << CONFIG_STRING << std::endl;
}
if (ENTIRE_PERIOD % OBSERVATION_CYCLE > 0) {
std::cerr << wtl::strprintf(
"T=%d is not a multiple of I=%d",
ENTIRE_PERIOD, OBSERVATION_CYCLE) << std::endl;
exit(1);
}
if (DIMENSIONS == 1) {
std::ostringstream ost;
ost << "diameter_pref = 0\n"
<< "limb_select = 0\n"
<< "diameter_compe = 0\n"
<< "limb_compe = 0\n"
<< "mutation_mask = 10\n";
std::istringstream ist(ost.str());
po::store(po::parse_config_file(ist, description, false), vm);
vm.notify();
}
switch (vm["test"].as<int>()) {
case 0:
break;
case 1:
test();
exit(0);
default:
exit(1);
}
const std::string now(wtl::strftime("%Y%m%d_%H%M%S"));
std::ostringstream pid_at_host;
pid_at_host << ::getpid() << "@" << wtl::gethostname();
WORK_DIR = TMP_DIR / (now + "_" + LABEL + "_" + pid_at_host.str());
derr("mkdir && cd to " << WORK_DIR << std::endl);
fs::create_directory(WORK_DIR);
wtl::cd(WORK_DIR.string());
fs::create_directory(OUT_DIR);
OUT_DIR /= (LABEL + "_" + now + "_" + pid_at_host.str());
wtl::Fout{"program_options.conf"} << CONFIG_STRING;
}
void Simulation::run() {HERE;
switch (MODE) {
case 0:
evolve();
break;
case 1:
Individual::write_resource_abundance();
break;
case 2:
wtl::gzip{wtl::Fout{"possible_geographic.csv.gz"}} << Individual::possible_geographic();
wtl::gzip{wtl::Fout{"possible_phenotypes.csv.gz"}} << Individual::possible_phenotypes();
break;
default:
exit(1);
}
derr("mv results to " << OUT_DIR << std::endl);
fs::rename(WORK_DIR, OUT_DIR);
std::cout << wtl::iso8601datetime() << std::endl;
}
void Simulation::evolve() {HERE;
assert(ENTIRE_PERIOD % OBSERVATION_CYCLE == 0);
population.assign(NUM_ROWS, std::vector<Patch>(NUM_COLS));
if (DIMENSIONS == 1) {
population[0][0] = Patch(INITIAL_PATCH_SIZE, Individual{{15, 0, 15, 0}});
} else {
population[0][0] = Patch(INITIAL_PATCH_SIZE);
}
std::ostringstream ost;
for (size_t t=0; t<=ENTIRE_PERIOD; ++t) {
if (VERBOSE) {
std::cout << "\nT = " << t << "\n"
<< str_population([](const Patch& p) {return p.size();});
}
if (t % OBSERVATION_CYCLE == 0) {
write_snapshot(t, ost);
}
if (t < ENTIRE_PERIOD) {
life_cycle();
}
}
wtl::gzip{wtl::Fout{"evolution.csv.gz"}} << ost.str();
}
void Simulation::life_cycle() {
std::vector<std::vector<Patch> > parents(population);
wtl::Semaphore sem(PPN);
std::mutex mtx;
auto patch_task = [&](const size_t row, const size_t col) {
auto offsprings = parents[row][col].mate_and_reproduce();
std::lock_guard<std::mutex> lck(mtx);
for (auto& child: offsprings) {
size_t dest_row = row;
size_t dest_col = col;
choose_patch(&dest_row, &dest_col);
population[dest_row][dest_col].append(std::move(child));
}
sem.unlock();
};
std::vector<std::thread> threads;
for (size_t row=0; row<NUM_ROWS; ++row) {
for (size_t col=0; col<NUM_COLS; ++col) {
sem.lock();
threads.emplace_back(patch_task, row, col);
}
}
for (auto& th: threads) {th.join();}
threads.clear();
for (size_t row=0; row<NUM_ROWS; ++row) {
for (size_t col=0; col<NUM_COLS; ++col) {
sem.lock();
threads.emplace_back([row, col, &sem, this] {
population[row][col].viability_selection();
sem.unlock();
});
}
}
for (auto& th: threads) {th.join();}
}
void Simulation::choose_patch(size_t* row, size_t* col) const {
if (!prandom().bernoulli(Individual::MIGRATION_RATE())) {return;}
size_t r = *row;
size_t c = *col;
switch (prandom().randrange(8)) {
case 0: ++c; break;
case 1: ++r; ++c; break;
case 2: ++r; break;
case 3: ++r; --c; break;
case 4: --c; break;
case 5: --r; --c; break;
case 6: --r; break;
case 7: --r; ++c; break;
}
// size_t(-1) also makes true
if ((r >= NUM_ROWS) | (c >= NUM_COLS)) {return;}
*row = r; *col = c;
}
void Simulation::write_snapshot(const size_t time, std::ostream& ost) const {
const std::string sep{","};
if (time == 0) {
ost << "time" << sep << "row" << sep << "col" << sep
<< "n" << sep << Individual::header() << "\n";
}
std::size_t popsize = 0;
for (size_t row=0; row<population.size(); ++row) {
for (size_t col=0; col<population[row].size(); ++col) {
for (const auto& item: population[row][col].summarize()) {
ost << time << sep << row << sep << col << sep
<< item.second << sep << item.first << "\n";
popsize += item.second;
}
}
}
derr("N = " << popsize << std::endl);
}
<|endoftext|>
|
<commit_before>#include "cuda.h"
#include <cstdio>
struct checkers_point{
int board[64];
int how_much_children;
checkers_point * children = NULL;
checkers_point * next = NULL;
checkers_point * prev = NULL;
checkers_point * parent = NULL;
bool min_max;
int alpha = -1000000000;
int beta = 1000000000;
int value;
int player;
};
#define default_n 8
#define EMPTY 0
#define WHITE 1
#define BLACK 2
#define queenW 11
#define queenB 22
int main(){
//przekazane powinny zostac: int siize, default_row_with_pawn, int * tab_with_board;
int siize = 8;
int * tab_with_board;
int default_row_with_pawn = 3;
tab_with_board = (int*) malloc(sizeof(int)*siize*siize);
for (int i = 0; i < siize*siize; i++)
tab_with_board[i] = EMPTY;
for (int i = 0; i < default_row_with_pawn; ++i){
for (int j = 0; j < siize/2; ++j){
tab_with_board[i*siize+2*j+(i%2)] = BLACK;
tab_with_board[(siize*siize-1)-(i*siize+2*j+(i%2))] = WHITE;
}
}
for (int i = 0; i < 64; i++)
printf("%d ", tab_with_board[i]);
//^ do usuniecia
cuInit(0);
CUdevice cuDevice;
CUresult res = cuDeviceGet(&cuDevice, 0);
if (res != CUDA_SUCCESS){
printf("cannot acquire device 0\n");
exit(1);
}
CUcontext cuContext;
res = cuCtxCreate(&cuContext, 0, cuDevice);
if (res != CUDA_SUCCESS){
printf("cannot create context\n");
exit(1);
}
CUmodule cuModule = (CUmodule)0;
res = cuModuleLoad(&cuModule, "checkers.ptx");
if (res != CUDA_SUCCESS) {
printf("cannot load module: %d\n", res);
exit(1);
}
CUfunction create_tree, delete_tree, print_tree, set_root, copy_best_result;
res = cuModuleGetFunction(&create_tree, cuModule, "create_tree");
if (res != CUDA_SUCCESS){
printf("cannot acquire kernel handle\n");
exit(1);
}
res = cuModuleGetFunction(&delete_tree, cuModule, "delete_tree");
if (res != CUDA_SUCCESS){
printf("cannot acquire kernel handle\n");
exit(1);
}
res = cuModuleGetFunction(&print_tree, cuModule, "print_tree");
if (res != CUDA_SUCCESS){
printf("cannot acquire kernel handle\n");
exit(1);
}
res = cuModuleGetFunction(&set_root, cuModule, "set_root");
if (res != CUDA_SUCCESS){
printf("cannot acquire kernel handle\n");
exit(1);
}
res = cuModuleGetFunction(©_best_result, cuModule, "copy_best_result");
if (res != CUDA_SUCCESS){
printf("cannot acquire kernel handle\n");
exit(1);
}
int how_deep = 6;
int max_children = 12 * 2;
int n = max_children;
for (int i = 0; i < 4; i++){
n *= max_children;
}
printf("N: %d\n", n);
size_t size = sizeof(checkers_point)*n;
size_t size_tab = sizeof(int)*siize*siize;
checkers_point * a = (checkers_point*) malloc(size);
res = cuMemHostRegister(a, size, 0);
if (res != CUDA_SUCCESS){
printf("cuMemHostRegister\n");
exit(1);
}
res = cuMemHostRegister(tab_with_board, size_tab, 0);
if (res != CUDA_SUCCESS){
printf("cuMemHostRegister\n");
exit(1);
}
int blocks_per_grid = (n+1023)/1024;
int threads_per_block = 1024;
int num_threads = threads_per_block * blocks_per_grid;
CUdeviceptr Adev, Atab, Vdev;
res = cuMemAlloc(&Adev, size);
if (res != CUDA_SUCCESS){
printf("cuMemAlloc\n");
exit(1);
}
res = cuMemAlloc(&Vdev, num_threads * sizeof(checkers_point*));
if (res != CUDA_SUCCESS){
printf("cuMemAlloc\n");
exit(1);
}
res = cuMemAlloc(&Atab, size_tab);
if (res != CUDA_SUCCESS){
printf("cuMemAlloc\n");
exit(1);
}
res = cuMemcpyHtoD(Atab, tab_with_board, size_tab);
if (res != CUDA_SUCCESS){
printf("cuMemcpy\n");
exit(1);
}
int i = 1;
void* args[] = {&n, &Adev, &i};
void* args2[] = {&Adev, &num_threads, &Vdev};
void* args_root[] = {&Adev, &Atab, &siize};
res = cuLaunchKernel(set_root, blocks_per_grid, 1, 1, threads_per_block, 1, 1, 0, 0, args_root, 0);
if (res != CUDA_SUCCESS){
printf("cannot run kernel\n");
exit(1);
}
for (i = 1; i < how_deep+1; i++){
res = cuLaunchKernel(create_tree, blocks_per_grid, 1, 1, threads_per_block, 1, 1, 0, 0, args, 0);
res = cuLaunchKernel(print_tree, blocks_per_grid, 1, 1, threads_per_block, 1, 1, 0, 0, args, 0);
}
if (res != CUDA_SUCCESS){
printf("cannot run kernel\n");
exit(1);
}
res = cuLaunchKernel(print_tree, blocks_per_grid, 1, 1, threads_per_block, 1, 1, 0, 0, args, 0);
if (res != CUDA_SUCCESS){
printf("cannot run kernel\n");
exit(1);
}
res = cuLaunchKernel(delete_tree, blocks_per_grid, 1, 1, threads_per_block, 1, 1, 0, 0, args2, 0);
if (res != CUDA_SUCCESS){
printf("cannot run kernel\n");
exit(1);
}
res = cuLaunchKernel(print_tree, blocks_per_grid, 1, 1, threads_per_block, 1, 1, 0, 0, args, 0);
if (res != CUDA_SUCCESS){
printf("cannot run kernel\n");
exit(1);
}
res = cuLaunchKernel(copy_best_result, blocks_per_grid, 1, 1, threads_per_block, 1, 1, 0, 0, args_root, 0);
if (res != CUDA_SUCCESS){
printf("cannot run kernel\n");
exit(1);
}
cuMemFree(Adev);
cuMemFree(Atab);
cuMemFree(Vdev);
cuCtxDestroy(cuContext);
// return tab_with_board;
return 0;
}
<commit_msg>Changing main<commit_after>#include "cuda.h"
#include <cstdio>
struct checkers_point{
int board[64];
int how_much_children;
checkers_point * children = NULL;
checkers_point * next = NULL;
checkers_point * prev = NULL;
checkers_point * parent = NULL;
bool min_max;
int alpha = -1000000000;
int beta = 1000000000;
int value;
int player;
};
#define default_n 8
#define EMPTY 0
#define WHITE 1
#define BLACK 2
#define queenW 11
#define queenB 22
int * computer_turn(int siize, int default_row_with_pawn, int * tab_with_board){
cuInit(0);
CUdevice cuDevice;
CUresult res = cuDeviceGet(&cuDevice, 0);
if (res != CUDA_SUCCESS){
printf("cannot acquire device 0\n");
exit(1);
}
CUcontext cuContext;
res = cuCtxCreate(&cuContext, 0, cuDevice);
if (res != CUDA_SUCCESS){
printf("cannot create context\n");
exit(1);
}
CUmodule cuModule = (CUmodule)0;
res = cuModuleLoad(&cuModule, "checkers.ptx");
if (res != CUDA_SUCCESS) {
printf("cannot load module: %d\n", res);
exit(1);
}
CUfunction alpha_beta, create_tree, delete_tree, print_tree, set_root, copy_best_result;
res = cuModuleGetFunction(&alpha_beta, cuModule, "alpha_beta");
if (res != CUDA_SUCCESS){
printf("cannot acquire kernel handle\n");
exit(1);
}
res = cuModuleGetFunction(&create_tree, cuModule, "create_tree");
if (res != CUDA_SUCCESS){
printf("cannot acquire kernel handle\n");
exit(1);
}
res = cuModuleGetFunction(&delete_tree, cuModule, "delete_tree");
if (res != CUDA_SUCCESS){
printf("cannot acquire kernel handle\n");
exit(1);
}
res = cuModuleGetFunction(&print_tree, cuModule, "print_tree");
if (res != CUDA_SUCCESS){
printf("cannot acquire kernel handle\n");
exit(1);
}
res = cuModuleGetFunction(&set_root, cuModule, "set_root");
if (res != CUDA_SUCCESS){
printf("cannot acquire kernel handle\n");
exit(1);
}
res = cuModuleGetFunction(©_best_result, cuModule, "copy_best_result");
if (res != CUDA_SUCCESS){
printf("cannot acquire kernel handle\n");
exit(1);
}
int how_deep = 6;
int max_children = 12 * 2;
int n = max_children;
for (int i = 0; i < 4; i++){
n *= max_children;
}
//printf("N: %d\n", n);
size_t size = sizeof(checkers_point)*n;
size_t size_tab = sizeof(int)*siize*siize;
checkers_point * a = (checkers_point*) malloc(size);
res = cuMemHostRegister(a, size, 0);
if (res != CUDA_SUCCESS){
printf("cuMemHostRegister\n");
exit(1);
}
res = cuMemHostRegister(tab_with_board, size_tab, 0);
if (res != CUDA_SUCCESS){
printf("cuMemHostRegister\n");
exit(1);
}
int blocks_per_grid = (n+1023)/1024;
int threads_per_block = 1024;
int blocks_per_grid2 = 100;
int threads_per_block2 = 100;
int num_threads = threads_per_block2 * blocks_per_grid2;
CUdeviceptr Adev, Atab, Vdev;
res = cuMemAlloc(&Adev, size);
if (res != CUDA_SUCCESS){
printf("cuMemAlloc\n");
exit(1);
}
res = cuMemAlloc(&Vdev, num_threads * sizeof(checkers_point*));
if (res != CUDA_SUCCESS){
printf("cuMemAlloc\n");
exit(1);
}
res = cuMemAlloc(&Atab, size_tab);
if (res != CUDA_SUCCESS){
printf("cuMemAlloc\n");
exit(1);
}
res = cuMemcpyHtoD(Atab, tab_with_board, size_tab);
if (res != CUDA_SUCCESS){
printf("cuMemcpy\n");
exit(1);
}
int i = 1;
void* args[] = {&n, &Adev, &i};
void* args2[] = {&Adev, &num_threads, &Vdev};
void* args3[] = {&Adev, &num_threads, &Vdev};
void* args_root[] = {&Adev, &Atab, &siize};
res = cuLaunchKernel(set_root, blocks_per_grid, 1, 1, threads_per_block, 1, 1, 0, 0, args_root, 0);
if (res != CUDA_SUCCESS){
printf("cannot run kernel\n");
exit(1);
}
for (i = 1; i < how_deep+1; i++){
res = cuLaunchKernel(create_tree, blocks_per_grid, 1, 1, threads_per_block, 1, 1, 0, 0, args, 0);
res = cuLaunchKernel(print_tree, blocks_per_grid, 1, 1, threads_per_block, 1, 1, 0, 0, args, 0);
}
if (res != CUDA_SUCCESS){
printf("cannot run kernel\n");
exit(1);
}
res = cuLaunchKernel(alpha_beta, blocks_per_grid2, 1, 1, threads_per_block2, 1, 1, 0, 0, args3, 0);
if (res != CUDA_SUCCESS){
printf("cannot run kernel\n");
exit(1);
}
res = cuLaunchKernel(delete_tree, blocks_per_grid2, 1, 1, threads_per_block2, 1, 1, 0, 0, args2, 0);
if (res != CUDA_SUCCESS){
printf("cannot run kernel\n");
exit(1);
}
res = cuLaunchKernel(copy_best_result, blocks_per_grid, 1, 1, threads_per_block, 1, 1, 0, 0, args_root, 0);
if (res != CUDA_SUCCESS){
printf("cannot run kernel\n");
exit(1);
}
res = cuMemcpyDtoH(tab_with_board, Atab, size_tab);
if (res != CUDA_SUCCESS){
printf("cuMemcpy\n");
exit(1);
}
cuMemFree(Adev);
cuMemFree(Atab);
cuMemFree(Vdev);
cuCtxDestroy(cuContext);
return tab_with_board;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/common_param_traits.h"
#include "chrome/common/chrome_constants.h"
#include "gfx/rect.h"
#include "googleurl/src/gurl.h"
#ifndef EXCLUDE_SKIA_DEPENDENCIES
#include "third_party/skia/include/core/SkBitmap.h"
#endif
#include "webkit/glue/dom_operations.h"
namespace IPC {
#ifndef EXCLUDE_SKIA_DEPENDENCIES
namespace {
struct SkBitmap_Data {
// The configuration for the bitmap (bits per pixel, etc).
SkBitmap::Config fConfig;
// The width of the bitmap in pixels.
uint32 fWidth;
// The height of the bitmap in pixels.
uint32 fHeight;
void InitSkBitmapDataForTransfer(const SkBitmap& bitmap) {
fConfig = bitmap.config();
fWidth = bitmap.width();
fHeight = bitmap.height();
}
// Returns whether |bitmap| successfully initialized.
bool InitSkBitmapFromData(SkBitmap* bitmap, const char* pixels,
size_t total_pixels) const {
if (total_pixels) {
bitmap->setConfig(fConfig, fWidth, fHeight, 0);
if (!bitmap->allocPixels())
return false;
if (total_pixels != bitmap->getSize())
return false;
memcpy(bitmap->getPixels(), pixels, total_pixels);
}
return true;
}
};
} // namespace
void ParamTraits<SkBitmap>::Write(Message* m, const SkBitmap& p) {
size_t fixed_size = sizeof(SkBitmap_Data);
SkBitmap_Data bmp_data;
bmp_data.InitSkBitmapDataForTransfer(p);
m->WriteData(reinterpret_cast<const char*>(&bmp_data),
static_cast<int>(fixed_size));
size_t pixel_size = p.getSize();
SkAutoLockPixels p_lock(p);
m->WriteData(reinterpret_cast<const char*>(p.getPixels()),
static_cast<int>(pixel_size));
}
bool ParamTraits<SkBitmap>::Read(const Message* m, void** iter, SkBitmap* r) {
const char* fixed_data;
int fixed_data_size = 0;
if (!m->ReadData(iter, &fixed_data, &fixed_data_size) ||
(fixed_data_size <= 0)) {
NOTREACHED();
return false;
}
if (fixed_data_size != sizeof(SkBitmap_Data))
return false; // Message is malformed.
const char* variable_data;
int variable_data_size = 0;
if (!m->ReadData(iter, &variable_data, &variable_data_size) ||
(variable_data_size < 0)) {
NOTREACHED();
return false;
}
const SkBitmap_Data* bmp_data =
reinterpret_cast<const SkBitmap_Data*>(fixed_data);
return bmp_data->InitSkBitmapFromData(r, variable_data, variable_data_size);
}
void ParamTraits<SkBitmap>::Log(const SkBitmap& p, std::wstring* l) {
l->append(StringPrintf(L"<SkBitmap>"));
}
#endif // EXCLUDE_SKIA_DEPENDENCIES
void ParamTraits<GURL>::Write(Message* m, const GURL& p) {
m->WriteString(p.possibly_invalid_spec());
// TODO(brettw) bug 684583: Add encoding for query params.
}
bool ParamTraits<GURL>::Read(const Message* m, void** iter, GURL* p) {
std::string s;
if (!m->ReadString(iter, &s) || s.length() > chrome::kMaxURLChars) {
*p = GURL();
return false;
}
*p = GURL(s);
return true;
}
void ParamTraits<GURL>::Log(const GURL& p, std::wstring* l) {
l->append(UTF8ToWide(p.spec()));
}
void ParamTraits<gfx::Point>::Write(Message* m, const gfx::Point& p) {
m->WriteInt(p.x());
m->WriteInt(p.y());
}
bool ParamTraits<gfx::Point>::Read(const Message* m, void** iter,
gfx::Point* r) {
int x, y;
if (!m->ReadInt(iter, &x) ||
!m->ReadInt(iter, &y))
return false;
r->set_x(x);
r->set_y(y);
return true;
}
void ParamTraits<gfx::Point>::Log(const gfx::Point& p, std::wstring* l) {
l->append(StringPrintf(L"(%d, %d)", p.x(), p.y()));
}
void ParamTraits<gfx::Rect>::Write(Message* m, const gfx::Rect& p) {
m->WriteInt(p.x());
m->WriteInt(p.y());
m->WriteInt(p.width());
m->WriteInt(p.height());
}
bool ParamTraits<gfx::Rect>::Read(const Message* m, void** iter, gfx::Rect* r) {
int x, y, w, h;
if (!m->ReadInt(iter, &x) ||
!m->ReadInt(iter, &y) ||
!m->ReadInt(iter, &w) ||
!m->ReadInt(iter, &h))
return false;
if (x < 0 || y < 0 || x >= (INT_MAX - w) || y >= (INT_MAX - h) ||
w < 0 || h < 0 || h >= ((INT_MAX / 16) / (w ? w : 1)))
return false;
r->set_x(x);
r->set_y(y);
r->set_width(w);
r->set_height(h);
return true;
}
void ParamTraits<gfx::Rect>::Log(const gfx::Rect& p, std::wstring* l) {
l->append(StringPrintf(L"(%d, %d, %d, %d)", p.x(), p.y(),
p.width(), p.height()));
}
void ParamTraits<gfx::Size>::Write(Message* m, const gfx::Size& p) {
m->WriteInt(p.width());
m->WriteInt(p.height());
}
bool ParamTraits<gfx::Size>::Read(const Message* m, void** iter, gfx::Size* r) {
int w, h;
if (!m->ReadInt(iter, &w) ||
!m->ReadInt(iter, &h))
return false;
if (w < 0 || h < 0 || h >= ((INT_MAX / 16) / (w ? w : 1)))
return false;
r->set_width(w);
r->set_height(h);
return true;
}
void ParamTraits<gfx::Size>::Log(const gfx::Size& p, std::wstring* l) {
l->append(StringPrintf(L"(%d, %d)", p.width(), p.height()));
}
void ParamTraits<ContentSettings>::Write(
Message* m, const ContentSettings& settings) {
for (size_t i = 0; i < arraysize(settings.settings); ++i)
WriteParam(m, settings.settings[i]);
}
bool ParamTraits<ContentSettings>::Read(
const Message* m, void** iter, ContentSettings* r) {
for (size_t i = 0; i < arraysize(r->settings); ++i) {
if (!ReadParam(m, iter, &r->settings[i]))
return false;
}
return true;
}
void ParamTraits<ContentSettings>::Log(
const ContentSettings& p, std::wstring* l) {
l->append(StringPrintf(L"<ContentSettings>"));
}
void ParamTraits<webkit_glue::WebApplicationInfo>::Write(
Message* m, const webkit_glue::WebApplicationInfo& p) {
WriteParam(m, p.title);
WriteParam(m, p.description);
WriteParam(m, p.app_url);
WriteParam(m, p.icons.size());
for (size_t i = 0; i < p.icons.size(); ++i) {
WriteParam(m, p.icons[i].url);
WriteParam(m, p.icons[i].width);
WriteParam(m, p.icons[i].height);
}
}
bool ParamTraits<webkit_glue::WebApplicationInfo>::Read(
const Message* m, void** iter, webkit_glue::WebApplicationInfo* r) {
size_t icon_count;
bool result =
ReadParam(m, iter, &r->title) &&
ReadParam(m, iter, &r->description) &&
ReadParam(m, iter, &r->app_url) &&
ReadParam(m, iter, &icon_count);
if (!result)
return false;
for (size_t i = 0; i < icon_count; ++i) {
param_type::IconInfo icon_info;
result =
ReadParam(m, iter, &icon_info.url) &&
ReadParam(m, iter, &icon_info.width) &&
ReadParam(m, iter, &icon_info.height);
if (!result)
return false;
r->icons.push_back(icon_info);
}
return true;
}
void ParamTraits<webkit_glue::WebApplicationInfo>::Log(
const webkit_glue::WebApplicationInfo& p, std::wstring* l) {
l->append(L"<WebApplicationInfo>");
}
void ParamTraits<Geoposition::ErrorCode>::Write(
Message* m, const Geoposition::ErrorCode& p) {
int error_code = p;
WriteParam(m, error_code);
}
bool ParamTraits<Geoposition::ErrorCode>::Read(
const Message* m, void** iter, Geoposition::ErrorCode* p) {
int error_code_param = 0;
bool ret = ReadParam(m, iter, &error_code_param);
*p = static_cast<Geoposition::ErrorCode>(error_code_param);
return ret;
}
void ParamTraits<Geoposition::ErrorCode>::Log(
const Geoposition::ErrorCode& p, std::wstring* l) {
int error_code = p;
l->append(StringPrintf(L"<Geoposition::ErrorCode>%d", error_code));
}
void ParamTraits<Geoposition>::Write(Message* m, const Geoposition& p) {
WriteParam(m, p.latitude);
WriteParam(m, p.longitude);
WriteParam(m, p.accuracy);
WriteParam(m, p.altitude);
WriteParam(m, p.altitude_accuracy);
WriteParam(m, p.speed);
WriteParam(m, p.heading);
WriteParam(m, p.timestamp);
WriteParam(m, p.error_code);
WriteParam(m, p.error_message);
}
bool ParamTraits<Geoposition>::Read(
const Message* m, void** iter, Geoposition* p) {
bool ret = ReadParam(m, iter, &p->latitude);
ret = ret && ReadParam(m, iter, &p->longitude);
ret = ret && ReadParam(m, iter, &p->accuracy);
ret = ret && ReadParam(m, iter, &p->altitude);
ret = ret && ReadParam(m, iter, &p->altitude_accuracy);
ret = ret && ReadParam(m, iter, &p->speed);
ret = ret && ReadParam(m, iter, &p->heading);
ret = ret && ReadParam(m, iter, &p->timestamp);
ret = ret && ReadParam(m, iter, &p->error_code);
ret = ret && ReadParam(m, iter, &p->error_message);
return ret;
}
void ParamTraits<Geoposition>::Log(const Geoposition& p, std::wstring* l) {
l->append(
StringPrintf(
L"<Geoposition>"
L"%.6f %.6f %.6f %.6f "
L"%.6f %.6f %.6f ",
p.latitude, p.longitude, p.accuracy, p.altitude,
p.altitude_accuracy, p.speed, p.heading));
LogParam(p.timestamp, l);
l->append(L" ");
l->append(p.error_message);
LogParam(p.error_code, l);
}
} // namespace IPC
<commit_msg>Revert 45797 - Apply a sanity limit to objects with width & height.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/common_param_traits.h"
#include "chrome/common/chrome_constants.h"
#include "gfx/rect.h"
#include "googleurl/src/gurl.h"
#ifndef EXCLUDE_SKIA_DEPENDENCIES
#include "third_party/skia/include/core/SkBitmap.h"
#endif
#include "webkit/glue/dom_operations.h"
namespace IPC {
#ifndef EXCLUDE_SKIA_DEPENDENCIES
namespace {
struct SkBitmap_Data {
// The configuration for the bitmap (bits per pixel, etc).
SkBitmap::Config fConfig;
// The width of the bitmap in pixels.
uint32 fWidth;
// The height of the bitmap in pixels.
uint32 fHeight;
void InitSkBitmapDataForTransfer(const SkBitmap& bitmap) {
fConfig = bitmap.config();
fWidth = bitmap.width();
fHeight = bitmap.height();
}
// Returns whether |bitmap| successfully initialized.
bool InitSkBitmapFromData(SkBitmap* bitmap, const char* pixels,
size_t total_pixels) const {
if (total_pixels) {
bitmap->setConfig(fConfig, fWidth, fHeight, 0);
if (!bitmap->allocPixels())
return false;
if (total_pixels != bitmap->getSize())
return false;
memcpy(bitmap->getPixels(), pixels, total_pixels);
}
return true;
}
};
} // namespace
void ParamTraits<SkBitmap>::Write(Message* m, const SkBitmap& p) {
size_t fixed_size = sizeof(SkBitmap_Data);
SkBitmap_Data bmp_data;
bmp_data.InitSkBitmapDataForTransfer(p);
m->WriteData(reinterpret_cast<const char*>(&bmp_data),
static_cast<int>(fixed_size));
size_t pixel_size = p.getSize();
SkAutoLockPixels p_lock(p);
m->WriteData(reinterpret_cast<const char*>(p.getPixels()),
static_cast<int>(pixel_size));
}
bool ParamTraits<SkBitmap>::Read(const Message* m, void** iter, SkBitmap* r) {
const char* fixed_data;
int fixed_data_size = 0;
if (!m->ReadData(iter, &fixed_data, &fixed_data_size) ||
(fixed_data_size <= 0)) {
NOTREACHED();
return false;
}
if (fixed_data_size != sizeof(SkBitmap_Data))
return false; // Message is malformed.
const char* variable_data;
int variable_data_size = 0;
if (!m->ReadData(iter, &variable_data, &variable_data_size) ||
(variable_data_size < 0)) {
NOTREACHED();
return false;
}
const SkBitmap_Data* bmp_data =
reinterpret_cast<const SkBitmap_Data*>(fixed_data);
return bmp_data->InitSkBitmapFromData(r, variable_data, variable_data_size);
}
void ParamTraits<SkBitmap>::Log(const SkBitmap& p, std::wstring* l) {
l->append(StringPrintf(L"<SkBitmap>"));
}
#endif // EXCLUDE_SKIA_DEPENDENCIES
void ParamTraits<GURL>::Write(Message* m, const GURL& p) {
m->WriteString(p.possibly_invalid_spec());
// TODO(brettw) bug 684583: Add encoding for query params.
}
bool ParamTraits<GURL>::Read(const Message* m, void** iter, GURL* p) {
std::string s;
if (!m->ReadString(iter, &s) || s.length() > chrome::kMaxURLChars) {
*p = GURL();
return false;
}
*p = GURL(s);
return true;
}
void ParamTraits<GURL>::Log(const GURL& p, std::wstring* l) {
l->append(UTF8ToWide(p.spec()));
}
void ParamTraits<gfx::Point>::Write(Message* m, const gfx::Point& p) {
m->WriteInt(p.x());
m->WriteInt(p.y());
}
bool ParamTraits<gfx::Point>::Read(const Message* m, void** iter,
gfx::Point* r) {
int x, y;
if (!m->ReadInt(iter, &x) ||
!m->ReadInt(iter, &y))
return false;
r->set_x(x);
r->set_y(y);
return true;
}
void ParamTraits<gfx::Point>::Log(const gfx::Point& p, std::wstring* l) {
l->append(StringPrintf(L"(%d, %d)", p.x(), p.y()));
}
void ParamTraits<gfx::Rect>::Write(Message* m, const gfx::Rect& p) {
m->WriteInt(p.x());
m->WriteInt(p.y());
m->WriteInt(p.width());
m->WriteInt(p.height());
}
bool ParamTraits<gfx::Rect>::Read(const Message* m, void** iter, gfx::Rect* r) {
int x, y, w, h;
if (!m->ReadInt(iter, &x) ||
!m->ReadInt(iter, &y) ||
!m->ReadInt(iter, &w) ||
!m->ReadInt(iter, &h))
return false;
r->set_x(x);
r->set_y(y);
r->set_width(w);
r->set_height(h);
return true;
}
void ParamTraits<gfx::Rect>::Log(const gfx::Rect& p, std::wstring* l) {
l->append(StringPrintf(L"(%d, %d, %d, %d)", p.x(), p.y(),
p.width(), p.height()));
}
void ParamTraits<gfx::Size>::Write(Message* m, const gfx::Size& p) {
m->WriteInt(p.width());
m->WriteInt(p.height());
}
bool ParamTraits<gfx::Size>::Read(const Message* m, void** iter, gfx::Size* r) {
int w, h;
if (!m->ReadInt(iter, &w) ||
!m->ReadInt(iter, &h))
return false;
r->set_width(w);
r->set_height(h);
return true;
}
void ParamTraits<gfx::Size>::Log(const gfx::Size& p, std::wstring* l) {
l->append(StringPrintf(L"(%d, %d)", p.width(), p.height()));
}
void ParamTraits<ContentSettings>::Write(
Message* m, const ContentSettings& settings) {
for (size_t i = 0; i < arraysize(settings.settings); ++i)
WriteParam(m, settings.settings[i]);
}
bool ParamTraits<ContentSettings>::Read(
const Message* m, void** iter, ContentSettings* r) {
for (size_t i = 0; i < arraysize(r->settings); ++i) {
if (!ReadParam(m, iter, &r->settings[i]))
return false;
}
return true;
}
void ParamTraits<ContentSettings>::Log(
const ContentSettings& p, std::wstring* l) {
l->append(StringPrintf(L"<ContentSettings>"));
}
void ParamTraits<webkit_glue::WebApplicationInfo>::Write(
Message* m, const webkit_glue::WebApplicationInfo& p) {
WriteParam(m, p.title);
WriteParam(m, p.description);
WriteParam(m, p.app_url);
WriteParam(m, p.icons.size());
for (size_t i = 0; i < p.icons.size(); ++i) {
WriteParam(m, p.icons[i].url);
WriteParam(m, p.icons[i].width);
WriteParam(m, p.icons[i].height);
}
}
bool ParamTraits<webkit_glue::WebApplicationInfo>::Read(
const Message* m, void** iter, webkit_glue::WebApplicationInfo* r) {
size_t icon_count;
bool result =
ReadParam(m, iter, &r->title) &&
ReadParam(m, iter, &r->description) &&
ReadParam(m, iter, &r->app_url) &&
ReadParam(m, iter, &icon_count);
if (!result)
return false;
for (size_t i = 0; i < icon_count; ++i) {
param_type::IconInfo icon_info;
result =
ReadParam(m, iter, &icon_info.url) &&
ReadParam(m, iter, &icon_info.width) &&
ReadParam(m, iter, &icon_info.height);
if (!result)
return false;
r->icons.push_back(icon_info);
}
return true;
}
void ParamTraits<webkit_glue::WebApplicationInfo>::Log(
const webkit_glue::WebApplicationInfo& p, std::wstring* l) {
l->append(L"<WebApplicationInfo>");
}
void ParamTraits<Geoposition::ErrorCode>::Write(
Message* m, const Geoposition::ErrorCode& p) {
int error_code = p;
WriteParam(m, error_code);
}
bool ParamTraits<Geoposition::ErrorCode>::Read(
const Message* m, void** iter, Geoposition::ErrorCode* p) {
int error_code_param = 0;
bool ret = ReadParam(m, iter, &error_code_param);
*p = static_cast<Geoposition::ErrorCode>(error_code_param);
return ret;
}
void ParamTraits<Geoposition::ErrorCode>::Log(
const Geoposition::ErrorCode& p, std::wstring* l) {
int error_code = p;
l->append(StringPrintf(L"<Geoposition::ErrorCode>%d", error_code));
}
void ParamTraits<Geoposition>::Write(Message* m, const Geoposition& p) {
WriteParam(m, p.latitude);
WriteParam(m, p.longitude);
WriteParam(m, p.accuracy);
WriteParam(m, p.altitude);
WriteParam(m, p.altitude_accuracy);
WriteParam(m, p.speed);
WriteParam(m, p.heading);
WriteParam(m, p.timestamp);
WriteParam(m, p.error_code);
WriteParam(m, p.error_message);
}
bool ParamTraits<Geoposition>::Read(
const Message* m, void** iter, Geoposition* p) {
bool ret = ReadParam(m, iter, &p->latitude);
ret = ret && ReadParam(m, iter, &p->longitude);
ret = ret && ReadParam(m, iter, &p->accuracy);
ret = ret && ReadParam(m, iter, &p->altitude);
ret = ret && ReadParam(m, iter, &p->altitude_accuracy);
ret = ret && ReadParam(m, iter, &p->speed);
ret = ret && ReadParam(m, iter, &p->heading);
ret = ret && ReadParam(m, iter, &p->timestamp);
ret = ret && ReadParam(m, iter, &p->error_code);
ret = ret && ReadParam(m, iter, &p->error_message);
return ret;
}
void ParamTraits<Geoposition>::Log(const Geoposition& p, std::wstring* l) {
l->append(
StringPrintf(
L"<Geoposition>"
L"%.6f %.6f %.6f %.6f "
L"%.6f %.6f %.6f ",
p.latitude, p.longitude, p.accuracy, p.altitude,
p.altitude_accuracy, p.speed, p.heading));
LogParam(p.timestamp, l);
l->append(L" ");
l->append(p.error_message);
LogParam(p.error_code, l);
}
} // namespace IPC
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/nacl/nacl_validation_query.h"
#include "base/logging.h"
#include "crypto/nss_util.h"
#include "chrome/nacl/nacl_validation_db.h"
#include "native_client/src/trusted/validator/validation_cache.h"
NaClValidationQueryContext::NaClValidationQueryContext(
NaClValidationDB* db,
const std::string& profile_key,
const std::string& nacl_version)
: db_(db),
profile_key_(profile_key),
nacl_version_(nacl_version) {
// Sanity checks.
CHECK(profile_key.length() >= 8);
CHECK(nacl_version.length() >= 4);
}
NaClValidationQuery* NaClValidationQueryContext::CreateQuery() {
NaClValidationQuery* query = new NaClValidationQuery(db_, profile_key_);
// Changing the version effectively invalidates existing hashes.
query->AddData(nacl_version_);
return query;
}
NaClValidationQuery::NaClValidationQuery(NaClValidationDB* db,
const std::string& profile_key)
: state_(READY),
hasher_(crypto::HMAC::SHA256),
db_(db),
buffer_length_(0) {
// Without this line on Linux, HMAC::Init will instantiate a singleton that
// in turn attempts to open a file. Disabling this behavior avoids a ~70 ms
// stall the first time HMAC is used.
// This function is also called in nacl_helper_linux.cc, but nacl_helper may
// not be used in all cases.
// TODO(ncbray) remove when nacl_helper becomes the only code path.
// http://code.google.com/p/chromium/issues/detail?id=118263
#if defined(OS_LINUX)
crypto::ForceNSSNoDBInit();
#endif
CHECK(hasher_.Init(profile_key));
}
void NaClValidationQuery::AddData(const char* data, size_t length) {
CHECK(state_ == READY);
CHECK(buffer_length_ >= 0);
CHECK(buffer_length_ <= (int) sizeof(buffer_));
// Chrome's HMAC class doesn't support incremental signing. Work around
// this by using a (small) temporary buffer to accumulate data.
// Check if there is space in the buffer.
if (buffer_length_ + kDigestLength > (int) sizeof(buffer_)) {
// Hash the buffer to make space.
CompressBuffer();
}
// Hash the input data into the buffer. Assumes that sizeof(buffer_) >=
// kDigestLength * 2 (the buffer can store at least two digests.)
CHECK(hasher_.Sign(base::StringPiece(data, length),
reinterpret_cast<unsigned char*>(buffer_ + buffer_length_),
kDigestLength));
buffer_length_ += kDigestLength;
}
void NaClValidationQuery::AddData(const unsigned char* data, size_t length) {
AddData(reinterpret_cast<const char*>(data), length);
}
void NaClValidationQuery::AddData(const base::StringPiece& data) {
AddData(data.data(), data.length());
}
int NaClValidationQuery::QueryKnownToValidate() {
CHECK(state_ == READY);
// It is suspicious if we have less than a digest's worth of data.
CHECK(buffer_length_ >= kDigestLength);
CHECK(buffer_length_ <= (int) sizeof(buffer_));
state_ = GET_CALLED;
// Ensure the buffer contains only one digest worth of data.
CompressBuffer();
return db_->QueryKnownToValidate(std::string(buffer_, buffer_length_));
}
void NaClValidationQuery::SetKnownToValidate() {
CHECK(state_ == GET_CALLED);
CHECK(buffer_length_ == kDigestLength);
state_ = SET_CALLED;
db_->SetKnownToValidate(std::string(buffer_, buffer_length_));
}
// Reduce the size of the data in the buffer by hashing it and writing it back
// to the buffer.
void NaClValidationQuery::CompressBuffer() {
// Calculate the digest into a temp buffer. It is likely safe to calculate it
// directly back into the buffer, but this is an "accidental" semantic we're
// avoiding depending on.
unsigned char temp[kDigestLength];
CHECK(hasher_.Sign(base::StringPiece(buffer_, buffer_length_), temp,
kDigestLength));
memcpy(buffer_, temp, kDigestLength);
buffer_length_ = kDigestLength;
}
// OO wrappers
static void* CreateQuery(void* handle) {
return static_cast<NaClValidationQueryContext*>(handle)->CreateQuery();
}
static void AddData(void* query, const uint8* data, size_t length) {
static_cast<NaClValidationQuery*>(query)->AddData(data, length);
}
static int QueryKnownToValidate(void* query) {
return static_cast<NaClValidationQuery*>(query)->QueryKnownToValidate();
}
static void SetKnownToValidate(void* query) {
static_cast<NaClValidationQuery*>(query)->SetKnownToValidate();
}
static void DestroyQuery(void* query) {
delete static_cast<NaClValidationQuery*>(query);
}
struct NaClValidationCache* CreateValidationCache(
NaClValidationDB* db, const std::string& profile_key,
const std::string& nacl_version) {
NaClValidationCache* cache =
static_cast<NaClValidationCache*>(malloc(sizeof(NaClValidationCache)));
// Make sure any fields introduced in a cross-repo change are zeroed.
memset(cache, 0, sizeof(*cache));
cache->handle = new NaClValidationQueryContext(db, profile_key, nacl_version);
cache->CreateQuery = CreateQuery;
cache->AddData = AddData;
cache->QueryKnownToValidate = QueryKnownToValidate;
cache->SetKnownToValidate = SetKnownToValidate;
cache->DestroyQuery = DestroyQuery;
return cache;
}
<commit_msg>Fix linux build with use_openssl=1 in GYP_DEFINES<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/nacl/nacl_validation_query.h"
#include "base/logging.h"
#include "crypto/nss_util.h"
#include "chrome/nacl/nacl_validation_db.h"
#include "native_client/src/trusted/validator/validation_cache.h"
NaClValidationQueryContext::NaClValidationQueryContext(
NaClValidationDB* db,
const std::string& profile_key,
const std::string& nacl_version)
: db_(db),
profile_key_(profile_key),
nacl_version_(nacl_version) {
// Sanity checks.
CHECK(profile_key.length() >= 8);
CHECK(nacl_version.length() >= 4);
}
NaClValidationQuery* NaClValidationQueryContext::CreateQuery() {
NaClValidationQuery* query = new NaClValidationQuery(db_, profile_key_);
// Changing the version effectively invalidates existing hashes.
query->AddData(nacl_version_);
return query;
}
NaClValidationQuery::NaClValidationQuery(NaClValidationDB* db,
const std::string& profile_key)
: state_(READY),
hasher_(crypto::HMAC::SHA256),
db_(db),
buffer_length_(0) {
// Without this line on Linux, HMAC::Init will instantiate a singleton that
// in turn attempts to open a file. Disabling this behavior avoids a ~70 ms
// stall the first time HMAC is used.
// This function is also called in nacl_helper_linux.cc, but nacl_helper may
// not be used in all cases.
// TODO(ncbray) remove when nacl_helper becomes the only code path.
// http://code.google.com/p/chromium/issues/detail?id=118263
#if defined(USE_NSS)
crypto::ForceNSSNoDBInit();
#endif
CHECK(hasher_.Init(profile_key));
}
void NaClValidationQuery::AddData(const char* data, size_t length) {
CHECK(state_ == READY);
CHECK(buffer_length_ >= 0);
CHECK(buffer_length_ <= (int) sizeof(buffer_));
// Chrome's HMAC class doesn't support incremental signing. Work around
// this by using a (small) temporary buffer to accumulate data.
// Check if there is space in the buffer.
if (buffer_length_ + kDigestLength > (int) sizeof(buffer_)) {
// Hash the buffer to make space.
CompressBuffer();
}
// Hash the input data into the buffer. Assumes that sizeof(buffer_) >=
// kDigestLength * 2 (the buffer can store at least two digests.)
CHECK(hasher_.Sign(base::StringPiece(data, length),
reinterpret_cast<unsigned char*>(buffer_ + buffer_length_),
kDigestLength));
buffer_length_ += kDigestLength;
}
void NaClValidationQuery::AddData(const unsigned char* data, size_t length) {
AddData(reinterpret_cast<const char*>(data), length);
}
void NaClValidationQuery::AddData(const base::StringPiece& data) {
AddData(data.data(), data.length());
}
int NaClValidationQuery::QueryKnownToValidate() {
CHECK(state_ == READY);
// It is suspicious if we have less than a digest's worth of data.
CHECK(buffer_length_ >= kDigestLength);
CHECK(buffer_length_ <= (int) sizeof(buffer_));
state_ = GET_CALLED;
// Ensure the buffer contains only one digest worth of data.
CompressBuffer();
return db_->QueryKnownToValidate(std::string(buffer_, buffer_length_));
}
void NaClValidationQuery::SetKnownToValidate() {
CHECK(state_ == GET_CALLED);
CHECK(buffer_length_ == kDigestLength);
state_ = SET_CALLED;
db_->SetKnownToValidate(std::string(buffer_, buffer_length_));
}
// Reduce the size of the data in the buffer by hashing it and writing it back
// to the buffer.
void NaClValidationQuery::CompressBuffer() {
// Calculate the digest into a temp buffer. It is likely safe to calculate it
// directly back into the buffer, but this is an "accidental" semantic we're
// avoiding depending on.
unsigned char temp[kDigestLength];
CHECK(hasher_.Sign(base::StringPiece(buffer_, buffer_length_), temp,
kDigestLength));
memcpy(buffer_, temp, kDigestLength);
buffer_length_ = kDigestLength;
}
// OO wrappers
static void* CreateQuery(void* handle) {
return static_cast<NaClValidationQueryContext*>(handle)->CreateQuery();
}
static void AddData(void* query, const uint8* data, size_t length) {
static_cast<NaClValidationQuery*>(query)->AddData(data, length);
}
static int QueryKnownToValidate(void* query) {
return static_cast<NaClValidationQuery*>(query)->QueryKnownToValidate();
}
static void SetKnownToValidate(void* query) {
static_cast<NaClValidationQuery*>(query)->SetKnownToValidate();
}
static void DestroyQuery(void* query) {
delete static_cast<NaClValidationQuery*>(query);
}
struct NaClValidationCache* CreateValidationCache(
NaClValidationDB* db, const std::string& profile_key,
const std::string& nacl_version) {
NaClValidationCache* cache =
static_cast<NaClValidationCache*>(malloc(sizeof(NaClValidationCache)));
// Make sure any fields introduced in a cross-repo change are zeroed.
memset(cache, 0, sizeof(*cache));
cache->handle = new NaClValidationQueryContext(db, profile_key, nacl_version);
cache->CreateQuery = CreateQuery;
cache->AddData = AddData;
cache->QueryKnownToValidate = QueryKnownToValidate;
cache->SetKnownToValidate = SetKnownToValidate;
cache->DestroyQuery = DestroyQuery;
return cache;
}
<|endoftext|>
|
<commit_before>#include "yaml-cpp/node/node.h"
#include "yaml-cpp/node/impl.h"
#include "yaml-cpp/node/convert.h"
#include "yaml-cpp/node/iterator.h"
#include "yaml-cpp/node/detail/impl.h"
#include "gtest/gtest.h"
namespace YAML {
namespace {
TEST(NodeTest, SimpleScalar) {
YAML::Node node = YAML::Node("Hello, World!");
EXPECT_TRUE(node.IsScalar());
EXPECT_EQ("Hello, World!", node.as<std::string>());
}
TEST(NodeTest, IntScalar) {
YAML::Node node = YAML::Node(15);
EXPECT_TRUE(node.IsScalar());
EXPECT_EQ(15, node.as<int>());
}
TEST(NodeTest, SimpleAppendSequence) {
YAML::Node node;
node.push_back(10);
node.push_back("foo");
node.push_back("monkey");
EXPECT_TRUE(node.IsSequence());
EXPECT_EQ(3, node.size());
EXPECT_EQ(10, node[0].as<int>());
EXPECT_EQ("foo", node[1].as<std::string>());
EXPECT_EQ("monkey", node[2].as<std::string>());
EXPECT_TRUE(node.IsSequence());
}
TEST(NodeTest, SimpleAssignSequence) {
YAML::Node node;
node[0] = 10;
node[1] = "foo";
node[2] = "monkey";
EXPECT_TRUE(node.IsSequence());
EXPECT_EQ(3, node.size());
EXPECT_EQ(10, node[0].as<int>());
EXPECT_EQ("foo", node[1].as<std::string>());
EXPECT_EQ("monkey", node[2].as<std::string>());
EXPECT_TRUE(node.IsSequence());
}
TEST(NodeTest, SimpleMap) {
YAML::Node node;
node["key"] = "value";
EXPECT_TRUE(node.IsMap());
EXPECT_EQ("value", node["key"].as<std::string>());
EXPECT_EQ(1, node.size());
}
TEST(NodeTest, MapWithUndefinedValues) {
YAML::Node node;
node["key"] = "value";
node["undefined"];
EXPECT_TRUE(node.IsMap());
EXPECT_EQ("value", node["key"].as<std::string>());
EXPECT_EQ(1, node.size());
node["undefined"] = "monkey";
EXPECT_EQ("monkey", node["undefined"].as<std::string>());
EXPECT_EQ(2, node.size());
}
TEST(NodeTest, MapIteratorWithUndefinedValues) {
YAML::Node node;
node["key"] = "value";
node["undefined"];
std::size_t count = 0;
for (const_iterator it = node.begin(); it != node.end(); ++it)
count++;
EXPECT_EQ(1, count);
}
TEST(NodeTest, SimpleSubkeys) {
YAML::Node node;
node["device"]["udid"] = "12345";
node["device"]["name"] = "iPhone";
node["device"]["os"] = "4.0";
node["username"] = "monkey";
EXPECT_EQ("12345", node["device"]["udid"].as<std::string>());
EXPECT_EQ("iPhone", node["device"]["name"].as<std::string>());
EXPECT_EQ("4.0", node["device"]["os"].as<std::string>());
EXPECT_EQ("monkey", node["username"].as<std::string>());
}
TEST(NodeTest, StdVector) {
std::vector<int> primes;
primes.push_back(2);
primes.push_back(3);
primes.push_back(5);
primes.push_back(7);
primes.push_back(11);
primes.push_back(13);
YAML::Node node;
node["primes"] = primes;
EXPECT_EQ(primes, node["primes"].as<std::vector<int> >());
}
TEST(NodeTest, StdList) {
std::list<int> primes;
primes.push_back(2);
primes.push_back(3);
primes.push_back(5);
primes.push_back(7);
primes.push_back(11);
primes.push_back(13);
YAML::Node node;
node["primes"] = primes;
EXPECT_EQ(primes, node["primes"].as<std::list<int> >());
}
TEST(NodeTest, StdMap) {
std::map<int, int> squares;
squares[0] = 0;
squares[1] = 1;
squares[2] = 4;
squares[3] = 9;
squares[4] = 16;
YAML::Node node;
node["squares"] = squares;
std::map<int, int> actualSquares = node["squares"].as<std::map<int, int> >();
EXPECT_EQ(squares, actualSquares);
}
TEST(NodeTest, StdPair) {
std::pair<int, std::string> p;
p.first = 5;
p.second = "five";
YAML::Node node;
node["pair"] = p;
std::pair<int, std::string> actualP =
node["pair"].as<std::pair<int, std::string> >();
EXPECT_EQ(p, actualP);
}
TEST(NodeTest, SimpleAlias) {
YAML::Node node;
node["foo"] = "value";
node["bar"] = node["foo"];
EXPECT_EQ("value", node["foo"].as<std::string>());
EXPECT_EQ("value", node["bar"].as<std::string>());
EXPECT_EQ(node["bar"], node["foo"]);
EXPECT_EQ(2, node.size());
}
TEST(NodeTest, AliasAsKey) {
YAML::Node node;
node["foo"] = "value";
YAML::Node value = node["foo"];
node[value] = "foo";
EXPECT_EQ("value", node["foo"].as<std::string>());
EXPECT_EQ("foo", node[value].as<std::string>());
EXPECT_EQ("foo", node["value"].as<std::string>());
EXPECT_EQ(2, node.size());
}
TEST(NodeTest, SelfReferenceSequence) {
YAML::Node node;
node[0] = node;
EXPECT_TRUE(node.IsSequence());
EXPECT_EQ(1, node.size());
EXPECT_EQ(node, node[0]);
EXPECT_EQ(node, node[0][0]);
EXPECT_EQ(node[0], node[0][0]);
}
TEST(NodeTest, ValueSelfReferenceMap) {
YAML::Node node;
node["key"] = node;
EXPECT_TRUE(node.IsMap());
EXPECT_EQ(1, node.size());
EXPECT_EQ(node, node["key"]);
EXPECT_EQ(node, node["key"]["key"]);
EXPECT_EQ(node["key"], node["key"]["key"]);
}
TEST(NodeTest, KeySelfReferenceMap) {
YAML::Node node;
node[node] = "value";
EXPECT_TRUE(node.IsMap());
EXPECT_EQ(1, node.size());
EXPECT_EQ("value", node[node].as<std::string>());
}
TEST(NodeTest, SelfReferenceMap) {
YAML::Node node;
node[node] = node;
EXPECT_TRUE(node.IsMap());
EXPECT_EQ(1, node.size());
EXPECT_EQ(node, node[node]);
EXPECT_EQ(node, node[node][node]);
EXPECT_EQ(node[node], node[node][node]);
}
TEST(NodeTest, TempMapVariable) {
YAML::Node node;
YAML::Node tmp = node["key"];
tmp = "value";
EXPECT_TRUE(node.IsMap());
EXPECT_EQ(1, node.size());
EXPECT_EQ("value", node["key"].as<std::string>());
}
TEST(NodeTest, TempMapVariableAlias) {
YAML::Node node;
YAML::Node tmp = node["key"];
tmp = node["other"];
node["other"] = "value";
EXPECT_TRUE(node.IsMap());
EXPECT_EQ(2, node.size());
EXPECT_EQ("value", node["key"].as<std::string>());
EXPECT_EQ("value", node["other"].as<std::string>());
EXPECT_EQ(node["key"], node["other"]);
}
TEST(NodeTest, Bool) {
YAML::Node node;
node[true] = false;
EXPECT_TRUE(node.IsMap());
EXPECT_EQ(false, node[true].as<bool>());
}
TEST(NodeTest, AutoBoolConversion) {
YAML::Node node;
node["foo"] = "bar";
EXPECT_TRUE(static_cast<bool>(node["foo"]));
EXPECT_TRUE(!node["monkey"]);
EXPECT_TRUE(!!node["foo"]);
}
TEST(NodeTest, FloatingPrecision) {
const double x = 0.123456789;
YAML::Node node = YAML::Node(x);
EXPECT_EQ(x, node.as<double>());
}
TEST(NodeTest, SpaceChar) {
YAML::Node node = YAML::Node(' ');
EXPECT_EQ(' ', node.as<char>());
}
TEST(NodeTest, CloneNull) {
Node node;
Node clone = Clone(node);
EXPECT_EQ(NodeType::Null, clone.Type());
}
}
}
<commit_msg>Disable warning:<commit_after>#include "yaml-cpp/node/node.h"
#include "yaml-cpp/node/impl.h"
#include "yaml-cpp/node/convert.h"
#include "yaml-cpp/node/iterator.h"
#include "yaml-cpp/node/detail/impl.h"
#include "gtest/gtest.h"
namespace YAML {
namespace {
TEST(NodeTest, SimpleScalar) {
YAML::Node node = YAML::Node("Hello, World!");
EXPECT_TRUE(node.IsScalar());
EXPECT_EQ("Hello, World!", node.as<std::string>());
}
TEST(NodeTest, IntScalar) {
YAML::Node node = YAML::Node(15);
EXPECT_TRUE(node.IsScalar());
EXPECT_EQ(15, node.as<int>());
}
TEST(NodeTest, SimpleAppendSequence) {
YAML::Node node;
node.push_back(10);
node.push_back("foo");
node.push_back("monkey");
EXPECT_TRUE(node.IsSequence());
EXPECT_EQ(3, node.size());
EXPECT_EQ(10, node[0].as<int>());
EXPECT_EQ("foo", node[1].as<std::string>());
EXPECT_EQ("monkey", node[2].as<std::string>());
EXPECT_TRUE(node.IsSequence());
}
TEST(NodeTest, SimpleAssignSequence) {
YAML::Node node;
node[0] = 10;
node[1] = "foo";
node[2] = "monkey";
EXPECT_TRUE(node.IsSequence());
EXPECT_EQ(3, node.size());
EXPECT_EQ(10, node[0].as<int>());
EXPECT_EQ("foo", node[1].as<std::string>());
EXPECT_EQ("monkey", node[2].as<std::string>());
EXPECT_TRUE(node.IsSequence());
}
TEST(NodeTest, SimpleMap) {
YAML::Node node;
node["key"] = "value";
EXPECT_TRUE(node.IsMap());
EXPECT_EQ("value", node["key"].as<std::string>());
EXPECT_EQ(1, node.size());
}
TEST(NodeTest, MapWithUndefinedValues) {
YAML::Node node;
node["key"] = "value";
node["undefined"];
EXPECT_TRUE(node.IsMap());
EXPECT_EQ("value", node["key"].as<std::string>());
EXPECT_EQ(1, node.size());
node["undefined"] = "monkey";
EXPECT_EQ("monkey", node["undefined"].as<std::string>());
EXPECT_EQ(2, node.size());
}
TEST(NodeTest, MapIteratorWithUndefinedValues) {
YAML::Node node;
node["key"] = "value";
node["undefined"];
std::size_t count = 0;
for (const_iterator it = node.begin(); it != node.end(); ++it)
count++;
EXPECT_EQ(1, count);
}
TEST(NodeTest, SimpleSubkeys) {
YAML::Node node;
node["device"]["udid"] = "12345";
node["device"]["name"] = "iPhone";
node["device"]["os"] = "4.0";
node["username"] = "monkey";
EXPECT_EQ("12345", node["device"]["udid"].as<std::string>());
EXPECT_EQ("iPhone", node["device"]["name"].as<std::string>());
EXPECT_EQ("4.0", node["device"]["os"].as<std::string>());
EXPECT_EQ("monkey", node["username"].as<std::string>());
}
TEST(NodeTest, StdVector) {
std::vector<int> primes;
primes.push_back(2);
primes.push_back(3);
primes.push_back(5);
primes.push_back(7);
primes.push_back(11);
primes.push_back(13);
YAML::Node node;
node["primes"] = primes;
EXPECT_EQ(primes, node["primes"].as<std::vector<int> >());
}
TEST(NodeTest, StdList) {
std::list<int> primes;
primes.push_back(2);
primes.push_back(3);
primes.push_back(5);
primes.push_back(7);
primes.push_back(11);
primes.push_back(13);
YAML::Node node;
node["primes"] = primes;
EXPECT_EQ(primes, node["primes"].as<std::list<int> >());
}
TEST(NodeTest, StdMap) {
std::map<int, int> squares;
squares[0] = 0;
squares[1] = 1;
squares[2] = 4;
squares[3] = 9;
squares[4] = 16;
YAML::Node node;
node["squares"] = squares;
std::map<int, int> actualSquares = node["squares"].as<std::map<int, int> >();
EXPECT_EQ(squares, actualSquares);
}
TEST(NodeTest, StdPair) {
std::pair<int, std::string> p;
p.first = 5;
p.second = "five";
YAML::Node node;
node["pair"] = p;
std::pair<int, std::string> actualP =
node["pair"].as<std::pair<int, std::string> >();
EXPECT_EQ(p, actualP);
}
TEST(NodeTest, SimpleAlias) {
YAML::Node node;
node["foo"] = "value";
node["bar"] = node["foo"];
EXPECT_EQ("value", node["foo"].as<std::string>());
EXPECT_EQ("value", node["bar"].as<std::string>());
EXPECT_EQ(node["bar"], node["foo"]);
EXPECT_EQ(2, node.size());
}
TEST(NodeTest, AliasAsKey) {
YAML::Node node;
node["foo"] = "value";
YAML::Node value = node["foo"];
node[value] = "foo";
EXPECT_EQ("value", node["foo"].as<std::string>());
EXPECT_EQ("foo", node[value].as<std::string>());
EXPECT_EQ("foo", node["value"].as<std::string>());
EXPECT_EQ(2, node.size());
}
TEST(NodeTest, SelfReferenceSequence) {
YAML::Node node;
node[0] = node;
EXPECT_TRUE(node.IsSequence());
EXPECT_EQ(1, node.size());
EXPECT_EQ(node, node[0]);
EXPECT_EQ(node, node[0][0]);
EXPECT_EQ(node[0], node[0][0]);
}
TEST(NodeTest, ValueSelfReferenceMap) {
YAML::Node node;
node["key"] = node;
EXPECT_TRUE(node.IsMap());
EXPECT_EQ(1, node.size());
EXPECT_EQ(node, node["key"]);
EXPECT_EQ(node, node["key"]["key"]);
EXPECT_EQ(node["key"], node["key"]["key"]);
}
TEST(NodeTest, KeySelfReferenceMap) {
YAML::Node node;
node[node] = "value";
EXPECT_TRUE(node.IsMap());
EXPECT_EQ(1, node.size());
EXPECT_EQ("value", node[node].as<std::string>());
}
TEST(NodeTest, SelfReferenceMap) {
YAML::Node node;
node[node] = node;
EXPECT_TRUE(node.IsMap());
EXPECT_EQ(1, node.size());
EXPECT_EQ(node, node[node]);
EXPECT_EQ(node, node[node][node]);
EXPECT_EQ(node[node], node[node][node]);
}
TEST(NodeTest, TempMapVariable) {
YAML::Node node;
YAML::Node tmp = node["key"];
tmp = "value";
EXPECT_TRUE(node.IsMap());
EXPECT_EQ(1, node.size());
EXPECT_EQ("value", node["key"].as<std::string>());
}
TEST(NodeTest, TempMapVariableAlias) {
YAML::Node node;
YAML::Node tmp = node["key"];
tmp = node["other"];
node["other"] = "value";
EXPECT_TRUE(node.IsMap());
EXPECT_EQ(2, node.size());
EXPECT_EQ("value", node["key"].as<std::string>());
EXPECT_EQ("value", node["other"].as<std::string>());
EXPECT_EQ(node["key"], node["other"]);
}
TEST(NodeTest, Bool) {
YAML::Node node;
node[true] = false;
EXPECT_TRUE(node.IsMap());
EXPECT_EQ(false, node[true].as<bool>());
}
TEST(NodeTest, AutoBoolConversion) {
#pragma warning(disable:4800)
YAML::Node node;
node["foo"] = "bar";
EXPECT_TRUE(static_cast<bool>(node["foo"]));
EXPECT_TRUE(!node["monkey"]);
EXPECT_TRUE(!!node["foo"]);
}
TEST(NodeTest, FloatingPrecision) {
const double x = 0.123456789;
YAML::Node node = YAML::Node(x);
EXPECT_EQ(x, node.as<double>());
}
TEST(NodeTest, SpaceChar) {
YAML::Node node = YAML::Node(' ');
EXPECT_EQ(' ', node.as<char>());
}
TEST(NodeTest, CloneNull) {
Node node;
Node clone = Clone(node);
EXPECT_EQ(NodeType::Null, clone.Type());
}
}
}
<|endoftext|>
|
<commit_before>//===- llvm/unittest/IR/AsmWriter.cpp - AsmWriter tests -------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Module.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
TEST(AsmWriterTest, DebugPrintDetachedInstruction) {
// PR24852: Ensure that an instruction can be printed even when it
// has metadata attached but no parent.
LLVMContext Ctx;
auto Ty = Type::getInt32Ty(Ctx);
auto Undef = UndefValue::get(Ty);
std::unique_ptr<BinaryOperator> Add(BinaryOperator::CreateAdd(Undef, Undef));
Add->setMetadata(
"", MDNode::get(Ctx, {ConstantAsMetadata::get(ConstantInt::get(Ty, 1))}));
std::string S;
raw_string_ostream OS(S);
Add->print(OS);
std::size_t r = OS.str().find("<badref> = add i32 undef, undef, !<empty");
EXPECT_TRUE(r != std::string::npos);
}
TEST(AsmWriterTest, DebugPrintDetachedArgument) {
LLVMContext Ctx;
auto Ty = Type::getInt32Ty(Ctx);
auto Arg = new Argument(Ty);
std::string S;
raw_string_ostream OS(S);
Arg->print(OS);
EXPECT_EQ(S, "i32 <badref>");
}
TEST(AsmWriterTest, DumpDIExpression) {
LLVMContext Ctx;
uint64_t Ops[] = {
dwarf::DW_OP_constu, 4,
dwarf::DW_OP_minus,
dwarf::DW_OP_deref,
};
DIExpression *Expr = DIExpression::get(Ctx, Ops);
std::string S;
raw_string_ostream OS(S);
Expr->print(OS);
EXPECT_EQ("!DIExpression(DW_OP_constu, 4, DW_OP_minus, DW_OP_deref)",
OS.str());
}
}
<commit_msg>IR: Cleanup after test to silence ASAN builds<commit_after>//===- llvm/unittest/IR/AsmWriter.cpp - AsmWriter tests -------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Module.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
TEST(AsmWriterTest, DebugPrintDetachedInstruction) {
// PR24852: Ensure that an instruction can be printed even when it
// has metadata attached but no parent.
LLVMContext Ctx;
auto Ty = Type::getInt32Ty(Ctx);
auto Undef = UndefValue::get(Ty);
std::unique_ptr<BinaryOperator> Add(BinaryOperator::CreateAdd(Undef, Undef));
Add->setMetadata(
"", MDNode::get(Ctx, {ConstantAsMetadata::get(ConstantInt::get(Ty, 1))}));
std::string S;
raw_string_ostream OS(S);
Add->print(OS);
std::size_t r = OS.str().find("<badref> = add i32 undef, undef, !<empty");
EXPECT_TRUE(r != std::string::npos);
}
TEST(AsmWriterTest, DebugPrintDetachedArgument) {
LLVMContext Ctx;
auto Ty = Type::getInt32Ty(Ctx);
auto Arg = new Argument(Ty);
std::string S;
raw_string_ostream OS(S);
Arg->print(OS);
EXPECT_EQ(S, "i32 <badref>");
delete Arg;
}
TEST(AsmWriterTest, DumpDIExpression) {
LLVMContext Ctx;
uint64_t Ops[] = {
dwarf::DW_OP_constu, 4,
dwarf::DW_OP_minus,
dwarf::DW_OP_deref,
};
DIExpression *Expr = DIExpression::get(Ctx, Ops);
std::string S;
raw_string_ostream OS(S);
Expr->print(OS);
EXPECT_EQ("!DIExpression(DW_OP_constu, 4, DW_OP_minus, DW_OP_deref)",
OS.str());
}
}
<|endoftext|>
|
<commit_before>/*
* nRF51-DK BLEDevice service/characteristic (read/write) using mbed.org
*/
// uncomment if not interested in a console log
#define CONSOLE_LOG
#include "mbed.h"
#include "BLE.h"
//-------------------------------------------------------------------------
#ifdef CONSOLE_LOG
#define INFO(x, ...) printf(x, ##__VA_ARGS__);
#define INFO_NL(x, ...) printf(x "\r\n", ##__VA_ARGS__);
#else
#define INFO(x, ...)
#define INFO_NL(x, ...)
#endif
// a little routine to print a 128-bit UUID nicely
void INFO_UUID(const char *prefix, UUID uuid)
{
uint8_t *p = (uint8_t *)uuid.getBaseUUID();
INFO("%s: ", prefix);
for (int i=0; i<16; i++)
{
INFO("%02x", p[i]);
if ((i == 3) || (i == 5) || (i == 7) || (i == 9)) INFO("-");
}
INFO_NL("");
}
//-------------------------------------------------------------------------
// name of the device
const static char DEVICE_NAME[] = "nRF51-DK";
// GATT service and characteristic UUIDs
const UUID nRF51_GATT_SERVICE = UUID((uint8_t *)"nRF51-DK ");
const UUID nRF51_GATT_CHAR_BUTTON = UUID((uint8_t *)"nRF51-DK button ");
const UUID nRF51_GATT_CHAR_LED = UUID((uint8_t *)"nRF51-DK led ");
#define CHARACTERISTIC_BUTTON 0
#define CHARACTERISTIC_LED 1
#define CHARACTERISTIC_COUNT 2
// our bluetooth smart objects
BLEDevice ble;
GattService *gatt_service;
GattCharacteristic *gatt_characteristics[CHARACTERISTIC_COUNT];
uint8_t gatt_char_value[CHARACTERISTIC_COUNT];
#ifdef CONSOLE_LOG
Serial pc(USBTX,USBRX);
#endif
//-------------------------------------------------------------------------
// button handling
//-------------------------------------------------------------------------
// define our digital in values we will be using for the characteristic
DigitalIn button1(P0_17);
DigitalIn button2(P0_18);
DigitalIn button3(P0_19);
DigitalIn button4(P0_20);
uint8_t button_new_value = 0;
uint8_t button_old_value = button_new_value;
void monitorButtons()
{
// read in the buttons, mapped into nibble (0000 = all off, 1111 = all on)
button_new_value = 0;
button_new_value |= (button1.read() != 1); button_new_value <<= 1;
button_new_value |= (button2.read() != 1); button_new_value <<= 1;
button_new_value |= (button3.read() != 1); button_new_value <<= 1;
button_new_value |= (button4.read() != 1);
// set the updated value of the characteristic if data has changed
if (button_new_value != button_old_value)
{
ble.updateCharacteristicValue(
gatt_characteristics[CHARACTERISTIC_BUTTON] -> getValueHandle(),
&button_new_value, sizeof(button_new_value));
button_old_value = button_new_value;
INFO_NL(" button state: [0x%02x]", button_new_value);
}
}
//-------------------------------------------------------------------------
// LED handling
//-------------------------------------------------------------------------
DigitalOut led1(P0_21);
DigitalOut led2(P0_22);
DigitalOut led3(P0_23);
DigitalOut led4(P0_24);
uint8_t led_value = 0;
void onLedDataWritten(const uint8_t* value, uint8_t length)
{
// we only care about a single byte
led_value = value[0];
// depending on the value coming through; set/unset LED's
if ((led_value & 0x01) != 0) led1.write(0); else led1.write(1);
if ((led_value & 0x02) != 0) led2.write(0); else led2.write(1);
if ((led_value & 0x04) != 0) led3.write(0); else led3.write(1);
if ((led_value & 0x08) != 0) led4.write(0); else led4.write(1);
INFO_NL(" led state: [0x%02x]", led_value);
}
//-------------------------------------------------------------------------
void onConnection(const Gap::ConnectionCallbackParams_t *params)
{
INFO_NL(">> connected");
// set the initial values of the characteristics (for every session)
led_value = 0;
onLedDataWritten(&led_value, 1); // force LED's to be in off state
}
void onDataWritten(const GattWriteCallbackParams *context)
{
// was the characteristic being written to nRF51_GATT_CHAR_LED?
if (context -> handle ==
gatt_characteristics[CHARACTERISTIC_LED] -> getValueHandle())
{
onLedDataWritten(context -> data, context -> len);
}
}
void onDisconnection(Gap::Handle_t handle,
Gap::DisconnectionReason_t disconnectReason)
{
INFO_NL(">> disconnected");
ble.startAdvertising();
INFO_NL(">> device advertising");
}
int main()
{
#ifdef CONSOLE_LOG
// wait a second before trying to write something to console
wait(1);
#endif
INFO_NL(">> nRF51-DK start");
// create our button characteristic (read, notify)
gatt_characteristics[CHARACTERISTIC_BUTTON] =
new GattCharacteristic(
nRF51_GATT_CHAR_BUTTON,
&gatt_char_value[CHARACTERISTIC_BUTTON], 1, 1,
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ |
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY);
// create our LED characteristic (read, write)
gatt_characteristics[CHARACTERISTIC_LED] =
new GattCharacteristic(
nRF51_GATT_CHAR_LED,
&gatt_char_value[CHARACTERISTIC_LED], 1, 1,
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ |
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE |
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE);
// create our service, with both characteristics
gatt_service =
new GattService(nRF51_GATT_SERVICE,
gatt_characteristics, CHARACTERISTIC_COUNT);
// initialize our ble device
ble.init();
ble.setDeviceName((uint8_t *)DEVICE_NAME);
INFO_NL(">> initialized device '%s'", DEVICE_NAME);
// configure our advertising type, payload and interval
ble.accumulateAdvertisingPayload(
GapAdvertisingData::BREDR_NOT_SUPPORTED |
GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
ble.accumulateAdvertisingPayload(
GapAdvertisingData::COMPLETE_LOCAL_NAME,
(uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
ble.setAdvertisingInterval(160); // 100ms
INFO_NL(">> configured advertising type, payload and interval");
// configure our callbacks
ble.onDisconnection(onDisconnection);
ble.onConnection(onConnection);
ble.onDataWritten(onDataWritten);
INFO_NL(">> registered for callbacks");
// add our gatt service with two characteristics
ble.addService(*gatt_service);
INFO_NL(">> added GATT service with two characteristics");
// show some debugging information about service/characteristics
INFO_UUID(" ", nRF51_GATT_SERVICE);
INFO_UUID(" :", nRF51_GATT_CHAR_BUTTON);
INFO_UUID(" :", nRF51_GATT_CHAR_LED);
// start advertising
ble.startAdvertising();
INFO_NL(">> device advertising");
// start monitoring the buttons and posting new values
Ticker ticker;
ticker.attach(monitorButtons, 0.1); // every 10th of a second
INFO_NL(">> monitoring button state");
// let the device do its thing
INFO_NL(">> waiting for events ");
for (;;)
{
ble.waitForEvent();
}
}
//-------------------------------------------------------------------------
<commit_msg>30 Sep 2015 - update to changed in mbed BLE API <commit_after>/*
* nRF51-DK BLEDevice service/characteristic (read/write) using mbed.org
*/
// uncomment if not interested in a console log
#define CONSOLE_LOG
#include "mbed.h"
#include "BLE.h"
//-------------------------------------------------------------------------
#ifdef CONSOLE_LOG
#define INFO(x, ...) printf(x, ##__VA_ARGS__);
#define INFO_NL(x, ...) printf(x "\r\n", ##__VA_ARGS__);
#else
#define INFO(x, ...)
#define INFO_NL(x, ...)
#endif
// a little routine to print a 128-bit UUID nicely
void INFO_UUID(const char *prefix, UUID uuid)
{
uint8_t *p = (uint8_t *)uuid.getBaseUUID();
INFO("%s: ", prefix);
for (int i=0; i<16; i++)
{
INFO("%02x", p[i]);
if ((i == 3) || (i == 5) || (i == 7) || (i == 9)) INFO("-");
}
INFO_NL("");
}
//-------------------------------------------------------------------------
// name of the device
const static char DEVICE_NAME[] = "nRF51-DK";
// GATT service and characteristic UUIDs
const UUID nRF51_GATT_SERVICE = UUID((uint8_t *)"nRF51-DK ");
const UUID nRF51_GATT_CHAR_BUTTON = UUID((uint8_t *)"nRF51-DK button ");
const UUID nRF51_GATT_CHAR_LED = UUID((uint8_t *)"nRF51-DK led ");
#define CHARACTERISTIC_BUTTON 0
#define CHARACTERISTIC_LED 1
#define CHARACTERISTIC_COUNT 2
// our bluetooth smart objects
BLEDevice ble;
GattService *gatt_service;
GattCharacteristic *gatt_characteristics[CHARACTERISTIC_COUNT];
uint8_t gatt_char_value[CHARACTERISTIC_COUNT];
#ifdef CONSOLE_LOG
Serial pc(USBTX,USBRX);
#endif
//-------------------------------------------------------------------------
// button handling
//-------------------------------------------------------------------------
// define our digital in values we will be using for the characteristic
DigitalIn button1(P0_17);
DigitalIn button2(P0_18);
DigitalIn button3(P0_19);
DigitalIn button4(P0_20);
uint8_t button_new_value = 0;
uint8_t button_old_value = button_new_value;
void monitorButtons()
{
// read in the buttons, mapped into nibble (0000 = all off, 1111 = all on)
button_new_value = 0;
button_new_value |= (button1.read() != 1); button_new_value <<= 1;
button_new_value |= (button2.read() != 1); button_new_value <<= 1;
button_new_value |= (button3.read() != 1); button_new_value <<= 1;
button_new_value |= (button4.read() != 1);
// set the updated value of the characteristic if data has changed
if (button_new_value != button_old_value)
{
ble.updateCharacteristicValue(
gatt_characteristics[CHARACTERISTIC_BUTTON] -> getValueHandle(),
&button_new_value, sizeof(button_new_value));
button_old_value = button_new_value;
INFO_NL(" button state: [0x%02x]", button_new_value);
}
}
//-------------------------------------------------------------------------
// LED handling
//-------------------------------------------------------------------------
DigitalOut led1(P0_21);
DigitalOut led2(P0_22);
DigitalOut led3(P0_23);
DigitalOut led4(P0_24);
uint8_t led_value = 0;
void onLedDataWritten(const uint8_t* value, uint8_t length)
{
// we only care about a single byte
led_value = value[0];
// depending on the value coming through; set/unset LED's
if ((led_value & 0x01) != 0) led1.write(0); else led1.write(1);
if ((led_value & 0x02) != 0) led2.write(0); else led2.write(1);
if ((led_value & 0x04) != 0) led3.write(0); else led3.write(1);
if ((led_value & 0x08) != 0) led4.write(0); else led4.write(1);
INFO_NL(" led state: [0x%02x]", led_value);
}
//-------------------------------------------------------------------------
void onConnection(const Gap::ConnectionCallbackParams_t *params)
{
INFO_NL(">> connected");
// set the initial values of the characteristics (for every session)
led_value = 0;
onLedDataWritten(&led_value, 1); // force LED's to be in off state
}
void onDataWritten(const GattWriteCallbackParams *context)
{
// was the characteristic being written to nRF51_GATT_CHAR_LED?
if (context -> handle ==
gatt_characteristics[CHARACTERISTIC_LED] -> getValueHandle())
{
onLedDataWritten(context -> data, context -> len);
}
}
void onDisconnection(const Gap::DisconnectionCallbackParams_t *params)
{
INFO_NL(">> disconnected");
ble.startAdvertising();
INFO_NL(">> device advertising");
}
int main()
{
#ifdef CONSOLE_LOG
// wait a second before trying to write something to console
wait(1);
#endif
INFO_NL(">> nRF51-DK start");
// create our button characteristic (read, notify)
gatt_characteristics[CHARACTERISTIC_BUTTON] =
new GattCharacteristic(
nRF51_GATT_CHAR_BUTTON,
&gatt_char_value[CHARACTERISTIC_BUTTON], 1, 1,
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ |
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY);
// create our LED characteristic (read, write)
gatt_characteristics[CHARACTERISTIC_LED] =
new GattCharacteristic(
nRF51_GATT_CHAR_LED,
&gatt_char_value[CHARACTERISTIC_LED], 1, 1,
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ |
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE |
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE);
// create our service, with both characteristics
gatt_service =
new GattService(nRF51_GATT_SERVICE,
gatt_characteristics, CHARACTERISTIC_COUNT);
// initialize our ble device
ble.init();
ble.setDeviceName((uint8_t *)DEVICE_NAME);
INFO_NL(">> initialized device '%s'", DEVICE_NAME);
// configure our advertising type, payload and interval
ble.accumulateAdvertisingPayload(
GapAdvertisingData::BREDR_NOT_SUPPORTED |
GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
ble.accumulateAdvertisingPayload(
GapAdvertisingData::COMPLETE_LOCAL_NAME,
(uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
ble.setAdvertisingInterval(160); // 100ms
INFO_NL(">> configured advertising type, payload and interval");
// configure our callbacks
ble.onDisconnection(onDisconnection);
ble.onConnection(onConnection);
ble.onDataWritten(onDataWritten);
INFO_NL(">> registered for callbacks");
// add our gatt service with two characteristics
ble.addService(*gatt_service);
INFO_NL(">> added GATT service with two characteristics");
// show some debugging information about service/characteristics
INFO_UUID(" ", nRF51_GATT_SERVICE);
INFO_UUID(" :", nRF51_GATT_CHAR_BUTTON);
INFO_UUID(" :", nRF51_GATT_CHAR_LED);
// start advertising
ble.startAdvertising();
INFO_NL(">> device advertising");
// start monitoring the buttons and posting new values
Ticker ticker;
ticker.attach(monitorButtons, 0.1); // every 10th of a second
INFO_NL(">> monitoring button state");
// let the device do its thing
INFO_NL(">> waiting for events ");
for (;;)
{
ble.waitForEvent();
}
}
//-------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee — CLIPP Echo Generator Implementation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#include "echo_generator.hpp"
#include <boost/make_shared.hpp>
using namespace std;
namespace IronBee {
namespace CLIPP {
struct EchoGenerator::State
{
State() :
produced_input(false)
{
// nop
}
bool produced_input;
string id;
string request;
};
EchoGenerator::EchoGenerator()
{
// nop
}
EchoGenerator::EchoGenerator(
const string& request_line
) :
m_state(boost::make_shared<State>())
{
m_state->id = request_line;
m_state->request = request_line + "\r\n";
}
bool EchoGenerator::operator()(Input::input_p& out_input)
{
if (m_state->produced_input) {
return false;
}
out_input->id = m_state->id;
out_input->connection = Input::Connection();
out_input->connection.connection_opened(
Input::Buffer(local_ip), local_port,
Input::Buffer(remote_ip), remote_port
);
out_input->connection.connection_closed();
out_input->connection.add_transaction(
Input::Buffer(m_state->request),
Input::Buffer()
);
m_state->produced_input = true;
return true;
}
const string EchoGenerator::local_ip = "1.2.3.4";
const string EchoGenerator::remote_ip = "5.6.7.8";
const uint16_t EchoGenerator::local_port = 1234;
const uint16_t EchoGenerator::remote_port = 5678;
} // CLIPP
} // IronBee
<commit_msg>clipp: Echo generator no longer has connection data out event.<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief IronBee — CLIPP Echo Generator Implementation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#include "echo_generator.hpp"
#include <boost/make_shared.hpp>
using namespace std;
namespace IronBee {
namespace CLIPP {
struct EchoGenerator::State
{
State() :
produced_input(false)
{
// nop
}
bool produced_input;
string id;
string request;
};
EchoGenerator::EchoGenerator()
{
// nop
}
EchoGenerator::EchoGenerator(
const string& request_line
) :
m_state(boost::make_shared<State>())
{
m_state->id = request_line;
m_state->request = request_line + "\r\n";
}
bool EchoGenerator::operator()(Input::input_p& out_input)
{
if (m_state->produced_input) {
return false;
}
out_input->id = m_state->id;
out_input->connection = Input::Connection();
out_input->connection.connection_opened(
Input::Buffer(local_ip), local_port,
Input::Buffer(remote_ip), remote_port
);
out_input->connection.connection_closed();
out_input->connection.add_transaction()
.connection_data_in(Input::Buffer(m_state->request));
m_state->produced_input = true;
return true;
}
const string EchoGenerator::local_ip = "1.2.3.4";
const string EchoGenerator::remote_ip = "5.6.7.8";
const uint16_t EchoGenerator::local_port = 1234;
const uint16_t EchoGenerator::remote_port = 5678;
} // CLIPP
} // IronBee
<|endoftext|>
|
<commit_before>#include <stan/lang/rethrow_located.hpp>
#include <gtest/gtest.h>
template <typename E, typename E2>
void test_rethrow_located_2() {
try {
try {
throw E("foo");
} catch (const std::exception& e) {
stan::lang::rethrow_located(e, 5);
}
} catch (const E2& e) {
EXPECT_TRUE(std::string(e.what()).find_first_of("5")
!= std::string::npos);
EXPECT_TRUE(std::string(e.what()).find_first_of("foo")
!= std::string::npos);
return;
} catch (...) {
FAIL();
}
FAIL();
}
template <typename E>
void test_rethrow_located() {
test_rethrow_located_2<E,E>();
}
template <typename E>
void test_rethrow_located_nullary(const std::string& original_type) {
try {
try {
throw E();
} catch (const std::exception& e) {
stan::lang::rethrow_located(e, 5);
}
} catch (const E& e) {
EXPECT_TRUE(std::string(e.what()).find_first_of("5")
!= std::string::npos);
EXPECT_TRUE(std::string(e.what()).find_first_of(original_type)
!= std::string::npos);
return;
} catch (...) {
FAIL();
}
FAIL();
}
struct my_test_exception : public std::exception {
const std::string what_;
my_test_exception(const std::string& what) throw() : what_(what) { }
~my_test_exception() throw() { }
const char* what() const throw() { return what_.c_str(); }
};
TEST(langRethrowLocated, allExpected) {
test_rethrow_located_nullary<std::bad_alloc>("bad_alloc");
test_rethrow_located_nullary<std::bad_cast>("bad_cast");
test_rethrow_located_nullary<std::bad_exception>("bad_exception");
test_rethrow_located_nullary<std::bad_typeid>("bad_typeid");
test_rethrow_located<std::domain_error>();
test_rethrow_located<std::invalid_argument>();
test_rethrow_located<std::length_error>();
test_rethrow_located<std::out_of_range>();
test_rethrow_located<std::logic_error>();
test_rethrow_located<std::overflow_error>();
test_rethrow_located<std::range_error>();
test_rethrow_located<std::underflow_error>();
test_rethrow_located<std::runtime_error>();
test_rethrow_located_nullary<std::exception>("std::exception");
test_rethrow_located_2<my_test_exception,std::exception>();
}
TEST(langRethrowLocated, locatedException) {
// tests nested case
using stan::lang::located_exception;
try {
try {
throw located_exception<located_exception<std::exception> >("foo","bar");
} catch (const std::exception& e) {
stan::lang::rethrow_located(e, 5);
}
} catch (const std::exception& e) {
EXPECT_TRUE(std::string(e.what()).find_first_of("foo")
!= std::string::npos);
EXPECT_TRUE(std::string(e.what()).find_first_of("bar")
!= std::string::npos);
EXPECT_TRUE(std::string(e.what()).find_first_of("5")
!= std::string::npos);
return;
} catch (...) {
FAIL();
}
FAIL();
}
<commit_msg>change ref to copy in rethrow-located test; fixes #2030<commit_after>#include <stan/lang/rethrow_located.hpp>
#include <gtest/gtest.h>
template <typename E, typename E2>
void test_rethrow_located_2() {
try {
try {
throw E("foo");
} catch (const std::exception& e) {
stan::lang::rethrow_located(e, 5);
}
} catch (const E2& e) {
EXPECT_TRUE(std::string(e.what()).find_first_of("5")
!= std::string::npos);
EXPECT_TRUE(std::string(e.what()).find_first_of("foo")
!= std::string::npos);
return;
} catch (...) {
FAIL();
}
FAIL();
}
template <typename E>
void test_rethrow_located() {
test_rethrow_located_2<E,E>();
}
template <typename E>
void test_rethrow_located_nullary(const std::string& original_type) {
try {
try {
throw E();
} catch (const std::exception& e) {
stan::lang::rethrow_located(e, 5);
}
} catch (const E& e) {
EXPECT_TRUE(std::string(e.what()).find_first_of("5")
!= std::string::npos);
EXPECT_TRUE(std::string(e.what()).find_first_of(original_type)
!= std::string::npos);
return;
} catch (...) {
FAIL();
}
FAIL();
}
struct my_test_exception : public std::exception {
const std::string what_;
my_test_exception(const std::string& what) throw() : what_(what) { }
~my_test_exception() throw() { }
const char* what() const throw() { return what_.c_str(); }
};
TEST(langRethrowLocated, allExpected) {
test_rethrow_located_nullary<std::bad_alloc>("bad_alloc");
test_rethrow_located_nullary<std::bad_cast>("bad_cast");
test_rethrow_located_nullary<std::bad_exception>("bad_exception");
test_rethrow_located_nullary<std::bad_typeid>("bad_typeid");
test_rethrow_located<std::domain_error>();
test_rethrow_located<std::invalid_argument>();
test_rethrow_located<std::length_error>();
test_rethrow_located<std::out_of_range>();
test_rethrow_located<std::logic_error>();
test_rethrow_located<std::overflow_error>();
test_rethrow_located<std::range_error>();
test_rethrow_located<std::underflow_error>();
test_rethrow_located<std::runtime_error>();
test_rethrow_located_nullary<std::exception>("std::exception");
test_rethrow_located_2<my_test_exception,std::exception>();
}
TEST(langRethrowLocated, locatedException) {
// tests nested case
using stan::lang::located_exception;
try {
try {
throw located_exception<located_exception<std::exception> >("foo","bar");
} catch (const std::exception& e) {
stan::lang::rethrow_located(e, 5);
}
} catch (const std::exception& e) {
EXPECT_TRUE(std::string(e.what()).find_first_of("foo")
!= std::string::npos);
EXPECT_TRUE(std::string(e.what()).find_first_of("bar")
!= std::string::npos);
EXPECT_TRUE(std::string(e.what()).find_first_of("5")
!= std::string::npos);
return;
} catch (...) {
FAIL();
}
FAIL();
}
<|endoftext|>
|
<commit_before>#include "Application.h"
#include <chrono>
#include "util.h"
using namespace world;
Application::Application()
: _running(false),
_mainView(std::make_unique<MainView>(*this)),
_newUpdatePos(0, 0, 5000),
_lastUpdatePos(_newUpdatePos),
_explorer(std::make_unique<FirstPersonExplorer>(1000)){
_explorer->setPosition(_lastUpdatePos);
_explorer->setFarDistance(10000);
// Collectors
for (int i = 0; i < 2; i++) {
_emptyCollectors.emplace_back(std::make_unique<FlatWorldCollector>());
}
}
void Application::run(int argc, char **argv) {
loadWorld(argc, argv);
_running = true;
_mainView->show();
bool firstExpand = true;
while(_running) {
if (!_mainView->running()) {
_running = false;
}
else {
// On prend les paramtres en local.
_paramLock.lock();
vec3d newUpdatePos = _newUpdatePos;
if (_emptyCollectors.empty()) {
_mainView->onWorldChange();
}
_paramLock.unlock();
if (((newUpdatePos - _lastUpdatePos).norm() > 50 || firstExpand) && !_emptyCollectors.empty()) {
// get collector
_paramLock.lock();
std::unique_ptr<FlatWorldCollector> collector = std::move(_emptyCollectors.front());
_emptyCollectors.pop_front();
_paramLock.unlock();
// Mise jour du monde
collector->reset();
_explorer->setPosition(newUpdatePos);
auto start = std::chrono::steady_clock::now();
_explorer->exploreAndCollect<FlatWorld>(*_world, *collector);
if (_dbgOn) {
std::cout << "Temps d'exploration : " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count() << " ms " << std::endl;
}
_paramLock.lock();
_fullCollectors.emplace_back(std::move(collector));
_paramLock.unlock();
// Mise jour de la vue
_mainView->onWorldChange();
_lastUpdatePos = newUpdatePos;
firstExpand = false;
}
}
sleep(20.0f);
}
_mainView->waitClose();
}
void Application::requestStop() {
_running = false;
}
void Application::setUserPosition(vec3d pos) {
std::lock_guard<std::mutex> lock(_paramLock);
_newUpdatePos = pos;
}
vec3d Application::getUserPosition() const {
std::lock_guard<std::mutex> lock(_paramLock);
auto pos = _newUpdatePos;
return pos;
}
void Application::refill(std::unique_ptr<world::FlatWorldCollector> &&toRefill) {
std::lock_guard<std::mutex> lock(_paramLock);
_emptyCollectors.emplace_back(std::move(toRefill));
}
std::unique_ptr<world::FlatWorldCollector> Application::popFull() {
std::lock_guard<std::mutex> lock(_paramLock);
if (_fullCollectors.empty())
return nullptr;
auto ret = std::move(_fullCollectors.front());
_fullCollectors.pop_front();
return std::move(ret);
}
void Application::loadWorld(int argc, char **argv) {
_world = std::unique_ptr<FlatWorld>(FlatWorld::createDemoFlatWorld());
}<commit_msg>World3D : Frequent updates<commit_after>#include "Application.h"
#include <chrono>
#include "util.h"
using namespace world;
Application::Application()
: _running(false),
_mainView(std::make_unique<MainView>(*this)),
_newUpdatePos(0, 0, 5000),
_lastUpdatePos(_newUpdatePos),
_explorer(std::make_unique<FirstPersonExplorer>(1000)){
_explorer->setPosition(_lastUpdatePos);
_explorer->setFarDistance(10000);
// Collectors
for (int i = 0; i < 2; i++) {
_emptyCollectors.emplace_back(std::make_unique<FlatWorldCollector>());
}
}
void Application::run(int argc, char **argv) {
loadWorld(argc, argv);
_running = true;
_mainView->show();
while(_running) {
if (!_mainView->running()) {
_running = false;
}
else {
// On prend les paramtres en local.
_paramLock.lock();
vec3d newUpdatePos = _newUpdatePos;
if (_emptyCollectors.empty()) {
_mainView->onWorldChange();
}
_paramLock.unlock();
if ((newUpdatePos - _lastUpdatePos).norm() > 0.01 && !_emptyCollectors.empty()) {
// get collector
_paramLock.lock();
std::unique_ptr<FlatWorldCollector> collector = std::move(_emptyCollectors.front());
_emptyCollectors.pop_front();
_paramLock.unlock();
// Mise jour du monde
collector->reset();
_explorer->setPosition(newUpdatePos);
auto start = std::chrono::steady_clock::now();
_explorer->exploreAndCollect<FlatWorld>(*_world, *collector);
if (_dbgOn) {
std::cout << "Temps d'exploration : " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count() << " ms " << std::endl;
}
_paramLock.lock();
_fullCollectors.emplace_back(std::move(collector));
_paramLock.unlock();
// Mise jour de la vue
_mainView->onWorldChange();
_lastUpdatePos = newUpdatePos;
}
}
sleep(20.0f);
}
_mainView->waitClose();
}
void Application::requestStop() {
_running = false;
}
void Application::setUserPosition(vec3d pos) {
std::lock_guard<std::mutex> lock(_paramLock);
_newUpdatePos = pos;
}
vec3d Application::getUserPosition() const {
std::lock_guard<std::mutex> lock(_paramLock);
auto pos = _newUpdatePos;
return pos;
}
void Application::refill(std::unique_ptr<world::FlatWorldCollector> &&toRefill) {
std::lock_guard<std::mutex> lock(_paramLock);
_emptyCollectors.emplace_back(std::move(toRefill));
}
std::unique_ptr<world::FlatWorldCollector> Application::popFull() {
std::lock_guard<std::mutex> lock(_paramLock);
if (_fullCollectors.empty())
return nullptr;
auto ret = std::move(_fullCollectors.front());
_fullCollectors.pop_front();
return std::move(ret);
}
void Application::loadWorld(int argc, char **argv) {
_world = std::unique_ptr<FlatWorld>(FlatWorld::createDemoFlatWorld());
}<|endoftext|>
|
<commit_before>/*
Copyright 2013 Rogier van Dalen.
This file is part of Rogier van Dalen's Rime library for C++.
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define BOOST_TEST_MODULE test_rime_sign
#include "utility/test/boost_unit_test.hpp"
#include "rime/sign.hpp"
#include <string>
#include <type_traits>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/int.hpp>
#include "rime/core.hpp"
#include "check_equal.hpp"
BOOST_AUTO_TEST_SUITE(test_rime_sign)
BOOST_AUTO_TEST_CASE (test_rime_sign_types) {
// is_signed.
static_assert (rime::types::is_signed <int>::value, "");
static_assert (rime::types::is_signed <short>::value, "");
static_assert (rime::types::is_signed <rime::int_ <-1>>::value, "");
static_assert (rime::types::is_signed <boost::mpl::int_ <0>>::value, "");
static_assert (rime::types::is_signed
<std::integral_constant <int, 1>>::value, "");
static_assert (!rime::types::is_signed <unsigned>::value, "");
static_assert (!rime::types::is_signed <unsigned short>::value, "");
static_assert (!rime::types::is_signed <std::size_t>::value, "");
static_assert (!rime::types::is_signed <rime::size_t <0>>::value, "");
static_assert (!rime::types::is_signed <rime::size_t <2>>::value, "");
static_assert (!rime::types::is_signed <void>::value, "");
static_assert (!rime::types::is_signed <std::string>::value, "");
// is_unsigned.
static_assert (rime::types::is_unsigned <unsigned>::value, "");
static_assert (rime::types::is_unsigned <unsigned short>::value, "");
static_assert (rime::types::is_unsigned <std::size_t>::value, "");
static_assert (rime::types::is_unsigned <rime::size_t <0>>::value, "");
static_assert (rime::types::is_unsigned <rime::size_t <2>>::value, "");
static_assert (!rime::types::is_unsigned <int>::value, "");
static_assert (!rime::types::is_unsigned <short>::value, "");
static_assert (!rime::types::is_unsigned <rime::int_ <-1>>::value, "");
static_assert (!rime::types::is_unsigned <boost::mpl::int_ <0>>::value, "");
static_assert (!rime::types::is_unsigned <
std::integral_constant <int, 1>>::value, "");
static_assert (!rime::types::is_unsigned <void>::value, "");
static_assert (!rime::types::is_unsigned <std::string>::value, "");
// make_signed.
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_signed <int>::type, int>));
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_signed <unsigned>::type, int>));
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_signed <short>::type, short>));
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_signed <unsigned short>::type, short>));
BOOST_MPL_ASSERT ((rime::same_constant <
rime::types::make_signed <rime::int_ <1>>::type, rime::int_ <1>>));
BOOST_MPL_ASSERT ((rime::same_constant <
rime::types::make_signed <rime::constant <unsigned, 1>>::type,
rime::int_ <1>>));
BOOST_MPL_ASSERT ((rime::same_constant <
rime::types::make_signed <std::integral_constant <unsigned, 2>>::type,
rime::int_ <2>>));
// make_unsigned.
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_unsigned <int>::type, unsigned>));
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_unsigned <unsigned>::type, unsigned>));
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_unsigned <short>::type, short unsigned>));
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_unsigned <unsigned short>::type,
short unsigned>));
BOOST_MPL_ASSERT ((rime::same_constant <
rime::types::make_unsigned <rime::int_ <1>>::type,
rime::constant <unsigned, 1u>>));
BOOST_MPL_ASSERT ((rime::same_constant <
rime::types::make_unsigned <rime::constant <int, 1>>::type,
rime::constant <unsigned, 1u>>));
BOOST_MPL_ASSERT ((rime::same_constant <
rime::types::make_unsigned <std::integral_constant <int, 2>>::type,
rime::constant <unsigned, 2u>>));
// make_zero.
RIME_CHECK_EQUAL (rime::types::make_zero <rime::int_ <1>>::type(),
rime::int_ <0>());
RIME_CHECK_EQUAL (rime::types::make_zero <rime::int_ <-5>>::type(),
rime::int_ <0>());
RIME_CHECK_EQUAL (
(rime::types::make_zero <rime::constant <unsigned, 1>>::type()),
(rime::constant <unsigned, 0>()));
}
BOOST_AUTO_TEST_CASE (test_rime_sign_convert) {
// make_signed.
RIME_CHECK_EQUAL (rime::make_signed (1), 1);
RIME_CHECK_EQUAL (rime::make_signed (1u), 1);
RIME_CHECK_EQUAL (rime::make_signed (rime::int_ <1>()), rime::int_ <1>());
RIME_CHECK_EQUAL (
rime::make_signed (rime::constant <unsigned, 1u>()), rime::int_ <1>());
// make_unsigned.
RIME_CHECK_EQUAL (rime::make_unsigned (1), 1u);
RIME_CHECK_EQUAL (rime::make_unsigned (1u), 1u);
RIME_CHECK_EQUAL (rime::make_unsigned (rime::int_ <3>()),
(rime::constant <unsigned, 3u>()));
RIME_CHECK_EQUAL (rime::make_unsigned (rime::constant <unsigned, 2u>()),
(rime::constant <unsigned, 2u>()));
// make_zero.
RIME_CHECK_EQUAL (rime::make_zero (1), 0);
RIME_CHECK_EQUAL (rime::make_zero (1u), 0u);
RIME_CHECK_EQUAL (rime::make_zero (rime::int_ <1>()), rime::int_ <0>());
RIME_CHECK_EQUAL (
rime::make_zero (rime::constant <unsigned, 1u>()),
(rime::constant <unsigned, 0u>()));
}
// Signed constants.
typedef rime::int_ <unsigned (-1)/2 + 1> very_negative_int;
very_negative_int i1;
boost::mpl::int_ <-4> i2;
std::integral_constant <int, 0> i3;
rime::int_ <30> i4;
rime::constant <unsigned, 0> u3;
rime::constant <unsigned, 30> u4;
typedef rime::constant <unsigned, unsigned (-1)> very_great_unsigned;
very_great_unsigned u5;
// Sanity check for constants.
static_assert (very_negative_int::value < 0, "Should be negative");
static_assert (int (very_great_unsigned::value) < 0,
"Unsigned should wrongly convert to negative");
template <bool reference, class Left, class Right>
void check_less_sign_safe (Left const & left, Right const & right)
{
// Known at compile time.
RIME_CHECK_EQUAL (rime::less_sign_safe (left, right),
rime::bool_ <reference>());
// Known only at run time.
RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, right), reference);
RIME_CHECK_EQUAL (rime::less_sign_safe (left, Right::value), reference);
RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, Right::value),
reference);
}
// The case where if the left operand is constant, the result is known.
// I.e. -1 < u for any unsigned u.
template <bool reference, class Left, class Right>
void check_less_sign_safe_left_constant (
Left const & left, Right const & right)
{
// Known at compile time.
RIME_CHECK_EQUAL (rime::less_sign_safe (left, right),
rime::bool_ <reference>());
RIME_CHECK_EQUAL (rime::less_sign_safe (left, Right::value),
rime::bool_ <reference>());
// Known only at run time.
RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, right), reference);
RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, Right::value),
reference);
}
// The case where if the right operand is constant, the result is known.
// I.e. u < -1 for any unsigned u.
template <bool reference, class Left, class Right>
void check_less_sign_safe_right_constant (
Left const & left, Right const & right)
{
// Known at compile time.
RIME_CHECK_EQUAL (rime::less_sign_safe (left, right),
rime::bool_ <reference>());
RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, right),
rime::bool_ <reference>());
// Known only at run time.
RIME_CHECK_EQUAL (rime::less_sign_safe (left, Right::value), reference);
RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, Right::value),
reference);
}
struct not_an_int {};
bool operator < (not_an_int, not_an_int) { return false; }
BOOST_AUTO_TEST_CASE (test_rime_less_sign_safe) {
check_less_sign_safe <false> (i1, i1);
check_less_sign_safe <true> (i1, i2);
check_less_sign_safe <true> (i1, i3);
check_less_sign_safe_left_constant <true> (i1, u3);
check_less_sign_safe <true> (i1, i4);
check_less_sign_safe_left_constant <true> (i1, u4);
check_less_sign_safe_left_constant <true> (i1, u5);
check_less_sign_safe <false> (i2, i1);
check_less_sign_safe <false> (i2, i2);
check_less_sign_safe <true> (i2, i3);
check_less_sign_safe_left_constant <true> (i2, u3);
check_less_sign_safe <true> (i2, i4);
check_less_sign_safe_left_constant <true> (i2, u4);
check_less_sign_safe_left_constant <true> (i2, u5);
check_less_sign_safe <false> (i3, i1);
check_less_sign_safe <false> (i3, i2);
check_less_sign_safe <false> (i3, i3);
check_less_sign_safe <false> (i3, u3);
check_less_sign_safe <true> (i3, i4);
check_less_sign_safe <true> (i3, u4);
check_less_sign_safe <true> (i3, u5);
check_less_sign_safe <false> (i4, i1);
check_less_sign_safe <false> (i4, i2);
check_less_sign_safe <false> (i4, i3);
check_less_sign_safe <false> (i4, u3);
check_less_sign_safe <false> (i4, i4);
check_less_sign_safe <false> (i4, u4);
check_less_sign_safe <true> (i4, u5);
check_less_sign_safe_right_constant <false> (u3, i1);
check_less_sign_safe_right_constant <false> (u3, i2);
check_less_sign_safe <false> (u3, i3);
check_less_sign_safe <false> (u3, u3);
check_less_sign_safe <true> (u3, i4);
check_less_sign_safe <true> (u3, u4);
check_less_sign_safe <true> (u3, u5);
check_less_sign_safe_right_constant <false> (u4, i1);
check_less_sign_safe_right_constant <false> (u4, i2);
check_less_sign_safe <false> (u4, i3);
check_less_sign_safe <false> (u4, u3);
check_less_sign_safe <false> (u4, i4);
check_less_sign_safe <false> (u4, u4);
check_less_sign_safe <true> (u4, u5);
check_less_sign_safe_right_constant <false> (u5, i1);
check_less_sign_safe_right_constant <false> (u5, i2);
check_less_sign_safe <false> (u5, i3);
check_less_sign_safe <false> (u5, u3);
check_less_sign_safe <false> (u5, i4);
check_less_sign_safe <false> (u5, u4);
check_less_sign_safe <false> (u5, u5);
RIME_CHECK_EQUAL (rime::less_sign_safe (not_an_int(), not_an_int()), false);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fix test for sign.hpp<commit_after>/*
Copyright 2013 Rogier van Dalen.
This file is part of Rogier van Dalen's Rime library for C++.
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define BOOST_TEST_MODULE test_rime_sign
#include "utility/test/boost_unit_test.hpp"
#include "rime/sign.hpp"
#include <string>
#include <type_traits>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/int.hpp>
#include "rime/core.hpp"
#include "check_equal.hpp"
BOOST_AUTO_TEST_SUITE(test_rime_sign)
BOOST_AUTO_TEST_CASE (test_rime_sign_types) {
// is_signed.
static_assert (rime::types::is_signed <int>::value, "");
static_assert (rime::types::is_signed <short>::value, "");
static_assert (rime::types::is_signed <rime::int_ <-1>>::value, "");
static_assert (rime::types::is_signed <boost::mpl::int_ <0>>::value, "");
static_assert (rime::types::is_signed
<std::integral_constant <int, 1>>::value, "");
static_assert (!rime::types::is_signed <unsigned>::value, "");
static_assert (!rime::types::is_signed <unsigned short>::value, "");
static_assert (!rime::types::is_signed <std::size_t>::value, "");
static_assert (!rime::types::is_signed <rime::size_t <0>>::value, "");
static_assert (!rime::types::is_signed <rime::size_t <2>>::value, "");
static_assert (!rime::types::is_signed <void>::value, "");
static_assert (!rime::types::is_signed <std::string>::value, "");
// is_unsigned.
static_assert (rime::types::is_unsigned <unsigned>::value, "");
static_assert (rime::types::is_unsigned <unsigned short>::value, "");
static_assert (rime::types::is_unsigned <std::size_t>::value, "");
static_assert (rime::types::is_unsigned <rime::size_t <0>>::value, "");
static_assert (rime::types::is_unsigned <rime::size_t <2>>::value, "");
static_assert (!rime::types::is_unsigned <int>::value, "");
static_assert (!rime::types::is_unsigned <short>::value, "");
static_assert (!rime::types::is_unsigned <rime::int_ <-1>>::value, "");
static_assert (!rime::types::is_unsigned <boost::mpl::int_ <0>>::value, "");
static_assert (!rime::types::is_unsigned <
std::integral_constant <int, 1>>::value, "");
static_assert (!rime::types::is_unsigned <void>::value, "");
static_assert (!rime::types::is_unsigned <std::string>::value, "");
// make_signed.
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_signed <int>::type, int>));
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_signed <unsigned>::type, int>));
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_signed <short>::type, short>));
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_signed <unsigned short>::type, short>));
BOOST_MPL_ASSERT ((rime::same_constant <
rime::types::make_signed <rime::int_ <1>>::type, rime::int_ <1>>));
BOOST_MPL_ASSERT ((rime::same_constant <
rime::types::make_signed <rime::constant <unsigned, 1>>::type,
rime::int_ <1>>));
BOOST_MPL_ASSERT ((rime::same_constant <
rime::types::make_signed <std::integral_constant <unsigned, 2>>::type,
rime::int_ <2>>));
// make_unsigned.
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_unsigned <int>::type, unsigned>));
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_unsigned <unsigned>::type, unsigned>));
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_unsigned <short>::type, short unsigned>));
BOOST_MPL_ASSERT ((std::is_same <
typename rime::types::make_unsigned <unsigned short>::type,
short unsigned>));
BOOST_MPL_ASSERT ((rime::same_constant <
rime::types::make_unsigned <rime::int_ <1>>::type,
rime::constant <unsigned, 1u>>));
BOOST_MPL_ASSERT ((rime::same_constant <
rime::types::make_unsigned <rime::constant <int, 1>>::type,
rime::constant <unsigned, 1u>>));
BOOST_MPL_ASSERT ((rime::same_constant <
rime::types::make_unsigned <std::integral_constant <int, 2>>::type,
rime::constant <unsigned, 2u>>));
// make_zero.
RIME_CHECK_EQUAL (rime::types::make_zero <rime::int_ <1>>::type(),
rime::int_ <0>());
RIME_CHECK_EQUAL (rime::types::make_zero <rime::int_ <-5>>::type(),
rime::int_ <0>());
RIME_CHECK_EQUAL (
(rime::types::make_zero <rime::constant <unsigned, 1>>::type()),
(rime::constant <unsigned, 0>()));
}
BOOST_AUTO_TEST_CASE (test_rime_sign_convert) {
// make_signed.
RIME_CHECK_EQUAL (rime::make_signed (1), 1);
RIME_CHECK_EQUAL (rime::make_signed (1u), 1);
RIME_CHECK_EQUAL (rime::make_signed (rime::int_ <1>()), rime::int_ <1>());
RIME_CHECK_EQUAL (
rime::make_signed (rime::constant <unsigned, 1u>()), rime::int_ <1>());
// make_unsigned.
RIME_CHECK_EQUAL (rime::make_unsigned (1), 1u);
RIME_CHECK_EQUAL (rime::make_unsigned (1u), 1u);
RIME_CHECK_EQUAL (rime::make_unsigned (rime::int_ <3>()),
(rime::constant <unsigned, 3u>()));
RIME_CHECK_EQUAL (rime::make_unsigned (rime::constant <unsigned, 2u>()),
(rime::constant <unsigned, 2u>()));
// make_zero.
RIME_CHECK_EQUAL (rime::make_zero (1), 0);
RIME_CHECK_EQUAL (rime::make_zero (1u), 0u);
RIME_CHECK_EQUAL (rime::make_zero (rime::int_ <1>()), rime::int_ <0>());
RIME_CHECK_EQUAL (
rime::make_zero (rime::constant <unsigned, 1u>()),
(rime::constant <unsigned, 0u>()));
}
// Signed constants.
typedef rime::int_ <int (unsigned (-1)/2 + 1)> very_negative_int;
very_negative_int i1;
boost::mpl::int_ <-4> i2;
std::integral_constant <int, 0> i3;
rime::int_ <30> i4;
rime::constant <unsigned, 0> u3;
rime::constant <unsigned, 30> u4;
typedef rime::constant <unsigned, unsigned (-1)> very_great_unsigned;
very_great_unsigned u5;
// Sanity check for constants.
static_assert (very_negative_int::value < 0, "Should be negative");
static_assert (int (very_great_unsigned::value) < 0,
"Unsigned should wrongly convert to negative");
template <bool reference, class Left, class Right>
void check_less_sign_safe (Left const & left, Right const & right)
{
// Known at compile time.
RIME_CHECK_EQUAL (rime::less_sign_safe (left, right),
rime::bool_ <reference>());
// Known only at run time.
RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, right), reference);
RIME_CHECK_EQUAL (rime::less_sign_safe (left, Right::value), reference);
RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, Right::value),
reference);
}
// The case where if the left operand is constant, the result is known.
// I.e. -1 < u for any unsigned u.
template <bool reference, class Left, class Right>
void check_less_sign_safe_left_constant (
Left const & left, Right const & right)
{
// Known at compile time.
RIME_CHECK_EQUAL (rime::less_sign_safe (left, right),
rime::bool_ <reference>());
RIME_CHECK_EQUAL (rime::less_sign_safe (left, Right::value),
rime::bool_ <reference>());
// Known only at run time.
RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, right), reference);
RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, Right::value),
reference);
}
// The case where if the right operand is constant, the result is known.
// I.e. u < -1 for any unsigned u.
template <bool reference, class Left, class Right>
void check_less_sign_safe_right_constant (
Left const & left, Right const & right)
{
// Known at compile time.
RIME_CHECK_EQUAL (rime::less_sign_safe (left, right),
rime::bool_ <reference>());
RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, right),
rime::bool_ <reference>());
// Known only at run time.
RIME_CHECK_EQUAL (rime::less_sign_safe (left, Right::value), reference);
RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, Right::value),
reference);
}
struct not_an_int {};
bool operator < (not_an_int, not_an_int) { return false; }
BOOST_AUTO_TEST_CASE (test_rime_less_sign_safe) {
check_less_sign_safe <false> (i1, i1);
check_less_sign_safe <true> (i1, i2);
check_less_sign_safe <true> (i1, i3);
check_less_sign_safe_left_constant <true> (i1, u3);
check_less_sign_safe <true> (i1, i4);
check_less_sign_safe_left_constant <true> (i1, u4);
check_less_sign_safe_left_constant <true> (i1, u5);
check_less_sign_safe <false> (i2, i1);
check_less_sign_safe <false> (i2, i2);
check_less_sign_safe <true> (i2, i3);
check_less_sign_safe_left_constant <true> (i2, u3);
check_less_sign_safe <true> (i2, i4);
check_less_sign_safe_left_constant <true> (i2, u4);
check_less_sign_safe_left_constant <true> (i2, u5);
check_less_sign_safe <false> (i3, i1);
check_less_sign_safe <false> (i3, i2);
check_less_sign_safe <false> (i3, i3);
check_less_sign_safe <false> (i3, u3);
check_less_sign_safe <true> (i3, i4);
check_less_sign_safe <true> (i3, u4);
check_less_sign_safe <true> (i3, u5);
check_less_sign_safe <false> (i4, i1);
check_less_sign_safe <false> (i4, i2);
check_less_sign_safe <false> (i4, i3);
check_less_sign_safe <false> (i4, u3);
check_less_sign_safe <false> (i4, i4);
check_less_sign_safe <false> (i4, u4);
check_less_sign_safe <true> (i4, u5);
check_less_sign_safe_right_constant <false> (u3, i1);
check_less_sign_safe_right_constant <false> (u3, i2);
check_less_sign_safe <false> (u3, i3);
check_less_sign_safe <false> (u3, u3);
check_less_sign_safe <true> (u3, i4);
check_less_sign_safe <true> (u3, u4);
check_less_sign_safe <true> (u3, u5);
check_less_sign_safe_right_constant <false> (u4, i1);
check_less_sign_safe_right_constant <false> (u4, i2);
check_less_sign_safe <false> (u4, i3);
check_less_sign_safe <false> (u4, u3);
check_less_sign_safe <false> (u4, i4);
check_less_sign_safe <false> (u4, u4);
check_less_sign_safe <true> (u4, u5);
check_less_sign_safe_right_constant <false> (u5, i1);
check_less_sign_safe_right_constant <false> (u5, i2);
check_less_sign_safe <false> (u5, i3);
check_less_sign_safe <false> (u5, u3);
check_less_sign_safe <false> (u5, i4);
check_less_sign_safe <false> (u5, u4);
check_less_sign_safe <false> (u5, u5);
RIME_CHECK_EQUAL (rime::less_sign_safe (not_an_int(), not_an_int()), false);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: HtmlReader.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:17:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBAUI_HTMLREADER_HXX
#define DBAUI_HTMLREADER_HXX
#ifndef DBAUI_DATABASEEXPORT_HXX
#include "DExport.hxx"
#endif
#ifndef _PARHTML_HXX //autogen
#include <svtools/parhtml.hxx>
#endif
#ifndef _SVX_SVXENUM_HXX
#include <svx/svxenum.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_
#include <com/sun/star/awt/FontDescriptor.hpp>
#endif
namespace dbaui
{
//===============================================================================================
// OHTMLReader
//===============================================================================================
class OHTMLReader : public HTMLParser, public ODatabaseExport
{
sal_Int32 m_nTableCount;
sal_Int16 m_nWidth;
sal_Int16 m_nColumnWidth; // max. Spaltenbreite
sal_Bool m_bMetaOptions; // true when we scaned the meta information
sal_Bool m_bSDNum;
protected:
virtual void NextToken( int nToken ); // Basisklasse
virtual sal_Bool CreateTable(int nToken);
/** createPage creates the tabpage for this type
@param _pParent teh parent window
*/
virtual OWizTypeSelect* createPage(Window* _pParent);
void TableDataOn(SvxCellHorJustify& eVal,String *pValue,int nToken);
void TableFontOn(::com::sun::star::awt::FontDescriptor& _rFont,sal_Int32 &_rTextColor);
sal_Int16 GetWidthPixel( const HTMLOption* pOption );
rtl_TextEncoding GetEncodingByMIME( const String& rMime );
void setTextEncoding();
~OHTMLReader();
public:
OHTMLReader(SvStream& rIn,
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,
const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
const TColumnVector* rList = 0,
const OTypeInfoMap* _pInfoMap = 0);
// wird f"ur auto. Typ-Erkennung gebraucht
OHTMLReader(SvStream& rIn,
sal_Int32 nRows,
const TPositions &_rColumnPositions,
const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
const TColumnVector* rList = 0,
const OTypeInfoMap* _pInfoMap = 0);
virtual SvParserState CallParser();// Basisklasse
virtual void release();
// birgt nur korrekte Daten, wenn der 2. CTOR benutzt wurde
};
SV_DECL_IMPL_REF( OHTMLReader );
}
#endif // DBAUI_HTMLREADER_HXX
<commit_msg>INTEGRATION: CWS dba201b (1.7.420); FILE MERGED 2005/09/21 08:58:12 oj 1.7.420.2: RESYNC: (1.7-1.8); FILE MERGED 2005/07/20 09:56:40 fs 1.7.420.1: #i51255# XConnection replaced with SharedConnection, and DataSourceHolder replaced with SharedModel<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: HtmlReader.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2005-09-23 12:33:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBAUI_HTMLREADER_HXX
#define DBAUI_HTMLREADER_HXX
#ifndef DBAUI_DATABASEEXPORT_HXX
#include "DExport.hxx"
#endif
#ifndef _PARHTML_HXX //autogen
#include <svtools/parhtml.hxx>
#endif
#ifndef _SVX_SVXENUM_HXX
#include <svx/svxenum.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_
#include <com/sun/star/awt/FontDescriptor.hpp>
#endif
namespace dbaui
{
//===============================================================================================
// OHTMLReader
//===============================================================================================
class OHTMLReader : public HTMLParser, public ODatabaseExport
{
sal_Int32 m_nTableCount;
sal_Int16 m_nWidth;
sal_Int16 m_nColumnWidth; // max. Spaltenbreite
sal_Bool m_bMetaOptions; // true when we scaned the meta information
sal_Bool m_bSDNum;
protected:
virtual void NextToken( int nToken ); // Basisklasse
virtual sal_Bool CreateTable(int nToken);
/** createPage creates the tabpage for this type
@param _pParent teh parent window
*/
virtual OWizTypeSelect* createPage(Window* _pParent);
void TableDataOn(SvxCellHorJustify& eVal,String *pValue,int nToken);
void TableFontOn(::com::sun::star::awt::FontDescriptor& _rFont,sal_Int32 &_rTextColor);
sal_Int16 GetWidthPixel( const HTMLOption* pOption );
rtl_TextEncoding GetEncodingByMIME( const String& rMime );
void setTextEncoding();
~OHTMLReader();
public:
OHTMLReader(SvStream& rIn,
const SharedConnection& _rxConnection,
const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
const TColumnVector* rList = 0,
const OTypeInfoMap* _pInfoMap = 0);
// wird f"ur auto. Typ-Erkennung gebraucht
OHTMLReader(SvStream& rIn,
sal_Int32 nRows,
const TPositions &_rColumnPositions,
const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
const TColumnVector* rList = 0,
const OTypeInfoMap* _pInfoMap = 0);
virtual SvParserState CallParser();// Basisklasse
virtual void release();
// birgt nur korrekte Daten, wenn der 2. CTOR benutzt wurde
};
SV_DECL_IMPL_REF( OHTMLReader );
}
#endif // DBAUI_HTMLREADER_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: evntpost.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-06-27 20:26:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <vcl/evntpost.hxx>
#include <vcl/svapp.hxx>
namespace vcl
{
EventPoster::EventPoster( const Link& rLink )
: m_aLink(rLink)
{
m_nId = 0;
}
EventPoster::~EventPoster()
{
if ( m_nId )
GetpApp()->RemoveUserEvent( m_nId );
}
void EventPoster::Post( UserEvent* pEvent )
{
m_nId = GetpApp()->PostUserEvent( ( LINK( this, EventPoster, DoEvent_Impl ) ), pEvent );
}
IMPL_LINK_INLINE_START( EventPoster, DoEvent_Impl, UserEvent*, pEvent )
{
m_nId = 0;
m_aLink.Call( pEvent );
return 0;
}
IMPL_LINK_INLINE_END( EventPoster, DoEvent_Impl, UserEvent*, pEvent )
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.248); FILE MERGED 2008/03/28 15:44:52 rt 1.7.248.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: evntpost.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <vcl/evntpost.hxx>
#include <vcl/svapp.hxx>
namespace vcl
{
EventPoster::EventPoster( const Link& rLink )
: m_aLink(rLink)
{
m_nId = 0;
}
EventPoster::~EventPoster()
{
if ( m_nId )
GetpApp()->RemoveUserEvent( m_nId );
}
void EventPoster::Post( UserEvent* pEvent )
{
m_nId = GetpApp()->PostUserEvent( ( LINK( this, EventPoster, DoEvent_Impl ) ), pEvent );
}
IMPL_LINK_INLINE_START( EventPoster, DoEvent_Impl, UserEvent*, pEvent )
{
m_nId = 0;
m_aLink.Call( pEvent );
return 0;
}
IMPL_LINK_INLINE_END( EventPoster, DoEvent_Impl, UserEvent*, pEvent )
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salinfo.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2006-07-26 09:20:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#define VCL_NEED_BASETSD
#include <tools/presys.h>
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include <tools/postsys.h>
#include <tools/string.hxx>
#include <salsys.hxx>
#include <salframe.h>
#include <salinst.h>
#include <tools/debug.hxx>
#include <svdata.hxx>
#include <window.hxx>
#include <multimon.h>
#include <vector>
class WinSalSystem : public SalSystem
{
std::vector< Rectangle > m_aMonitors;
public:
WinSalSystem() {}
virtual ~WinSalSystem();
virtual unsigned int GetDisplayScreenCount();
virtual Rectangle GetDisplayScreenPosSizePixel( unsigned int nScreen );
virtual int ShowNativeMessageBox( const String& rTitle,
const String& rMessage,
int nButtonCombination,
int nDefaultButton);
bool initMonitors();
void addMonitor( const Rectangle& rRect) { m_aMonitors.push_back( rRect ); }
};
SalSystem* WinSalInstance::CreateSalSystem()
{
return new WinSalSystem();
}
WinSalSystem::~WinSalSystem()
{
}
// -----------------------------------------------------------------------
static BOOL CALLBACK ImplEnumMonitorProc( HMONITOR hMonitor,
HDC hdcMonitor,
LPRECT lprcMonitor,
LPARAM dwData )
{
WinSalSystem* pSys = reinterpret_cast<WinSalSystem*>(dwData);
pSys->addMonitor( Rectangle( Point( lprcMonitor->left,
lprcMonitor->top ),
Size( lprcMonitor->right - lprcMonitor->left,
lprcMonitor->bottom - lprcMonitor->top ) ) );
return TRUE;
}
bool WinSalSystem::initMonitors()
{
if( m_aMonitors.size() > 0 )
return true;
bool winVerOk = true;
// multi monitor calls not available on Win95/NT
OSVERSIONINFO aVerInfo;
aVerInfo.dwOSVersionInfoSize = sizeof( aVerInfo );
if ( GetVersionEx( &aVerInfo ) )
{
if ( aVerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT )
{
if ( aVerInfo.dwMajorVersion <= 4 )
winVerOk = false; // NT
}
else if( aVerInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
{
if ( aVerInfo.dwMajorVersion == 4 && aVerInfo.dwMinorVersion == 0 )
winVerOk = false; // Win95
}
}
if( winVerOk )
{
int nMonitors = GetSystemMetrics( SM_CMONITORS );
if( nMonitors == 1 )
{
int w = GetSystemMetrics( SM_CXSCREEN );
int h = GetSystemMetrics( SM_CYSCREEN );
m_aMonitors.push_back( Rectangle( Point(), Size( w, h ) ) );
}
else
{
HDC aDesktopRC = GetDC( NULL );
EnumDisplayMonitors( aDesktopRC, NULL, ImplEnumMonitorProc, reinterpret_cast<LPARAM>(this) );
}
}
else
{
int w = GetSystemMetrics( SM_CXSCREEN );
int h = GetSystemMetrics( SM_CYSCREEN );
m_aMonitors.push_back( Rectangle( Point(), Size( w, h ) ) );
}
return m_aMonitors.size() > 0;
}
unsigned int WinSalSystem::GetDisplayScreenCount()
{
initMonitors();
return m_aMonitors.size();
}
Rectangle WinSalSystem::GetDisplayScreenPosSizePixel( unsigned int nScreen )
{
initMonitors();
return (nScreen < m_aMonitors.size()) ? m_aMonitors[nScreen] : Rectangle();
}
// -----------------------------------------------------------------------
/* We have to map the button identifier to the identifier used by the Win32
Platform SDK to specify the default button for the MessageBox API.
The first dimension is the button combination, the second dimension
is the button identifier.
*/
static int DEFAULT_BTN_MAPPING_TABLE[][8] =
{
// Undefined OK CANCEL ABORT RETRY IGNORE YES NO
{ MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1 }, //OK
{ MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1 }, //OK_CANCEL
{ MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON3, MB_DEFBUTTON1, MB_DEFBUTTON1 }, //ABORT_RETRY_IGNO
{ MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON3, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON2 }, //YES_NO_CANCEL
{ MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON2 }, //YES_NO
{ MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1 } //RETRY_CANCEL
};
int WinSalSystem::ShowNativeMessageBox(const String& rTitle, const String& rMessage, int nButtonCombination, int nDefaultButton)
{
DBG_ASSERT( nButtonCombination >= SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK &&
nButtonCombination <= SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL &&
nDefaultButton >= SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK &&
nDefaultButton <= SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO, "Invalid arguments!" );
int nFlags = MB_TASKMODAL | MB_SETFOREGROUND | MB_ICONWARNING | nButtonCombination;
if (nButtonCombination >= SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK &&
nButtonCombination <= SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL &&
nDefaultButton >= SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK &&
nDefaultButton <= SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO)
nFlags |= DEFAULT_BTN_MAPPING_TABLE[nButtonCombination][nDefaultButton];
//#107209 hide the splash screen if active
ImplSVData* pSVData = ImplGetSVData();
if (pSVData->mpIntroWindow)
pSVData->mpIntroWindow->Hide();
return MessageBoxW(
0,
rMessage.GetBuffer(),
rTitle.GetBuffer(),
nFlags);
}
<commit_msg>#i10000# ImplEnumMonitorProc: unreferenced formal parameter.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salinfo.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2006-07-26 13:47:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#define VCL_NEED_BASETSD
#include <tools/presys.h>
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include <tools/postsys.h>
#include <tools/string.hxx>
#include <salsys.hxx>
#include <salframe.h>
#include <salinst.h>
#include <tools/debug.hxx>
#include <svdata.hxx>
#include <window.hxx>
#include <multimon.h>
#include <vector>
class WinSalSystem : public SalSystem
{
std::vector< Rectangle > m_aMonitors;
public:
WinSalSystem() {}
virtual ~WinSalSystem();
virtual unsigned int GetDisplayScreenCount();
virtual Rectangle GetDisplayScreenPosSizePixel( unsigned int nScreen );
virtual int ShowNativeMessageBox( const String& rTitle,
const String& rMessage,
int nButtonCombination,
int nDefaultButton);
bool initMonitors();
void addMonitor( const Rectangle& rRect) { m_aMonitors.push_back( rRect ); }
};
SalSystem* WinSalInstance::CreateSalSystem()
{
return new WinSalSystem();
}
WinSalSystem::~WinSalSystem()
{
}
// -----------------------------------------------------------------------
static BOOL CALLBACK ImplEnumMonitorProc( HMONITOR,
HDC,
LPRECT lprcMonitor,
LPARAM dwData )
{
WinSalSystem* pSys = reinterpret_cast<WinSalSystem*>(dwData);
pSys->addMonitor( Rectangle( Point( lprcMonitor->left,
lprcMonitor->top ),
Size( lprcMonitor->right - lprcMonitor->left,
lprcMonitor->bottom - lprcMonitor->top ) ) );
return TRUE;
}
bool WinSalSystem::initMonitors()
{
if( m_aMonitors.size() > 0 )
return true;
bool winVerOk = true;
// multi monitor calls not available on Win95/NT
OSVERSIONINFO aVerInfo;
aVerInfo.dwOSVersionInfoSize = sizeof( aVerInfo );
if ( GetVersionEx( &aVerInfo ) )
{
if ( aVerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT )
{
if ( aVerInfo.dwMajorVersion <= 4 )
winVerOk = false; // NT
}
else if( aVerInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
{
if ( aVerInfo.dwMajorVersion == 4 && aVerInfo.dwMinorVersion == 0 )
winVerOk = false; // Win95
}
}
if( winVerOk )
{
int nMonitors = GetSystemMetrics( SM_CMONITORS );
if( nMonitors == 1 )
{
int w = GetSystemMetrics( SM_CXSCREEN );
int h = GetSystemMetrics( SM_CYSCREEN );
m_aMonitors.push_back( Rectangle( Point(), Size( w, h ) ) );
}
else
{
HDC aDesktopRC = GetDC( NULL );
EnumDisplayMonitors( aDesktopRC, NULL, ImplEnumMonitorProc, reinterpret_cast<LPARAM>(this) );
}
}
else
{
int w = GetSystemMetrics( SM_CXSCREEN );
int h = GetSystemMetrics( SM_CYSCREEN );
m_aMonitors.push_back( Rectangle( Point(), Size( w, h ) ) );
}
return m_aMonitors.size() > 0;
}
unsigned int WinSalSystem::GetDisplayScreenCount()
{
initMonitors();
return m_aMonitors.size();
}
Rectangle WinSalSystem::GetDisplayScreenPosSizePixel( unsigned int nScreen )
{
initMonitors();
return (nScreen < m_aMonitors.size()) ? m_aMonitors[nScreen] : Rectangle();
}
// -----------------------------------------------------------------------
/* We have to map the button identifier to the identifier used by the Win32
Platform SDK to specify the default button for the MessageBox API.
The first dimension is the button combination, the second dimension
is the button identifier.
*/
static int DEFAULT_BTN_MAPPING_TABLE[][8] =
{
// Undefined OK CANCEL ABORT RETRY IGNORE YES NO
{ MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1 }, //OK
{ MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1 }, //OK_CANCEL
{ MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON3, MB_DEFBUTTON1, MB_DEFBUTTON1 }, //ABORT_RETRY_IGNO
{ MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON3, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON2 }, //YES_NO_CANCEL
{ MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON2 }, //YES_NO
{ MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1, MB_DEFBUTTON1 } //RETRY_CANCEL
};
int WinSalSystem::ShowNativeMessageBox(const String& rTitle, const String& rMessage, int nButtonCombination, int nDefaultButton)
{
DBG_ASSERT( nButtonCombination >= SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK &&
nButtonCombination <= SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL &&
nDefaultButton >= SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK &&
nDefaultButton <= SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO, "Invalid arguments!" );
int nFlags = MB_TASKMODAL | MB_SETFOREGROUND | MB_ICONWARNING | nButtonCombination;
if (nButtonCombination >= SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK &&
nButtonCombination <= SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL &&
nDefaultButton >= SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK &&
nDefaultButton <= SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO)
nFlags |= DEFAULT_BTN_MAPPING_TABLE[nButtonCombination][nDefaultButton];
//#107209 hide the splash screen if active
ImplSVData* pSVData = ImplGetSVData();
if (pSVData->mpIntroWindow)
pSVData->mpIntroWindow->Hide();
return MessageBoxW(
0,
rMessage.GetBuffer(),
rTitle.GetBuffer(),
nFlags);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/keygen_handler.h"
#include <Security/SecAsn1Coder.h>
#include <Security/SecAsn1Templates.h>
#include <Security/Security.h>
#include "base/base64.h"
#include "base/logging.h"
#include "base/scoped_cftyperef.h"
// These are in Security.framework but not declared in a public header.
extern const SecAsn1Template kSecAsn1AlgorithmIDTemplate[];
extern const SecAsn1Template kSecAsn1SubjectPublicKeyInfoTemplate[];
namespace net {
// Declarations of Netscape keygen cert structures for ASN.1 encoding:
struct PublicKeyAndChallenge {
CSSM_X509_SUBJECT_PUBLIC_KEY_INFO spki;
CSSM_DATA challenge_string;
};
static const SecAsn1Template kPublicKeyAndChallengeTemplate[] = {
{
SEC_ASN1_SEQUENCE,
0,
NULL,
sizeof(PublicKeyAndChallenge)
},
{
SEC_ASN1_INLINE,
offsetof(PublicKeyAndChallenge, spki),
kSecAsn1SubjectPublicKeyInfoTemplate
},
{
SEC_ASN1_INLINE,
offsetof(PublicKeyAndChallenge, challenge_string),
kSecAsn1IA5StringTemplate
},
{
0
}
};
struct SignedPublicKeyAndChallenge {
PublicKeyAndChallenge pkac;
CSSM_X509_ALGORITHM_IDENTIFIER signature_algorithm;
CSSM_DATA signature;
};
static const SecAsn1Template kSignedPublicKeyAndChallengeTemplate[] = {
{
SEC_ASN1_SEQUENCE,
0,
NULL,
sizeof(SignedPublicKeyAndChallenge)
},
{
SEC_ASN1_INLINE,
offsetof(SignedPublicKeyAndChallenge, pkac),
kPublicKeyAndChallengeTemplate
},
{
SEC_ASN1_INLINE,
offsetof(SignedPublicKeyAndChallenge, signature_algorithm),
kSecAsn1AlgorithmIDTemplate
},
{
SEC_ASN1_BIT_STRING,
offsetof(SignedPublicKeyAndChallenge, signature)
},
{
0
}
};
static OSStatus CreateRSAKeyPair(int size_in_bits,
SecKeyRef* out_pub_key,
SecKeyRef* out_priv_key);
static OSStatus SignData(CSSM_DATA data,
SecKeyRef private_key,
CSSM_DATA* signature);
bool KeygenHandler::KeyLocation::Equals(
const KeygenHandler::KeyLocation& location) const {
return keychain_path == location.keychain_path;
}
std::string KeygenHandler::GenKeyAndSignChallenge() {
std::string result;
OSStatus err;
SecKeyRef public_key = NULL;
SecKeyRef private_key = NULL;
SecAsn1CoderRef coder = NULL;
CSSM_DATA signature = {0, NULL};
{
// Create the key-pair.
err = CreateRSAKeyPair(key_size_in_bits_, &public_key, &private_key);
if (err)
goto failure;
// Get the public key data (DER sequence of modulus, exponent).
CFDataRef key_data = NULL;
err = SecKeychainItemExport(public_key, kSecFormatBSAFE, 0, NULL,
&key_data);
if (err)
goto failure;
scoped_cftyperef<CFDataRef> scoped_key_data(key_data);
// Create an ASN.1 encoder.
err = SecAsn1CoderCreate(&coder);
if (err)
goto failure;
// Fill in and DER-encode the PublicKeyAndChallenge:
SignedPublicKeyAndChallenge spkac;
memset(&spkac, 0, sizeof(spkac));
spkac.pkac.spki.algorithm.algorithm = CSSMOID_RSA;
spkac.pkac.spki.subjectPublicKey.Length =
CFDataGetLength(key_data) * 8; // interpreted as a _bit_ count
spkac.pkac.spki.subjectPublicKey.Data =
const_cast<uint8_t*>(CFDataGetBytePtr(key_data));
spkac.pkac.challenge_string.Length = challenge_.length();
spkac.pkac.challenge_string.Data =
reinterpret_cast<uint8_t*>(const_cast<char*>(challenge_.data()));
CSSM_DATA encoded;
err = SecAsn1EncodeItem(coder, &spkac.pkac,
kPublicKeyAndChallengeTemplate, &encoded);
if (err)
goto failure;
// Compute a signature of the result:
err = SignData(encoded, private_key, &signature);
if (err)
goto failure;
spkac.signature.Data = signature.Data;
spkac.signature.Length = signature.Length * 8; // a _bit_ count
spkac.signature_algorithm.algorithm = CSSMOID_MD5WithRSA;
// TODO(snej): MD5 is weak. Can we use SHA1 instead?
// See <https://bugzilla.mozilla.org/show_bug.cgi?id=549460>
// DER-encode the entire SignedPublicKeyAndChallenge:
err = SecAsn1EncodeItem(coder, &spkac,
kSignedPublicKeyAndChallengeTemplate, &encoded);
if (err)
goto failure;
// Base64 encode the result.
std::string input(reinterpret_cast<char*>(encoded.Data), encoded.Length);
base::Base64Encode(input, &result);
}
failure:
if (err) {
LOG(ERROR) << "SSL Keygen failed! OSStatus = " << err;
} else {
LOG(INFO) << "SSL Keygen succeeded! Output is: " << result;
}
// Remove keys from keychain if asked to during unit testing:
if (!stores_key_) {
if (public_key)
SecKeychainItemDelete(reinterpret_cast<SecKeychainItemRef>(public_key));
if (private_key)
SecKeychainItemDelete(reinterpret_cast<SecKeychainItemRef>(private_key));
}
// Clean up:
free(signature.Data);
if (coder)
SecAsn1CoderRelease(coder);
if (public_key)
CFRelease(public_key);
if (private_key)
CFRelease(private_key);
return result;
}
static OSStatus CreateRSAKeyPair(int size_in_bits,
SecKeyRef* out_pub_key,
SecKeyRef* out_priv_key) {
OSStatus err;
SecKeychainRef keychain;
err = SecKeychainCopyDefault(&keychain);
if (err)
return err;
scoped_cftyperef<SecKeychainRef> scoped_keychain(keychain);
return SecKeyCreatePair(
keychain,
CSSM_ALGID_RSA,
size_in_bits,
0LL,
// public key usage and attributes:
CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_VERIFY | CSSM_KEYUSE_WRAP,
CSSM_KEYATTR_EXTRACTABLE | CSSM_KEYATTR_PERMANENT,
// private key usage and attributes:
CSSM_KEYUSE_DECRYPT | CSSM_KEYUSE_SIGN | CSSM_KEYUSE_UNWRAP,
CSSM_KEYATTR_EXTRACTABLE | CSSM_KEYATTR_PERMANENT |
CSSM_KEYATTR_SENSITIVE,
NULL,
out_pub_key, out_priv_key);
}
static OSStatus CreateSignatureContext(SecKeyRef key,
CSSM_ALGORITHMS algorithm,
CSSM_CC_HANDLE* out_cc_handle) {
OSStatus err;
const CSSM_ACCESS_CREDENTIALS* credentials = NULL;
err = SecKeyGetCredentials(key,
CSSM_ACL_AUTHORIZATION_SIGN,
kSecCredentialTypeDefault,
&credentials);
if (err)
return err;
CSSM_CSP_HANDLE csp_handle = 0;
err = SecKeyGetCSPHandle(key, &csp_handle);
if (err)
return err;
const CSSM_KEY* cssm_key = NULL;
err = SecKeyGetCSSMKey(key, &cssm_key);
if (err)
return err;
return CSSM_CSP_CreateSignatureContext(csp_handle,
algorithm,
credentials,
cssm_key,
out_cc_handle);
}
static OSStatus SignData(CSSM_DATA data,
SecKeyRef private_key,
CSSM_DATA* signature) {
CSSM_CC_HANDLE cc_handle;
OSStatus err = CreateSignatureContext(private_key,
CSSM_ALGID_MD5WithRSA,
&cc_handle);
if (err)
return err;
err = CSSM_SignData(cc_handle, &data, 1, CSSM_ALGID_NONE, signature);
CSSM_DeleteContext(cc_handle);
return err;
}
} // namespace net
<commit_msg>Mac: Generate valid <keygen> data if challenge string is empty This works around an apparent bug in Apple's ASN.1 encoder. BUG=41679 TEST=Manual testing with comodo.com or a local test site<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/keygen_handler.h"
#include <Security/SecAsn1Coder.h>
#include <Security/SecAsn1Templates.h>
#include <Security/Security.h>
#include "base/base64.h"
#include "base/logging.h"
#include "base/scoped_cftyperef.h"
// These are in Security.framework but not declared in a public header.
extern const SecAsn1Template kSecAsn1AlgorithmIDTemplate[];
extern const SecAsn1Template kSecAsn1SubjectPublicKeyInfoTemplate[];
namespace net {
// Declarations of Netscape keygen cert structures for ASN.1 encoding:
struct PublicKeyAndChallenge {
CSSM_X509_SUBJECT_PUBLIC_KEY_INFO spki;
CSSM_DATA challenge_string;
};
// This is a copy of the built-in kSecAsn1IA5StringTemplate, but without the
// 'streamable' flag, which was causing bogus data to be written.
const SecAsn1Template kIA5StringTemplate[] = {
{ SEC_ASN1_IA5_STRING, 0, NULL, sizeof(CSSM_DATA) }
};
static const SecAsn1Template kPublicKeyAndChallengeTemplate[] = {
{
SEC_ASN1_SEQUENCE,
0,
NULL,
sizeof(PublicKeyAndChallenge)
},
{
SEC_ASN1_INLINE,
offsetof(PublicKeyAndChallenge, spki),
kSecAsn1SubjectPublicKeyInfoTemplate
},
{
SEC_ASN1_INLINE,
offsetof(PublicKeyAndChallenge, challenge_string),
kIA5StringTemplate
},
{
0
}
};
struct SignedPublicKeyAndChallenge {
PublicKeyAndChallenge pkac;
CSSM_X509_ALGORITHM_IDENTIFIER signature_algorithm;
CSSM_DATA signature;
};
static const SecAsn1Template kSignedPublicKeyAndChallengeTemplate[] = {
{
SEC_ASN1_SEQUENCE,
0,
NULL,
sizeof(SignedPublicKeyAndChallenge)
},
{
SEC_ASN1_INLINE,
offsetof(SignedPublicKeyAndChallenge, pkac),
kPublicKeyAndChallengeTemplate
},
{
SEC_ASN1_INLINE,
offsetof(SignedPublicKeyAndChallenge, signature_algorithm),
kSecAsn1AlgorithmIDTemplate
},
{
SEC_ASN1_BIT_STRING,
offsetof(SignedPublicKeyAndChallenge, signature)
},
{
0
}
};
static OSStatus CreateRSAKeyPair(int size_in_bits,
SecKeyRef* out_pub_key,
SecKeyRef* out_priv_key);
static OSStatus SignData(CSSM_DATA data,
SecKeyRef private_key,
CSSM_DATA* signature);
bool KeygenHandler::KeyLocation::Equals(
const KeygenHandler::KeyLocation& location) const {
return keychain_path == location.keychain_path;
}
std::string KeygenHandler::GenKeyAndSignChallenge() {
std::string result;
OSStatus err;
SecKeyRef public_key = NULL;
SecKeyRef private_key = NULL;
SecAsn1CoderRef coder = NULL;
CSSM_DATA signature = {0, NULL};
{
// Create the key-pair.
err = CreateRSAKeyPair(key_size_in_bits_, &public_key, &private_key);
if (err)
goto failure;
// Get the public key data (DER sequence of modulus, exponent).
CFDataRef key_data = NULL;
err = SecKeychainItemExport(public_key, kSecFormatBSAFE, 0, NULL,
&key_data);
if (err)
goto failure;
scoped_cftyperef<CFDataRef> scoped_key_data(key_data);
// Create an ASN.1 encoder.
err = SecAsn1CoderCreate(&coder);
if (err)
goto failure;
// Fill in and DER-encode the PublicKeyAndChallenge:
SignedPublicKeyAndChallenge spkac;
memset(&spkac, 0, sizeof(spkac));
spkac.pkac.spki.algorithm.algorithm = CSSMOID_RSA;
spkac.pkac.spki.subjectPublicKey.Length =
CFDataGetLength(key_data) * 8; // interpreted as a _bit_ count
spkac.pkac.spki.subjectPublicKey.Data =
const_cast<uint8_t*>(CFDataGetBytePtr(key_data));
spkac.pkac.challenge_string.Length = challenge_.length();
spkac.pkac.challenge_string.Data =
reinterpret_cast<uint8_t*>(const_cast<char*>(challenge_.data()));
CSSM_DATA encoded;
err = SecAsn1EncodeItem(coder, &spkac.pkac,
kPublicKeyAndChallengeTemplate, &encoded);
if (err)
goto failure;
// Compute a signature of the result:
err = SignData(encoded, private_key, &signature);
if (err)
goto failure;
spkac.signature.Data = signature.Data;
spkac.signature.Length = signature.Length * 8; // a _bit_ count
spkac.signature_algorithm.algorithm = CSSMOID_MD5WithRSA;
// TODO(snej): MD5 is weak. Can we use SHA1 instead?
// See <https://bugzilla.mozilla.org/show_bug.cgi?id=549460>
// DER-encode the entire SignedPublicKeyAndChallenge:
err = SecAsn1EncodeItem(coder, &spkac,
kSignedPublicKeyAndChallengeTemplate, &encoded);
if (err)
goto failure;
// Base64 encode the result.
std::string input(reinterpret_cast<char*>(encoded.Data), encoded.Length);
base::Base64Encode(input, &result);
}
failure:
if (err) {
LOG(ERROR) << "SSL Keygen failed! OSStatus = " << err;
} else {
LOG(INFO) << "SSL Keygen succeeded! Output is: " << result;
}
// Remove keys from keychain if asked to during unit testing:
if (!stores_key_) {
if (public_key)
SecKeychainItemDelete(reinterpret_cast<SecKeychainItemRef>(public_key));
if (private_key)
SecKeychainItemDelete(reinterpret_cast<SecKeychainItemRef>(private_key));
}
// Clean up:
free(signature.Data);
if (coder)
SecAsn1CoderRelease(coder);
if (public_key)
CFRelease(public_key);
if (private_key)
CFRelease(private_key);
return result;
}
static OSStatus CreateRSAKeyPair(int size_in_bits,
SecKeyRef* out_pub_key,
SecKeyRef* out_priv_key) {
OSStatus err;
SecKeychainRef keychain;
err = SecKeychainCopyDefault(&keychain);
if (err)
return err;
scoped_cftyperef<SecKeychainRef> scoped_keychain(keychain);
return SecKeyCreatePair(
keychain,
CSSM_ALGID_RSA,
size_in_bits,
0LL,
// public key usage and attributes:
CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_VERIFY | CSSM_KEYUSE_WRAP,
CSSM_KEYATTR_EXTRACTABLE | CSSM_KEYATTR_PERMANENT,
// private key usage and attributes:
CSSM_KEYUSE_DECRYPT | CSSM_KEYUSE_SIGN | CSSM_KEYUSE_UNWRAP,
CSSM_KEYATTR_EXTRACTABLE | CSSM_KEYATTR_PERMANENT |
CSSM_KEYATTR_SENSITIVE,
NULL,
out_pub_key, out_priv_key);
}
static OSStatus CreateSignatureContext(SecKeyRef key,
CSSM_ALGORITHMS algorithm,
CSSM_CC_HANDLE* out_cc_handle) {
OSStatus err;
const CSSM_ACCESS_CREDENTIALS* credentials = NULL;
err = SecKeyGetCredentials(key,
CSSM_ACL_AUTHORIZATION_SIGN,
kSecCredentialTypeDefault,
&credentials);
if (err)
return err;
CSSM_CSP_HANDLE csp_handle = 0;
err = SecKeyGetCSPHandle(key, &csp_handle);
if (err)
return err;
const CSSM_KEY* cssm_key = NULL;
err = SecKeyGetCSSMKey(key, &cssm_key);
if (err)
return err;
return CSSM_CSP_CreateSignatureContext(csp_handle,
algorithm,
credentials,
cssm_key,
out_cc_handle);
}
static OSStatus SignData(CSSM_DATA data,
SecKeyRef private_key,
CSSM_DATA* signature) {
CSSM_CC_HANDLE cc_handle;
OSStatus err = CreateSignatureContext(private_key,
CSSM_ALGID_MD5WithRSA,
&cc_handle);
if (err)
return err;
err = CSSM_SignData(cc_handle, &data, 1, CSSM_ALGID_NONE, signature);
CSSM_DeleteContext(cc_handle);
return err;
}
} // namespace net
<|endoftext|>
|
<commit_before><commit_msg>Fix clang warning in UDPSocketTest.<commit_after><|endoftext|>
|
<commit_before>#include "xchainer/backprop_mode.h"
#include <cstddef>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include <nonstd/optional.hpp>
#include "xchainer/context.h"
#include "xchainer/error.h"
#include "xchainer/graph.h"
namespace xchainer {
namespace {
void ExpectLastBackpropModeEqual(Context& context, const nonstd::optional<GraphId>& graph_id, bool backprop) {
const internal::BackpropMode& actual = internal::GetBackpropModeStack()->back();
EXPECT_EQ(&context, &actual.context());
EXPECT_EQ(graph_id, actual.graph_id());
EXPECT_EQ(backprop, actual.backprop());
}
TEST(BackpropModeScopeTest, BackpropModeScopeOneContext) {
Context context1{};
ContextScope context_scope1{context1};
EXPECT_EQ(nullptr, internal::GetBackpropModeStack());
{
NoBackpropModeScope backprop_mode_scope1{};
EXPECT_EQ(size_t{1}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), nonstd::nullopt, false);
{
ForceBackpropModeScope backprop_mode_scope2{"default"};
EXPECT_EQ(size_t{2}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, true);
{
NoBackpropModeScope backprop_mode_scope3{"default"};
EXPECT_EQ(size_t{3}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, false);
}
EXPECT_EQ(size_t{2}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, true);
}
EXPECT_EQ(size_t{1}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), nonstd::nullopt, false);
}
EXPECT_EQ(nullptr, internal::GetBackpropModeStack());
}
TEST(BackpropModeScopeTest, BackpropModeScopeMultipleContexts) {
Context context1{};
ContextScope context_scope1{context1};
EXPECT_EQ(nullptr, internal::GetBackpropModeStack());
{
NoBackpropModeScope backprop_mode_scope1;
EXPECT_EQ(size_t{1}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), nonstd::nullopt, false);
{
Context context2{};
ContextScope context_scope2{context2};
EXPECT_EQ(size_t{1}, internal::GetBackpropModeStack()->size());
NoBackpropModeScope backprop_mode_scope1{"default"};
// New context stack, and a stack for the context should be created.
EXPECT_EQ(size_t{2}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, false);
{
ForceBackpropModeScope backprop_mode_scope2{"default"};
EXPECT_EQ(size_t{3}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, true);
}
EXPECT_EQ(size_t{2}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, false);
}
EXPECT_EQ(size_t{1}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), nonstd::nullopt, false);
}
EXPECT_EQ(nullptr, internal::GetBackpropModeStack());
}
// It is possible to use in flat scope because, in C++ spec, dtors are called in reverse order of ctors.
TEST(BackpropModeScopeTest, BackpropModeScopeFlatScope) {
Context context1{};
ContextScope context_scope1{context1};
EXPECT_EQ(nullptr, internal::GetBackpropModeStack());
{
NoBackpropModeScope backprop_mode_scope1{};
ExpectLastBackpropModeEqual(GetDefaultContext(), nonstd::nullopt, false);
ForceBackpropModeScope backprop_mode_scope2{"default"};
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, true);
}
EXPECT_EQ(nullptr, internal::GetBackpropModeStack());
}
// TODO(niboshi): Write a test where the outermost scope is ForceBackpropMode.
TEST(BackpropModeScopeTest, BackpropModeWithoutContext) {
EXPECT_THROW({ NoBackpropModeScope{}; }, ContextError);
EXPECT_THROW({ ForceBackpropModeScope{}; }, ContextError);
}
} // namespace
} // namespace xchainer
<commit_msg>Add {}<commit_after>#include "xchainer/backprop_mode.h"
#include <cstddef>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include <nonstd/optional.hpp>
#include "xchainer/context.h"
#include "xchainer/error.h"
#include "xchainer/graph.h"
namespace xchainer {
namespace {
void ExpectLastBackpropModeEqual(Context& context, const nonstd::optional<GraphId>& graph_id, bool backprop) {
const internal::BackpropMode& actual = internal::GetBackpropModeStack()->back();
EXPECT_EQ(&context, &actual.context());
EXPECT_EQ(graph_id, actual.graph_id());
EXPECT_EQ(backprop, actual.backprop());
}
TEST(BackpropModeScopeTest, BackpropModeScopeOneContext) {
Context context1{};
ContextScope context_scope1{context1};
EXPECT_EQ(nullptr, internal::GetBackpropModeStack());
{
NoBackpropModeScope backprop_mode_scope1{};
EXPECT_EQ(size_t{1}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), nonstd::nullopt, false);
{
ForceBackpropModeScope backprop_mode_scope2{"default"};
EXPECT_EQ(size_t{2}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, true);
{
NoBackpropModeScope backprop_mode_scope3{"default"};
EXPECT_EQ(size_t{3}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, false);
}
EXPECT_EQ(size_t{2}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, true);
}
EXPECT_EQ(size_t{1}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), nonstd::nullopt, false);
}
EXPECT_EQ(nullptr, internal::GetBackpropModeStack());
}
TEST(BackpropModeScopeTest, BackpropModeScopeMultipleContexts) {
Context context1{};
ContextScope context_scope1{context1};
EXPECT_EQ(nullptr, internal::GetBackpropModeStack());
{
NoBackpropModeScope backprop_mode_scope1{};
EXPECT_EQ(size_t{1}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), nonstd::nullopt, false);
{
Context context2{};
ContextScope context_scope2{context2};
EXPECT_EQ(size_t{1}, internal::GetBackpropModeStack()->size());
NoBackpropModeScope backprop_mode_scope1{"default"};
// New context stack, and a stack for the context should be created.
EXPECT_EQ(size_t{2}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, false);
{
ForceBackpropModeScope backprop_mode_scope2{"default"};
EXPECT_EQ(size_t{3}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, true);
}
EXPECT_EQ(size_t{2}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, false);
}
EXPECT_EQ(size_t{1}, internal::GetBackpropModeStack()->size());
ExpectLastBackpropModeEqual(GetDefaultContext(), nonstd::nullopt, false);
}
EXPECT_EQ(nullptr, internal::GetBackpropModeStack());
}
// It is possible to use in flat scope because, in C++ spec, dtors are called in reverse order of ctors.
TEST(BackpropModeScopeTest, BackpropModeScopeFlatScope) {
Context context1{};
ContextScope context_scope1{context1};
EXPECT_EQ(nullptr, internal::GetBackpropModeStack());
{
NoBackpropModeScope backprop_mode_scope1{};
ExpectLastBackpropModeEqual(GetDefaultContext(), nonstd::nullopt, false);
ForceBackpropModeScope backprop_mode_scope2{"default"};
ExpectLastBackpropModeEqual(GetDefaultContext(), {"default"}, true);
}
EXPECT_EQ(nullptr, internal::GetBackpropModeStack());
}
// TODO(niboshi): Write a test where the outermost scope is ForceBackpropMode.
TEST(BackpropModeScopeTest, BackpropModeWithoutContext) {
EXPECT_THROW({ NoBackpropModeScope{}; }, ContextError);
EXPECT_THROW({ ForceBackpropModeScope{}; }, ContextError);
}
} // namespace
} // namespace xchainer
<|endoftext|>
|
<commit_before>#include "process.h"
#include "timing.h"
#include "database.h"
#include "shop.h"
#include "parse.h"
#include "faction.h"
#include "extern.h"
#include "toggle.h"
#include "guild.h"
#include "being.h"
#include <sys/shm.h>
#include <sys/ipc.h>
///////////
// procFactoryProduction
procFactoryProduction::procFactoryProduction(const int &p)
{
trigger_pulse=p;
name="procFactoryProduction";
}
void procFactoryProduction::run(const TPulse &) const
{
TDatabase db(DB_SNEEZY);
db.query("select distinct shop_nr from factoryproducing");
while(db.fetchRow()){
factoryProduction(convertTo<int>(db["shop_nr"]));
}
}
// procSaveFactions
procSaveFactions::procSaveFactions(const int &p)
{
trigger_pulse=p;
name="procSaveFactions";
}
void procSaveFactions::run(const TPulse &) const
{
save_factions();
}
// procSaveNewFactions
procSaveNewFactions::procSaveNewFactions(const int &p)
{
trigger_pulse=p;
name="procSaveNewFactions";
}
void procSaveNewFactions::run(const TPulse &) const
{
save_guilds();
}
// procDoComponents
procDoComponents::procDoComponents(const int &p)
{
trigger_pulse=p;
name="procDoComponents";
}
void procDoComponents::run(const TPulse &) const
{
do_components(-1);
}
// procPerformViolence
procPerformViolence::procPerformViolence(const int &p)
{
trigger_pulse=p;
name="procPerformViolence";
}
void procPerformViolence::run(const TPulse &pl) const
{
perform_violence(pl.pulse);
}
///////
bool TBaseProcess::should_run(int p) const
{
if(!(p % trigger_pulse))
return true;
else
return false;
}
void TScheduler::add(TProcess *p)
{
procs.push_back(p);
}
void TScheduler::add(TObjProcess *p)
{
obj_procs.push_back(p);
}
void TScheduler::add(TCharProcess *p)
{
char_procs.push_back(p);
}
TProcTop::TProcTop(){
if((shmid=shmget(gamePort, shm_size, IPC_CREAT | 0666)) < 0){
vlogf(LOG_BUG, "failed to get shared memory segment in TScheduler()");
} else if((shm = (char *)shmat(shmid, NULL, 0)) == (char *) -1){
vlogf(LOG_BUG, "failed to attach shared memory segment in TScheduler()");
}
}
void TProcTop::clear(){
memset(shm, 0, shm_size);
shm_ptr=shm;
added.clear();
}
void TProcTop::add(const sstring &s){
if(added.find(s)==added.end()){
strcpy(shm_ptr, s.c_str());
shm_ptr+=s.length()+1;
added[s]=true;
}
}
TScheduler::TScheduler(){
pulse.init(0);
placeholder=read_object(42, VIRTUAL);
// don't think we can recover from this
mud_assert(placeholder!=NULL, "couldn't load placeholder object");
*(real_roomp(0)) += *placeholder;
objIter=find(object_list.begin(), object_list.end(), placeholder);
tmp_ch=NULL;
}
void TScheduler::runObj(int pulseNum)
{
int count;
TObj *obj;
TTiming timer;
// we want to go through 1/12th of the object list every pulse
// obviously the object count will change, so this is approximate.
count=(int)((float)objCount/11.5);
if(toggleInfo[TOG_GAMELOOP]->toggle){
for(std::vector<TObjProcess *>::iterator iter=obj_procs.begin();
iter!=obj_procs.end();++iter)
(*iter)->timing=0;
}
while(count--){
// remove placeholder from object list and increment iterator
object_list.erase(objIter++);
// set object to be processed
obj=(*objIter);
// move to front of list if we reach the end
// otherwise just stick the placeholder in
if(++objIter == object_list.end()){
object_list.push_front(placeholder);
objIter=object_list.begin();
} else {
object_list.insert(objIter, placeholder);
--objIter;
}
for(std::vector<TObjProcess *>::iterator iter=obj_procs.begin();
iter!=obj_procs.end();++iter){
if((*iter)->should_run(pulse.pulse)){
if(toggleInfo[TOG_GAMELOOP]->toggle)
timer.start();
top.add((*iter)->name);
if((*iter)->run(pulse, obj)){
delete obj;
if(toggleInfo[TOG_GAMELOOP]->toggle)
(*iter)->timing+=timer.getElapsed();
break;
}
if(toggleInfo[TOG_GAMELOOP]->toggle)
(*iter)->timing+=timer.getElapsed();
}
}
}
if(toggleInfo[TOG_GAMELOOP]->toggle){
for(std::vector<TObjProcess *>::iterator iter=obj_procs.begin();
iter!=obj_procs.end();++iter){
if((*iter)->should_run(pulse.pulse)){
vlogf(LOG_MISC, format("%i %i) %s: %i") %
(pulseNum % 2400) % (pulseNum%12) % (*iter)->name %
(int)((*iter)->timing*1000000));
(*iter)->timing=0;
}
}
}
}
void TScheduler::runChar(int pulseNum)
{
TBeing *temp;
int count;
TTiming timer;
// we've already finished going through the character list, so start over
if(!tmp_ch)
tmp_ch=character_list;
count=max((int)((float)mobCount/11.5), 1);
if(toggleInfo[TOG_GAMELOOP]->toggle)
for(std::vector<TCharProcess *>::iterator iter=char_procs.begin();
iter!=char_procs.end();++iter)
(*iter)->timing=0;
for (; tmp_ch; tmp_ch = temp) {
temp = tmp_ch->next; // just for safety
if(!count--)
break;
if (tmp_ch->getPosition() == POSITION_DEAD) {
vlogf(LOG_BUG, format("Error: dead creature (%s at %d) in character_list, removing.") %
tmp_ch->getName() % tmp_ch->in_room);
delete tmp_ch;
continue;
}
if ((tmp_ch->getPosition() < POSITION_STUNNED) &&
(tmp_ch->getHit() > 0)) {
vlogf(LOG_BUG, format("Error: creature (%s) with hit > 0 found with position < stunned") %
tmp_ch->getName());
vlogf(LOG_BUG, "Setting player to POSITION_STANDING");
tmp_ch->setPosition(POSITION_STANDING);
}
for(std::vector<TCharProcess *>::iterator iter=char_procs.begin();
iter!=char_procs.end();++iter){
if((*iter)->should_run(pulse.pulse)){
if(toggleInfo[TOG_GAMELOOP]->toggle)
timer.start();
top.add((*iter)->name);
if((*iter)->run(pulse, tmp_ch)){
delete tmp_ch;
if(toggleInfo[TOG_GAMELOOP]->toggle)
(*iter)->timing+=timer.getElapsed();
break;
}
if(toggleInfo[TOG_GAMELOOP]->toggle)
(*iter)->timing+=timer.getElapsed();
}
}
temp = tmp_ch->next; // just for safety
}
if(toggleInfo[TOG_GAMELOOP]->toggle){
for(std::vector<TCharProcess *>::iterator iter=char_procs.begin();
iter!=char_procs.end();++iter){
if((*iter)->should_run(pulse.pulse)){
vlogf(LOG_MISC, format("%i %i) %s: %i") %
(pulseNum % 2400) % (pulseNum%12) % (*iter)->name %
(int)((*iter)->timing*1000000));
}
}
}
}
void TScheduler::run(int pulseNum)
{
TTiming timer;
pulse.init(pulseNum);
top.clear();
if(toggleInfo[TOG_GAMELOOP]->toggle)
vlogf(LOG_MISC, format("%i %i) pulses: %s") %
pulse.pulse % (pulse.pulse%12) % pulse.showPulses());
// run general processes
for(std::vector<TProcess *>::iterator iter=procs.begin();
iter!=procs.end();++iter){
if((*iter)->should_run(pulse.pulse)){
if(toggleInfo[TOG_GAMELOOP]->toggle)
timer.start();
top.add((*iter)->name);
(*iter)->run(pulse);
if(toggleInfo[TOG_GAMELOOP]->toggle){
timer.end();
vlogf(LOG_MISC, format("%i %i) %s: %i") %
(pulseNum % 2400) % (pulseNum%12) % (*iter)->name %
(int)(timer.getElapsed()*1000000));
}
}
}
pulse.init12(pulseNum);
if(toggleInfo[TOG_GAMELOOP]->toggle)
vlogf(LOG_MISC, format("%i %i) distributed pulses: %s") %
pulse.pulse % (pulse.pulse%12) % pulse.showPulses());
// run object processes
runObj(pulseNum);
// run character processes
runChar(pulseNum);
pulse.init(pulseNum);
}
procSeedRandom::procSeedRandom(const int &p)
{
trigger_pulse=p;
name="procSeedRandom";
}
void procSeedRandom::run(const TPulse &) const
{
srand(time(0));
vlogf(LOG_SILENT, "procSeedRandom: Generated new seed.");
}
<commit_msg>added some crash proofing to TProcTop<commit_after>#include "process.h"
#include "timing.h"
#include "database.h"
#include "shop.h"
#include "parse.h"
#include "faction.h"
#include "extern.h"
#include "toggle.h"
#include "guild.h"
#include "being.h"
#include <sys/shm.h>
#include <sys/ipc.h>
///////////
// procFactoryProduction
procFactoryProduction::procFactoryProduction(const int &p)
{
trigger_pulse=p;
name="procFactoryProduction";
}
void procFactoryProduction::run(const TPulse &) const
{
TDatabase db(DB_SNEEZY);
db.query("select distinct shop_nr from factoryproducing");
while(db.fetchRow()){
factoryProduction(convertTo<int>(db["shop_nr"]));
}
}
// procSaveFactions
procSaveFactions::procSaveFactions(const int &p)
{
trigger_pulse=p;
name="procSaveFactions";
}
void procSaveFactions::run(const TPulse &) const
{
save_factions();
}
// procSaveNewFactions
procSaveNewFactions::procSaveNewFactions(const int &p)
{
trigger_pulse=p;
name="procSaveNewFactions";
}
void procSaveNewFactions::run(const TPulse &) const
{
save_guilds();
}
// procDoComponents
procDoComponents::procDoComponents(const int &p)
{
trigger_pulse=p;
name="procDoComponents";
}
void procDoComponents::run(const TPulse &) const
{
do_components(-1);
}
// procPerformViolence
procPerformViolence::procPerformViolence(const int &p)
{
trigger_pulse=p;
name="procPerformViolence";
}
void procPerformViolence::run(const TPulse &pl) const
{
perform_violence(pl.pulse);
}
///////
bool TBaseProcess::should_run(int p) const
{
if(!(p % trigger_pulse))
return true;
else
return false;
}
void TScheduler::add(TProcess *p)
{
procs.push_back(p);
}
void TScheduler::add(TObjProcess *p)
{
obj_procs.push_back(p);
}
void TScheduler::add(TCharProcess *p)
{
char_procs.push_back(p);
}
TProcTop::TProcTop(){
if((shmid=shmget(gamePort, shm_size, IPC_CREAT | 0666)) < 0){
vlogf(LOG_BUG, "failed to get shared memory segment in TScheduler()");
shm=NULL;
} else if((shm = (char *)shmat(shmid, NULL, 0)) == (char *) -1){
vlogf(LOG_BUG, "failed to attach shared memory segment in TScheduler()");
shm=NULL;
}
}
void TProcTop::clear(){
if(shm){
memset(shm, 0, shm_size);
shm_ptr=shm;
added.clear();
}
}
void TProcTop::add(const sstring &s){
if(shm){
if(added.find(s)==added.end()){
strcpy(shm_ptr, s.c_str());
shm_ptr+=s.length()+1;
added[s]=true;
}
}
}
TScheduler::TScheduler(){
pulse.init(0);
placeholder=read_object(42, VIRTUAL);
// don't think we can recover from this
mud_assert(placeholder!=NULL, "couldn't load placeholder object");
*(real_roomp(0)) += *placeholder;
objIter=find(object_list.begin(), object_list.end(), placeholder);
tmp_ch=NULL;
}
void TScheduler::runObj(int pulseNum)
{
int count;
TObj *obj;
TTiming timer;
// we want to go through 1/12th of the object list every pulse
// obviously the object count will change, so this is approximate.
count=(int)((float)objCount/11.5);
if(toggleInfo[TOG_GAMELOOP]->toggle){
for(std::vector<TObjProcess *>::iterator iter=obj_procs.begin();
iter!=obj_procs.end();++iter)
(*iter)->timing=0;
}
while(count--){
// remove placeholder from object list and increment iterator
object_list.erase(objIter++);
// set object to be processed
obj=(*objIter);
// move to front of list if we reach the end
// otherwise just stick the placeholder in
if(++objIter == object_list.end()){
object_list.push_front(placeholder);
objIter=object_list.begin();
} else {
object_list.insert(objIter, placeholder);
--objIter;
}
for(std::vector<TObjProcess *>::iterator iter=obj_procs.begin();
iter!=obj_procs.end();++iter){
if((*iter)->should_run(pulse.pulse)){
if(toggleInfo[TOG_GAMELOOP]->toggle)
timer.start();
top.add((*iter)->name);
if((*iter)->run(pulse, obj)){
delete obj;
if(toggleInfo[TOG_GAMELOOP]->toggle)
(*iter)->timing+=timer.getElapsed();
break;
}
if(toggleInfo[TOG_GAMELOOP]->toggle)
(*iter)->timing+=timer.getElapsed();
}
}
}
if(toggleInfo[TOG_GAMELOOP]->toggle){
for(std::vector<TObjProcess *>::iterator iter=obj_procs.begin();
iter!=obj_procs.end();++iter){
if((*iter)->should_run(pulse.pulse)){
vlogf(LOG_MISC, format("%i %i) %s: %i") %
(pulseNum % 2400) % (pulseNum%12) % (*iter)->name %
(int)((*iter)->timing*1000000));
(*iter)->timing=0;
}
}
}
}
void TScheduler::runChar(int pulseNum)
{
TBeing *temp;
int count;
TTiming timer;
// we've already finished going through the character list, so start over
if(!tmp_ch)
tmp_ch=character_list;
count=max((int)((float)mobCount/11.5), 1);
if(toggleInfo[TOG_GAMELOOP]->toggle)
for(std::vector<TCharProcess *>::iterator iter=char_procs.begin();
iter!=char_procs.end();++iter)
(*iter)->timing=0;
for (; tmp_ch; tmp_ch = temp) {
temp = tmp_ch->next; // just for safety
if(!count--)
break;
if (tmp_ch->getPosition() == POSITION_DEAD) {
vlogf(LOG_BUG, format("Error: dead creature (%s at %d) in character_list, removing.") %
tmp_ch->getName() % tmp_ch->in_room);
delete tmp_ch;
continue;
}
if ((tmp_ch->getPosition() < POSITION_STUNNED) &&
(tmp_ch->getHit() > 0)) {
vlogf(LOG_BUG, format("Error: creature (%s) with hit > 0 found with position < stunned") %
tmp_ch->getName());
vlogf(LOG_BUG, "Setting player to POSITION_STANDING");
tmp_ch->setPosition(POSITION_STANDING);
}
for(std::vector<TCharProcess *>::iterator iter=char_procs.begin();
iter!=char_procs.end();++iter){
if((*iter)->should_run(pulse.pulse)){
if(toggleInfo[TOG_GAMELOOP]->toggle)
timer.start();
top.add((*iter)->name);
if((*iter)->run(pulse, tmp_ch)){
delete tmp_ch;
if(toggleInfo[TOG_GAMELOOP]->toggle)
(*iter)->timing+=timer.getElapsed();
break;
}
if(toggleInfo[TOG_GAMELOOP]->toggle)
(*iter)->timing+=timer.getElapsed();
}
}
temp = tmp_ch->next; // just for safety
}
if(toggleInfo[TOG_GAMELOOP]->toggle){
for(std::vector<TCharProcess *>::iterator iter=char_procs.begin();
iter!=char_procs.end();++iter){
if((*iter)->should_run(pulse.pulse)){
vlogf(LOG_MISC, format("%i %i) %s: %i") %
(pulseNum % 2400) % (pulseNum%12) % (*iter)->name %
(int)((*iter)->timing*1000000));
}
}
}
}
void TScheduler::run(int pulseNum)
{
TTiming timer;
pulse.init(pulseNum);
top.clear();
if(toggleInfo[TOG_GAMELOOP]->toggle)
vlogf(LOG_MISC, format("%i %i) pulses: %s") %
pulse.pulse % (pulse.pulse%12) % pulse.showPulses());
// run general processes
for(std::vector<TProcess *>::iterator iter=procs.begin();
iter!=procs.end();++iter){
if((*iter)->should_run(pulse.pulse)){
if(toggleInfo[TOG_GAMELOOP]->toggle)
timer.start();
top.add((*iter)->name);
(*iter)->run(pulse);
if(toggleInfo[TOG_GAMELOOP]->toggle){
timer.end();
vlogf(LOG_MISC, format("%i %i) %s: %i") %
(pulseNum % 2400) % (pulseNum%12) % (*iter)->name %
(int)(timer.getElapsed()*1000000));
}
}
}
pulse.init12(pulseNum);
if(toggleInfo[TOG_GAMELOOP]->toggle)
vlogf(LOG_MISC, format("%i %i) distributed pulses: %s") %
pulse.pulse % (pulse.pulse%12) % pulse.showPulses());
// run object processes
runObj(pulseNum);
// run character processes
runChar(pulseNum);
pulse.init(pulseNum);
}
procSeedRandom::procSeedRandom(const int &p)
{
trigger_pulse=p;
name="procSeedRandom";
}
void procSeedRandom::run(const TPulse &) const
{
srand(time(0));
vlogf(LOG_SILENT, "procSeedRandom: Generated new seed.");
}
<|endoftext|>
|
<commit_before>#ifndef DOMImplementation_HEADER_GUARD_
#define DOMImplementation_HEADER_GUARD_
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001-2002 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$
*/
#include <xercesc/dom/DOMImplementationLS.hpp>
class DOMDocument;
class DOMDocumentType;
/**
* This class provides a way to query the capabilities of an implementation
* of the DOM
*/
class CDOM_EXPORT DOMImplementation : public DOMImplementationLS
{
protected:
DOMImplementation() {}; // no plain constructor
DOMImplementation(const DOMImplementation &other) {}; // no copy construtor.
DOMImplementation & operator = (const DOMImplementation &other) {return *this;}; // No Assignment
public:
// Factory method for getting a DOMImplementation object.
// The DOM implementation retains ownership of the returned object.
// Application code should NOT delete it.
//
static DOMImplementation *getImplementation();
virtual ~DOMImplementation() {};
virtual bool hasFeature(const XMLCh *feature, const XMLCh *version) = 0;
// Create a new DocumentType.
// Initially the application owns the returned DocumentType object and is responsible
// for deleting it. If the DocumentType is subsequently associated with a Document,
// that document becomes the owner of the storage and will delete the document type
// when the document is deleted.
virtual DOMDocumentType *createDocumentType(const XMLCh *qualifiedName,
const XMLCh *publicId, const XMLCh *systemId) = 0;
virtual DOMDocument *createDocument(const XMLCh *namespaceURI,
const XMLCh *qualifiedName, DOMDocumentType *doctype) = 0;
// Non-standard extension. Create a completely empty document that has neither a root
// element or a doctype node.
//
virtual DOMDocument *createDocument() = 0;
};
#endif
<commit_msg>Update API documentation for DOMImplementation.<commit_after>#ifndef DOMImplementation_HEADER_GUARD_
#define DOMImplementation_HEADER_GUARD_
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001-2002 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$
*/
#include <xercesc/dom/DOMImplementationLS.hpp>
class DOMDocument;
class DOMDocumentType;
/**
* The <code>DOMImplementation</code> interface provides a number of methods
* for performing operations that are independent of any particular instance
* of the document object model.
*/
class CDOM_EXPORT DOMImplementation : public DOMImplementationLS
{
protected :
// -----------------------------------------------------------------------
// Hidden constructors
// -----------------------------------------------------------------------
/** @name Constructors */
//@{
DOMImplementation() {}; // no plain constructor
DOMImplementation(const DOMImplementation &other) {}; // no copy construtor.
DOMImplementation & operator = (const DOMImplementation &other) {return *this;}; // No Assignment
//@}
public:
// -----------------------------------------------------------------------
// All constructors are hidden, just the destructor is available
// -----------------------------------------------------------------------
/** @name Destructor */
//@{
/**
* Destructor
*
*/
virtual ~DOMImplementation() {};
//@}
// -----------------------------------------------------------------------
// DOMImplementation interface
// -----------------------------------------------------------------------
/** @name Virtual DOMImplementation interface */
//@{
/**
* Test if the DOM implementation implements a specific feature.
* @param feature The name of the feature to test (case-insensitive). The
* values used by DOM features are defined throughout the DOM Level 2
* specifications and listed in the section. The name must be an XML
* name. To avoid possible conflicts, as a convention, names referring
* to features defined outside the DOM specification should be made
* unique.
* @param version This is the version number of the feature to test. In
* Level 2, the string can be either "2.0" or "1.0". If the version is
* not specified, supporting any version of the feature causes the
* method to return <code>true</code>.
* @return <code>true</code> if the feature is implemented in the
* specified version, <code>false</code> otherwise.
*/
virtual bool hasFeature(const XMLCh *feature, const XMLCh *version) = 0;
/**
* Introduced in DOM Level 2
*
* Creates an empty <code>DocumentType</code> node. Entity declarations
* and notations are not made available. Entity reference expansions and
* default attribute additions do not occur. It is expected that a
* future version of the DOM will provide a way for populating a
* <code>DocumentType</code>.
* @param qualifiedName The qualified name of the document type to be
* created.
* @param publicId The external subset public identifier.
* @param systemId The external subset system identifier.
* @return A new <code>DocumentType</code> node with
* <code>Node.ownerDocument</code> set to <code>null</code>.
* @exception DOMException
* INVALID_CHARACTER_ERR: Raised if the specified qualified name
* contains an illegal character.
* <br>NAMESPACE_ERR: Raised if the <code>qualifiedName</code> is
* malformed.
* <br>NOT_SUPPORTED_ERR: May be raised by DOM implementations which do
* not support the <code>"XML"</code> feature, if they choose not to
* support this method. Other features introduced in the future, by
* the DOM WG or in extensions defined by other groups, may also
* demand support for this method; please consult the definition of
* the feature to see if it requires this method.
* @since DOM Level 2
*/
virtual DOMDocumentType *createDocumentType(const XMLCh *qualifiedName,
const XMLCh *publicId,
const XMLCh *systemId) = 0;
/**
* Introduced in DOM Level 2
*
* Creates a DOM Document object of the specified type with its document
* element.
* @param namespaceURI The namespace URI of the document element to
* create.
* @param qualifiedName The qualified name of the document element to be
* created.
* @param doctype The type of document to be created or <code>null</code>.
* When <code>doctype</code> is not <code>null</code>, its
* <code>Node.ownerDocument</code> attribute is set to the document
* being created.
* @return A new <code>Document</code> object.
* @exception DOMException
* INVALID_CHARACTER_ERR: Raised if the specified qualified name
* contains an illegal character.
* <br>NAMESPACE_ERR: Raised if the <code>qualifiedName</code> is
* malformed, if the <code>qualifiedName</code> has a prefix and the
* <code>namespaceURI</code> is <code>null</code>, or if the
* <code>qualifiedName</code> has a prefix that is "xml" and the
* <code>namespaceURI</code> is different from "
* http://www.w3.org/XML/1998/namespace" , or if the DOM
* implementation does not support the <code>"XML"</code> feature but
* a non-null namespace URI was provided, since namespaces were
* defined by XML.
* <br>WRONG_DOCUMENT_ERR: Raised if <code>doctype</code> has already
* been used with a different document or was created from a different
* implementation.
* <br>NOT_SUPPORTED_ERR: May be raised by DOM implementations which do
* not support the "XML" feature, if they choose not to support this
* method. Other features introduced in the future, by the DOM WG or
* in extensions defined by other groups, may also demand support for
* this method; please consult the definition of the feature to see if
* it requires this method.
* @since DOM Level 2
*/
virtual DOMDocument *createDocument(const XMLCh *namespaceURI,
const XMLCh *qualifiedName,
DOMDocumentType *doctype) = 0;
//@}
// -----------------------------------------------------------------------
// Non-standard extension
// -----------------------------------------------------------------------
/** @name Non-standard extension */
//@{
/**
* Non-standard extension
*
* Factory method for getting a DOMImplementation object.
* The DOM implementation retains ownership of the returned object.
* Application code should NOT delete it.
*/
static DOMImplementation *getImplementation();
/**
* Non-standard extension
*
* Create a completely empty document that has neither a root element or a doctype node.
*/
virtual DOMDocument *createDocument() = 0;
//@}
};
#endif
<|endoftext|>
|
<commit_before>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014 Taras Kushnir <kushnirTV@gmail.com>
*
* Xpiks is distributed under the GNU General Public License, version 3.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QStringList>
#include <QDirIterator>
#include <QDebug>
#include <QList>
#include "artitemsmodel.h"
#include "artiteminfo.h"
#include "../Helpers/indiceshelper.h"
namespace Models {
ArtItemsModel::~ArtItemsModel() {
qDeleteAll(m_ArtworkList);
m_ArtworkList.clear();
// being freed in gui
//delete m_ArtworksDirectories;
}
int ArtItemsModel::getModifiedArtworksCount()
{
int modifiedCount = 0;
foreach (ArtworkMetadata *metadata, m_ArtworkList) {
if (metadata->isModified()) {
modifiedCount++;
}
}
return modifiedCount;
}
void ArtItemsModel::updateAllProperties()
{
QList<QPair<int, int> > ranges;
ranges << qMakePair(0, m_ArtworkList.length() - 1);
QVector<int> roles;
roles << ArtworkDescriptionRole << KeywordsRole << IsModifiedRole << ArtworkAuthorRole << ArtworkTitleRole;
updateItemsAtIndices(ranges, roles);
}
void ArtItemsModel::removeArtworksDirectory(int index)
{
const QString &directory = m_ArtworksRepository->getDirectory(index);
QList<int> indicesToRemove;
QList<ArtworkMetadata*>::const_iterator it = m_ArtworkList.constBegin();
for (int i = 0; it < m_ArtworkList.constEnd(); ++it, ++i) {
if ((*it)->isInDirectory(directory)) {
indicesToRemove.append(i);
}
}
doRemoveItemsAtIndices(indicesToRemove);
emit selectedArtworksCountChanged();
emit modifiedArtworksCountChanged();
}
void ArtItemsModel::removeKeywordAt(int metadataIndex, int keywordIndex)
{
if (metadataIndex >= 0 && metadataIndex < m_ArtworkList.length()) {
ArtworkMetadata *metadata = m_ArtworkList.at(metadataIndex);
if (metadata->removeKeywordAt(keywordIndex)) {
QModelIndex index = this->index(metadataIndex);
emit dataChanged(index, index, QVector<int>() << KeywordsRole << IsModifiedRole << KeywordsCountRole);
}
}
}
void ArtItemsModel::removeLastKeyword(int metadataIndex)
{
if (metadataIndex >= 0 && metadataIndex < m_ArtworkList.length()) {
ArtworkMetadata *metadata = m_ArtworkList.at(metadataIndex);
if (metadata->removeLastKeyword()) {
QModelIndex index = this->index(metadataIndex);
emit dataChanged(index, index, QVector<int>() << KeywordsRole << IsModifiedRole << KeywordsCountRole);
}
}
}
void ArtItemsModel::appendKeyword(int metadataIndex, const QString &keyword)
{
if (metadataIndex >= 0 && metadataIndex < m_ArtworkList.length()) {
ArtworkMetadata *metadata = m_ArtworkList.at(metadataIndex);
if (metadata->appendKeyword(keyword)) {
QModelIndex index = this->index(metadataIndex);
emit dataChanged(index, index, QVector<int>() << KeywordsRole << IsModifiedRole << KeywordsCountRole);
}
}
}
void ArtItemsModel::setSelectedItemsSaved()
{
QList<int> selectedIndices;
getSelectedItemsIndices(selectedIndices);
foreach (int index, selectedIndices) {
m_ArtworkList[index]->unsetModified();
}
QList<QPair<int, int> > rangesToUpdate;
Helpers::indicesToRanges(selectedIndices, rangesToUpdate);
updateItemsAtIndices(rangesToUpdate, QVector<int>() << IsModifiedRole);
updateModifiedCount();
}
void ArtItemsModel::removeSelectedArtworks()
{
QList<int> indicesToRemove;
getSelectedItemsIndices(indicesToRemove);
doRemoveItemsAtIndices(indicesToRemove);
}
void ArtItemsModel::updateSelectedArtworks()
{
QList<int> selectedIndices;
getSelectedItemsIndices(selectedIndices);
QList<QPair<int, int> > rangesToUpdate;
Helpers::indicesToRanges(selectedIndices, rangesToUpdate);
QVector<int> roles;
roles << ArtworkDescriptionRole << KeywordsRole << IsModifiedRole << ArtworkAuthorRole << ArtworkTitleRole;
updateItemsAtIndices(rangesToUpdate, roles);
}
void ArtItemsModel::patchSelectedArtworks()
{
QList<ArtworkMetadata*> selectedArtworks;
int count = m_ArtworkList.length();
for (int i = 0; i < count; ++i) {
ArtworkMetadata *metadata = m_ArtworkList[i];
if (metadata->getIsSelected()) {
selectedArtworks.append(metadata);
}
}
// TODO: assert iptc provider is not null
// TODO: remove this two times copying
m_IptcProvider->setArtworks(selectedArtworks);
}
void ArtItemsModel::uploadSelectedArtworks()
{
QList<ArtworkMetadata*> selectedArtworks;
int count = m_ArtworkList.length();
for (int i = 0; i < count; ++i) {
ArtworkMetadata *metadata = m_ArtworkList[i];
if (metadata->getIsSelected()) {
selectedArtworks.append(metadata);
}
}
// TODO: assert uploader is not null
// TODO: remove this two times copying
m_ArtworkUploader->setArtworks(selectedArtworks);
}
bool ArtItemsModel::areSelectedArtworksSaved()
{
bool areModified = false;
foreach(ArtworkMetadata *metadata, m_ArtworkList) {
if (metadata->getIsSelected()) {
if (metadata->isModified()) {
areModified = true;
break;
}
}
}
return !areModified;
}
void ArtItemsModel::selectDirectory(int directoryIndex)
{
QList<int> directoryItems;
const QString directory = m_ArtworksRepository->getDirectory(directoryIndex);
int i = 0;
foreach (ArtworkMetadata *metadata, m_ArtworkList) {
if (metadata->isInDirectory(directory)) {
directoryItems.append(i);
metadata->setIsSelected(!metadata->getIsSelected());
}
i++;
}
QList<QPair<int, int> > rangesToUpdate;
Helpers::indicesToRanges(directoryItems, rangesToUpdate);
updateItemsAtIndices(rangesToUpdate, QVector<int>() << IsSelectedRole);
}
int ArtItemsModel::rowCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
return m_ArtworkList.count();
}
QVariant ArtItemsModel::data(const QModelIndex &index, int role) const {
if (index.row() < 0 || index.row() >= m_ArtworkList.count())
return QVariant();
ArtworkMetadata *metadata = m_ArtworkList.at(index.row());
switch (role) {
case ArtworkDescriptionRole:
return metadata->getDescription();
case ArtworkFilenameRole:
return metadata->getFilepath();
case ArtworkAuthorRole:
return metadata->getAuthor();
case ArtworkTitleRole:
return metadata->getTitle();
case KeywordsRole:
return metadata->getKeywords();
case KeywordsStringRole:
return metadata->getKeywordsString();
case IsModifiedRole:
return metadata->isModified();
case IsSelectedRole:
return metadata->getIsSelected();
case KeywordsCountRole:
return metadata->getKeywordsCount();
default:
return QVariant();
}
}
Qt::ItemFlags ArtItemsModel::flags(const QModelIndex &index) const
{
if (!index.isValid()) {
return Qt::ItemIsEnabled;
}
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
bool ArtItemsModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid()) {
return false;
}
ArtworkMetadata *metadata = m_ArtworkList.at(index.row());
int roleToUpdate = 0;
switch (role) {
case EditArtworkDescriptionRole:
metadata->setDescription(value.toString());
roleToUpdate = ArtworkDescriptionRole;
break;
case EditArtworkTitleRole:
metadata->setTitle(value.toString());
roleToUpdate = ArtworkTitleRole;
break;
case EditArtworkAuthorRole:
metadata->setAuthor(value.toString());
roleToUpdate = ArtworkAuthorRole;
break;
case EditIsSelectedRole:
metadata->setIsSelected(value.toBool());
roleToUpdate = IsSelectedRole;
break;
default:
return false;
}
emit dataChanged(index, index, QVector<int>() << IsModifiedRole << role << roleToUpdate);
return true;
}
void ArtItemsModel::addLocalArtworks(const QList<QUrl> &artworksPaths)
{
qDebug() << artworksPaths;
QStringList fileList;
foreach (const QUrl &url, artworksPaths) {
fileList.append(url.toLocalFile());
}
addFiles(fileList);
}
void ArtItemsModel::addLocalDirectory(const QUrl &directory)
{
qDebug() << directory;
addDirectory(directory.toLocalFile());
}
void ArtItemsModel::itemSelectedChanged(bool value)
{
int plus = value ? +1 : -1;
m_SelectedArtworksCount += plus;
emit selectedArtworksCountChanged();
}
void ArtItemsModel::addDirectory(const QString &directory)
{
QDir dir(directory);
dir.setFilter(QDir::NoDotAndDotDot | QDir::Files);
QStringList items = dir.entryList();
for (int i = 0; i < items.size(); ++i) {
items[i] = dir.filePath(items[i]);
}
if (items.count() > 0) {
addFiles(items);
}
}
void ArtItemsModel::addFiles(const QStringList &rawFilenames)
{
QStringList filenames = rawFilenames.filter(QRegExp("^.*[.]jpg$", Qt::CaseInsensitive));
const int count = filenames.count();
const int newFilesCount = m_ArtworksRepository->getNewFilesCount(filenames);
bool filesWereAccounted = m_ArtworksRepository->beginAccountingFiles(filenames);
if (newFilesCount > 0) {
beginInsertRows(QModelIndex(), rowCount(), rowCount() + newFilesCount - 1);
for (int i = 0; i < count; ++i) {
const QString &filename = filenames[i];
if (m_ArtworksRepository->accountFile(filename))
{
ArtworkMetadata *metadata = new ArtworkMetadata(filename);
QObject::connect(metadata, SIGNAL(modifiedChanged(bool)),
this, SLOT(itemModifiedChanged(bool)));
QObject::connect(metadata, SIGNAL(selectedChanged(bool)),
this, SLOT(itemSelectedChanged(bool)));
QObject::connect(metadata, SIGNAL(fileSelectedChanged(QString,bool)),
m_ArtworksRepository, SLOT(fileSelectedChanged(QString,bool)));
m_ArtworkList.append(metadata);
}
}
endInsertRows();
}
m_ArtworksRepository->endAccountingFiles(filesWereAccounted);
if (newFilesCount > 0) {
m_ArtworksRepository->updateCountsForExistingDirectories();
}
// set artworks for initial import
m_IptcProvider->setArtworks(m_ArtworkList);
}
void ArtItemsModel::setAllItemsSelected(bool selected)
{
qDebug() << "Setting all items selected (" << selected << ")";
int length = m_ArtworkList.length();
for (int i = 0; i < length; ++i) {
ArtworkMetadata *metadata = m_ArtworkList[i];
metadata->setIsSelected(selected);
}
if (length > 0) {
QModelIndex startIndex = index(0);
QModelIndex endIndex = index(length - 1);
emit dataChanged(startIndex, endIndex, QVector<int>() << IsSelectedRole);
}
}
void ArtItemsModel::doCombineSelectedImages(CombinedArtworksModel *combinedModel) const
{
QList<ArtItemInfo*> artworksList;
foreach (ArtworkMetadata *metadata, m_ArtworkList) {
if (metadata->getIsSelected()) {
ArtItemInfo *info = new ArtItemInfo(metadata);
artworksList.append(info);
}
}
combinedModel->initArtworks(artworksList);
combinedModel->recombineArtworks();
}
void ArtItemsModel::doCombineArtwork(int index, CombinedArtworksModel *combinedModel)
{
if (index >= 0 && index < m_ArtworkList.length()) {
QList<ArtItemInfo*> artworksList;
ArtworkMetadata *metadata = m_ArtworkList.at(index);
metadata->setIsSelected(true);
QModelIndex qmIndex = this->index(index);
emit dataChanged(qmIndex, qmIndex, QVector<int>() << IsSelectedRole);
ArtItemInfo *info = new ArtItemInfo(metadata);
artworksList.append(info);
combinedModel->initArtworks(artworksList);
combinedModel->recombineArtworks();
}
}
QHash<int, QByteArray> ArtItemsModel::roleNames() const {
QHash<int, QByteArray> roles;
roles[ArtworkDescriptionRole] = "description";
roles[EditArtworkDescriptionRole] = "editdescription";
roles[ArtworkAuthorRole] = "author";
roles[EditArtworkAuthorRole] = "editauthor";
roles[ArtworkTitleRole] = "title";
roles[EditArtworkTitleRole] = "edittitle";
roles[ArtworkFilenameRole] = "filename";
roles[KeywordsRole] = "keywords";
roles[KeywordsStringRole] = "keywordsstring";
roles[IsModifiedRole] = "ismodified";
roles[IsSelectedRole] = "isselected";
roles[EditIsSelectedRole] = "editisselected";
roles[KeywordsCountRole] = "keywordscount";
return roles;
}
void ArtItemsModel::removeInnerItem(int row)
{
// TODO: add assert for row
ArtworkMetadata *metadata = m_ArtworkList[row];
m_ArtworksRepository->removeFile(metadata->getFilepath());
if (metadata->getIsSelected()) {
m_SelectedArtworksCount--;
emit selectedArtworksCountChanged();
}
delete metadata;
m_ArtworkList.removeAt(row);
}
void ArtItemsModel::doRemoveItemsAtIndices(const QList<int> &indicesToRemove)
{
QList<QPair<int, int> > rangesToRemove;
Helpers::indicesToRanges(indicesToRemove, rangesToRemove);
removeItemsAtIndices(rangesToRemove);
m_ArtworksRepository->cleanupEmptyDirectories();
m_ArtworksRepository->updateCountsForExistingDirectories();
}
void ArtItemsModel::getSelectedItemsIndices(QList<int> &indices)
{
int count = m_ArtworkList.length();
for (int i = 0; i < count; ++i) {
ArtworkMetadata *metadata = m_ArtworkList[i];
if (metadata->getIsSelected()) {
indices.append(i);
}
}
}
}
<commit_msg>Fixed issue with keywords count after combined edit<commit_after>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014 Taras Kushnir <kushnirTV@gmail.com>
*
* Xpiks is distributed under the GNU General Public License, version 3.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QStringList>
#include <QDirIterator>
#include <QDebug>
#include <QList>
#include "artitemsmodel.h"
#include "artiteminfo.h"
#include "../Helpers/indiceshelper.h"
namespace Models {
ArtItemsModel::~ArtItemsModel() {
qDeleteAll(m_ArtworkList);
m_ArtworkList.clear();
// being freed in gui
//delete m_ArtworksDirectories;
}
int ArtItemsModel::getModifiedArtworksCount()
{
int modifiedCount = 0;
foreach (ArtworkMetadata *metadata, m_ArtworkList) {
if (metadata->isModified()) {
modifiedCount++;
}
}
return modifiedCount;
}
void ArtItemsModel::updateAllProperties()
{
QList<QPair<int, int> > ranges;
ranges << qMakePair(0, m_ArtworkList.length() - 1);
QVector<int> roles;
roles << ArtworkDescriptionRole << KeywordsRole << IsModifiedRole << ArtworkAuthorRole << ArtworkTitleRole;
updateItemsAtIndices(ranges, roles);
}
void ArtItemsModel::removeArtworksDirectory(int index)
{
const QString &directory = m_ArtworksRepository->getDirectory(index);
QList<int> indicesToRemove;
QList<ArtworkMetadata*>::const_iterator it = m_ArtworkList.constBegin();
for (int i = 0; it < m_ArtworkList.constEnd(); ++it, ++i) {
if ((*it)->isInDirectory(directory)) {
indicesToRemove.append(i);
}
}
doRemoveItemsAtIndices(indicesToRemove);
emit selectedArtworksCountChanged();
emit modifiedArtworksCountChanged();
}
void ArtItemsModel::removeKeywordAt(int metadataIndex, int keywordIndex)
{
if (metadataIndex >= 0 && metadataIndex < m_ArtworkList.length()) {
ArtworkMetadata *metadata = m_ArtworkList.at(metadataIndex);
if (metadata->removeKeywordAt(keywordIndex)) {
QModelIndex index = this->index(metadataIndex);
emit dataChanged(index, index, QVector<int>() << KeywordsRole << IsModifiedRole << KeywordsCountRole);
}
}
}
void ArtItemsModel::removeLastKeyword(int metadataIndex)
{
if (metadataIndex >= 0 && metadataIndex < m_ArtworkList.length()) {
ArtworkMetadata *metadata = m_ArtworkList.at(metadataIndex);
if (metadata->removeLastKeyword()) {
QModelIndex index = this->index(metadataIndex);
emit dataChanged(index, index, QVector<int>() << KeywordsRole << IsModifiedRole << KeywordsCountRole);
}
}
}
void ArtItemsModel::appendKeyword(int metadataIndex, const QString &keyword)
{
if (metadataIndex >= 0 && metadataIndex < m_ArtworkList.length()) {
ArtworkMetadata *metadata = m_ArtworkList.at(metadataIndex);
if (metadata->appendKeyword(keyword)) {
QModelIndex index = this->index(metadataIndex);
emit dataChanged(index, index, QVector<int>() << KeywordsRole << IsModifiedRole << KeywordsCountRole);
}
}
}
void ArtItemsModel::setSelectedItemsSaved()
{
QList<int> selectedIndices;
getSelectedItemsIndices(selectedIndices);
foreach (int index, selectedIndices) {
m_ArtworkList[index]->unsetModified();
}
QList<QPair<int, int> > rangesToUpdate;
Helpers::indicesToRanges(selectedIndices, rangesToUpdate);
updateItemsAtIndices(rangesToUpdate, QVector<int>() << IsModifiedRole);
updateModifiedCount();
}
void ArtItemsModel::removeSelectedArtworks()
{
QList<int> indicesToRemove;
getSelectedItemsIndices(indicesToRemove);
doRemoveItemsAtIndices(indicesToRemove);
}
void ArtItemsModel::updateSelectedArtworks()
{
QList<int> selectedIndices;
getSelectedItemsIndices(selectedIndices);
QList<QPair<int, int> > rangesToUpdate;
Helpers::indicesToRanges(selectedIndices, rangesToUpdate);
QVector<int> roles;
roles << ArtworkDescriptionRole << KeywordsRole << IsModifiedRole <<
ArtworkAuthorRole << ArtworkTitleRole << KeywordsCountRole;
updateItemsAtIndices(rangesToUpdate, roles);
}
void ArtItemsModel::patchSelectedArtworks()
{
QList<ArtworkMetadata*> selectedArtworks;
int count = m_ArtworkList.length();
for (int i = 0; i < count; ++i) {
ArtworkMetadata *metadata = m_ArtworkList[i];
if (metadata->getIsSelected()) {
selectedArtworks.append(metadata);
}
}
// TODO: assert iptc provider is not null
// TODO: remove this two times copying
m_IptcProvider->setArtworks(selectedArtworks);
}
void ArtItemsModel::uploadSelectedArtworks()
{
QList<ArtworkMetadata*> selectedArtworks;
int count = m_ArtworkList.length();
for (int i = 0; i < count; ++i) {
ArtworkMetadata *metadata = m_ArtworkList[i];
if (metadata->getIsSelected()) {
selectedArtworks.append(metadata);
}
}
// TODO: assert uploader is not null
// TODO: remove this two times copying
m_ArtworkUploader->setArtworks(selectedArtworks);
}
bool ArtItemsModel::areSelectedArtworksSaved()
{
bool areModified = false;
foreach(ArtworkMetadata *metadata, m_ArtworkList) {
if (metadata->getIsSelected()) {
if (metadata->isModified()) {
areModified = true;
break;
}
}
}
return !areModified;
}
void ArtItemsModel::selectDirectory(int directoryIndex)
{
QList<int> directoryItems;
const QString directory = m_ArtworksRepository->getDirectory(directoryIndex);
int i = 0;
foreach (ArtworkMetadata *metadata, m_ArtworkList) {
if (metadata->isInDirectory(directory)) {
directoryItems.append(i);
metadata->setIsSelected(!metadata->getIsSelected());
}
i++;
}
QList<QPair<int, int> > rangesToUpdate;
Helpers::indicesToRanges(directoryItems, rangesToUpdate);
updateItemsAtIndices(rangesToUpdate, QVector<int>() << IsSelectedRole);
}
int ArtItemsModel::rowCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
return m_ArtworkList.count();
}
QVariant ArtItemsModel::data(const QModelIndex &index, int role) const {
if (index.row() < 0 || index.row() >= m_ArtworkList.count())
return QVariant();
ArtworkMetadata *metadata = m_ArtworkList.at(index.row());
switch (role) {
case ArtworkDescriptionRole:
return metadata->getDescription();
case ArtworkFilenameRole:
return metadata->getFilepath();
case ArtworkAuthorRole:
return metadata->getAuthor();
case ArtworkTitleRole:
return metadata->getTitle();
case KeywordsRole:
return metadata->getKeywords();
case KeywordsStringRole:
return metadata->getKeywordsString();
case IsModifiedRole:
return metadata->isModified();
case IsSelectedRole:
return metadata->getIsSelected();
case KeywordsCountRole:
return metadata->getKeywordsCount();
default:
return QVariant();
}
}
Qt::ItemFlags ArtItemsModel::flags(const QModelIndex &index) const
{
if (!index.isValid()) {
return Qt::ItemIsEnabled;
}
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
bool ArtItemsModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid()) {
return false;
}
ArtworkMetadata *metadata = m_ArtworkList.at(index.row());
int roleToUpdate = 0;
switch (role) {
case EditArtworkDescriptionRole:
metadata->setDescription(value.toString());
roleToUpdate = ArtworkDescriptionRole;
break;
case EditArtworkTitleRole:
metadata->setTitle(value.toString());
roleToUpdate = ArtworkTitleRole;
break;
case EditArtworkAuthorRole:
metadata->setAuthor(value.toString());
roleToUpdate = ArtworkAuthorRole;
break;
case EditIsSelectedRole:
metadata->setIsSelected(value.toBool());
roleToUpdate = IsSelectedRole;
break;
default:
return false;
}
emit dataChanged(index, index, QVector<int>() << IsModifiedRole << role << roleToUpdate);
return true;
}
void ArtItemsModel::addLocalArtworks(const QList<QUrl> &artworksPaths)
{
qDebug() << artworksPaths;
QStringList fileList;
foreach (const QUrl &url, artworksPaths) {
fileList.append(url.toLocalFile());
}
addFiles(fileList);
}
void ArtItemsModel::addLocalDirectory(const QUrl &directory)
{
qDebug() << directory;
addDirectory(directory.toLocalFile());
}
void ArtItemsModel::itemSelectedChanged(bool value)
{
int plus = value ? +1 : -1;
m_SelectedArtworksCount += plus;
emit selectedArtworksCountChanged();
}
void ArtItemsModel::addDirectory(const QString &directory)
{
QDir dir(directory);
dir.setFilter(QDir::NoDotAndDotDot | QDir::Files);
QStringList items = dir.entryList();
for (int i = 0; i < items.size(); ++i) {
items[i] = dir.filePath(items[i]);
}
if (items.count() > 0) {
addFiles(items);
}
}
void ArtItemsModel::addFiles(const QStringList &rawFilenames)
{
QStringList filenames = rawFilenames.filter(QRegExp("^.*[.]jpg$", Qt::CaseInsensitive));
const int count = filenames.count();
const int newFilesCount = m_ArtworksRepository->getNewFilesCount(filenames);
bool filesWereAccounted = m_ArtworksRepository->beginAccountingFiles(filenames);
if (newFilesCount > 0) {
beginInsertRows(QModelIndex(), rowCount(), rowCount() + newFilesCount - 1);
for (int i = 0; i < count; ++i) {
const QString &filename = filenames[i];
if (m_ArtworksRepository->accountFile(filename))
{
ArtworkMetadata *metadata = new ArtworkMetadata(filename);
QObject::connect(metadata, SIGNAL(modifiedChanged(bool)),
this, SLOT(itemModifiedChanged(bool)));
QObject::connect(metadata, SIGNAL(selectedChanged(bool)),
this, SLOT(itemSelectedChanged(bool)));
QObject::connect(metadata, SIGNAL(fileSelectedChanged(QString,bool)),
m_ArtworksRepository, SLOT(fileSelectedChanged(QString,bool)));
m_ArtworkList.append(metadata);
}
}
endInsertRows();
}
m_ArtworksRepository->endAccountingFiles(filesWereAccounted);
if (newFilesCount > 0) {
m_ArtworksRepository->updateCountsForExistingDirectories();
}
// set artworks for initial import
m_IptcProvider->setArtworks(m_ArtworkList);
}
void ArtItemsModel::setAllItemsSelected(bool selected)
{
qDebug() << "Setting all items selected (" << selected << ")";
int length = m_ArtworkList.length();
for (int i = 0; i < length; ++i) {
ArtworkMetadata *metadata = m_ArtworkList[i];
metadata->setIsSelected(selected);
}
if (length > 0) {
QModelIndex startIndex = index(0);
QModelIndex endIndex = index(length - 1);
emit dataChanged(startIndex, endIndex, QVector<int>() << IsSelectedRole);
}
}
void ArtItemsModel::doCombineSelectedImages(CombinedArtworksModel *combinedModel) const
{
QList<ArtItemInfo*> artworksList;
foreach (ArtworkMetadata *metadata, m_ArtworkList) {
if (metadata->getIsSelected()) {
ArtItemInfo *info = new ArtItemInfo(metadata);
artworksList.append(info);
}
}
combinedModel->initArtworks(artworksList);
combinedModel->recombineArtworks();
}
void ArtItemsModel::doCombineArtwork(int index, CombinedArtworksModel *combinedModel)
{
if (index >= 0 && index < m_ArtworkList.length()) {
QList<ArtItemInfo*> artworksList;
ArtworkMetadata *metadata = m_ArtworkList.at(index);
metadata->setIsSelected(true);
QModelIndex qmIndex = this->index(index);
emit dataChanged(qmIndex, qmIndex, QVector<int>() << IsSelectedRole);
ArtItemInfo *info = new ArtItemInfo(metadata);
artworksList.append(info);
combinedModel->initArtworks(artworksList);
combinedModel->recombineArtworks();
}
}
QHash<int, QByteArray> ArtItemsModel::roleNames() const {
QHash<int, QByteArray> roles;
roles[ArtworkDescriptionRole] = "description";
roles[EditArtworkDescriptionRole] = "editdescription";
roles[ArtworkAuthorRole] = "author";
roles[EditArtworkAuthorRole] = "editauthor";
roles[ArtworkTitleRole] = "title";
roles[EditArtworkTitleRole] = "edittitle";
roles[ArtworkFilenameRole] = "filename";
roles[KeywordsRole] = "keywords";
roles[KeywordsStringRole] = "keywordsstring";
roles[IsModifiedRole] = "ismodified";
roles[IsSelectedRole] = "isselected";
roles[EditIsSelectedRole] = "editisselected";
roles[KeywordsCountRole] = "keywordscount";
return roles;
}
void ArtItemsModel::removeInnerItem(int row)
{
// TODO: add assert for row
ArtworkMetadata *metadata = m_ArtworkList[row];
m_ArtworksRepository->removeFile(metadata->getFilepath());
if (metadata->getIsSelected()) {
m_SelectedArtworksCount--;
emit selectedArtworksCountChanged();
}
delete metadata;
m_ArtworkList.removeAt(row);
}
void ArtItemsModel::doRemoveItemsAtIndices(const QList<int> &indicesToRemove)
{
QList<QPair<int, int> > rangesToRemove;
Helpers::indicesToRanges(indicesToRemove, rangesToRemove);
removeItemsAtIndices(rangesToRemove);
m_ArtworksRepository->cleanupEmptyDirectories();
m_ArtworksRepository->updateCountsForExistingDirectories();
}
void ArtItemsModel::getSelectedItemsIndices(QList<int> &indices)
{
int count = m_ArtworkList.length();
for (int i = 0; i < count; ++i) {
ArtworkMetadata *metadata = m_ArtworkList[i];
if (metadata->getIsSelected()) {
indices.append(i);
}
}
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkVotingBinaryImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkRandomImageSource.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkVotingBinaryImageFilter.h"
#include "itkTextOutput.h"
int itkVotingBinaryImageFilterTest(int, char* [] )
{
// Comment the following if you want to use the itk text output window
itk::OutputWindow::SetInstance(itk::TextOutput::New());
typedef itk::Image<unsigned short,2> ImageType;
itk::RandomImageSource<ImageType>::Pointer random;
random = itk::RandomImageSource<ImageType>::New();
random->SetMin( 0 );
random->SetMax( 100 );
unsigned long randomSize[2];
randomSize[0] = randomSize[1] = 8;
random->SetSize(randomSize);
float spacing[2] = {0.7, 2.1};
random->SetSpacing( spacing );
float origin[2] = {15, 400};
random->SetOrigin( origin );
ImageType::PixelType foreground = 97; // prime numbers are good testers
ImageType::PixelType background = 29;
itk::BinaryThresholdImageFilter<ImageType,ImageType>::Pointer thresholder;
thresholder = itk::BinaryThresholdImageFilter<ImageType,ImageType>::New();
thresholder->SetInput( random->GetOutput() );
thresholder->SetLowerThreshold( 30 );
thresholder->SetUpperThreshold( 100 );
thresholder->SetInsideValue( foreground );
thresholder->SetOutsideValue( background );
// Create a voting image
itk::VotingBinaryImageFilter<ImageType, ImageType>::Pointer voting;
voting = itk::VotingBinaryImageFilter<ImageType,ImageType>::New();
voting->SetInput( thresholder->GetOutput());
voting->SetForegroundValue( foreground );
voting->SetBackgroundValue( background );
// define the neighborhood size used for the voting filter (5x5)
ImageType::SizeType neighRadius;
neighRadius[0] = 1;
neighRadius[1] = 1;
voting->SetRadius(neighRadius);
// run the algorithm
voting->Update();
itk::ImageRegionIterator<ImageType> it;
it = itk::ImageRegionIterator<ImageType>(random->GetOutput(),
random->GetOutput()->GetBufferedRegion());
std::cout << "Input image" << std::endl;
unsigned int i;
for (i=1; !it.IsAtEnd(); ++i, ++it)
{
std::cout << "\t" << it.Get();
if ((i % 8) == 0)
{
std::cout << std::endl;
}
}
it = itk::ImageRegionIterator<ImageType>(thresholder->GetOutput(),
thresholder->GetOutput()->GetBufferedRegion());
std::cout << "Binary image" << std::endl;
for (i=1; !it.IsAtEnd(); ++i, ++it)
{
std::cout << "\t" << it.Get();
if ((i % 8) == 0)
{
std::cout << std::endl;
}
}
std::cout << "Output image" << std::endl;
it = itk::ImageRegionIterator<ImageType>(voting->GetOutput(),
voting->GetOutput()->GetBufferedRegion());
for (i=1; !it.IsAtEnd(); ++i, ++it)
{
std::cout << "\t" << it.Get();
if ((i % 8) == 0)
{
std::cout << std::endl;
}
}
return EXIT_SUCCESS;
}
<commit_msg>ENH: Added invokations for SetSurvivalThreshold and SetBornThreshold.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkVotingBinaryImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkRandomImageSource.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkVotingBinaryImageFilter.h"
#include "itkTextOutput.h"
int itkVotingBinaryImageFilterTest(int, char* [] )
{
// Comment the following if you want to use the itk text output window
itk::OutputWindow::SetInstance(itk::TextOutput::New());
typedef itk::Image<unsigned short,2> ImageType;
itk::RandomImageSource<ImageType>::Pointer random;
random = itk::RandomImageSource<ImageType>::New();
random->SetMin( 0 );
random->SetMax( 100 );
unsigned long randomSize[2];
randomSize[0] = randomSize[1] = 8;
random->SetSize(randomSize);
float spacing[2] = {0.7, 2.1};
random->SetSpacing( spacing );
float origin[2] = {15, 400};
random->SetOrigin( origin );
ImageType::PixelType foreground = 97; // prime numbers are good testers
ImageType::PixelType background = 29;
itk::BinaryThresholdImageFilter<ImageType,ImageType>::Pointer thresholder;
thresholder = itk::BinaryThresholdImageFilter<ImageType,ImageType>::New();
thresholder->SetInput( random->GetOutput() );
thresholder->SetLowerThreshold( 30 );
thresholder->SetUpperThreshold( 100 );
thresholder->SetInsideValue( foreground );
thresholder->SetOutsideValue( background );
// Create a voting image
itk::VotingBinaryImageFilter<ImageType, ImageType>::Pointer voting;
voting = itk::VotingBinaryImageFilter<ImageType,ImageType>::New();
voting->SetInput( thresholder->GetOutput());
voting->SetForegroundValue( foreground );
voting->SetBackgroundValue( background );
// define the neighborhood size used for the voting filter (5x5)
ImageType::SizeType neighRadius;
neighRadius[0] = 1;
neighRadius[1] = 1;
voting->SetRadius(neighRadius);
voting->SetBornThreshold( 5 );
voting->SetSurvivalThreshold( 0 );
// run the algorithm
voting->Update();
itk::ImageRegionIterator<ImageType> it;
it = itk::ImageRegionIterator<ImageType>(random->GetOutput(),
random->GetOutput()->GetBufferedRegion());
std::cout << "Input image" << std::endl;
unsigned int i;
for (i=1; !it.IsAtEnd(); ++i, ++it)
{
std::cout << "\t" << it.Get();
if ((i % 8) == 0)
{
std::cout << std::endl;
}
}
it = itk::ImageRegionIterator<ImageType>(thresholder->GetOutput(),
thresholder->GetOutput()->GetBufferedRegion());
std::cout << "Binary image" << std::endl;
for (i=1; !it.IsAtEnd(); ++i, ++it)
{
std::cout << "\t" << it.Get();
if ((i % 8) == 0)
{
std::cout << std::endl;
}
}
std::cout << "Output image" << std::endl;
it = itk::ImageRegionIterator<ImageType>(voting->GetOutput(),
voting->GetOutput()->GetBufferedRegion());
for (i=1; !it.IsAtEnd(); ++i, ++it)
{
std::cout << "\t" << it.Get();
if ((i % 8) == 0)
{
std::cout << std::endl;
}
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2014-2019 AscEmu Team <http://www.ascemu.org>
This file is released under the MIT license. See README-MIT for more information.
*/
#include "StdAfx.h"
#include "ConsoleAuthMgr.h"
ConsoleAuthMgr& ConsoleAuthMgr::getInstance()
{
static ConsoleAuthMgr mInstance;
return mInstance;
}
void ConsoleAuthMgr::initialize()
{
authRequestId = 1;
}
uint32_t ConsoleAuthMgr::getGeneratedId()
{
consoleAuthMgrLock.Acquire();
uint32_t requestId = authRequestId++;
consoleAuthMgrLock.Release();
return requestId;
}
void ConsoleAuthMgr::addRequestIdSocket(uint32_t id, ConsoleSocket* sock)
{
consoleAuthMgrLock.Acquire();
if (sock == nullptr)
{
consoleRequestMap.erase(id);
}
else
{
consoleRequestMap.insert(std::make_pair(id, sock));
}
consoleAuthMgrLock.Release();
}
ConsoleSocket* ConsoleAuthMgr::getSocketByRequestId(uint32_t id)
{
ConsoleSocket* consoleSocket = nullptr;
consoleAuthMgrLock.Acquire();
std::map<uint32_t, ConsoleSocket*>::iterator itr = consoleRequestMap.find(id);
if (itr != consoleRequestMap.end())
{
consoleSocket = itr->second;
}
consoleAuthMgrLock.Release();
return consoleSocket;
}
<commit_msg>Resolved CID 351682 (#1 of 1): Data race condition<commit_after>/*
Copyright (c) 2014-2019 AscEmu Team <http://www.ascemu.org>
This file is released under the MIT license. See README-MIT for more information.
*/
#include "StdAfx.h"
#include "ConsoleAuthMgr.h"
ConsoleAuthMgr& ConsoleAuthMgr::getInstance()
{
static ConsoleAuthMgr mInstance;
return mInstance;
}
void ConsoleAuthMgr::initialize()
{
consoleAuthMgrLock.Acquire();
authRequestId = 1;
consoleAuthMgrLock.Release();
}
uint32_t ConsoleAuthMgr::getGeneratedId()
{
consoleAuthMgrLock.Acquire();
uint32_t requestId = authRequestId++;
consoleAuthMgrLock.Release();
return requestId;
}
void ConsoleAuthMgr::addRequestIdSocket(uint32_t id, ConsoleSocket* sock)
{
consoleAuthMgrLock.Acquire();
if (sock == nullptr)
{
consoleRequestMap.erase(id);
}
else
{
consoleRequestMap.insert(std::make_pair(id, sock));
}
consoleAuthMgrLock.Release();
}
ConsoleSocket* ConsoleAuthMgr::getSocketByRequestId(uint32_t id)
{
ConsoleSocket* consoleSocket = nullptr;
consoleAuthMgrLock.Acquire();
std::map<uint32_t, ConsoleSocket*>::iterator itr = consoleRequestMap.find(id);
if (itr != consoleRequestMap.end())
{
consoleSocket = itr->second;
}
consoleAuthMgrLock.Release();
return consoleSocket;
}
<|endoftext|>
|
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/hid/winkey/winkey_input_driver.h"
#include "xenia/base/platform_win.h"
#include "xenia/hid/hid_flags.h"
#include "xenia/hid/input_system.h"
#include "xenia/ui/window.h"
namespace xe {
namespace hid {
namespace winkey {
WinKeyInputDriver::WinKeyInputDriver(xe::ui::Window* window)
: InputDriver(window), packet_number_(1) {
// Register a key listener.
window_->on_key_down.AddListener([this](ui::KeyEvent* evt) {
auto global_lock = global_critical_region_.Acquire();
KeyEvent key;
key.vkey = evt->key_code();
key.transition = true;
key.prev_state = evt->prev_state();
key.repeat_count = evt->repeat_count();
key_events_.push(key);
});
window_->on_key_up.AddListener([this](ui::KeyEvent* evt) {
auto global_lock = global_critical_region_.Acquire();
KeyEvent key;
key.vkey = evt->key_code();
key.transition = false;
key.prev_state = evt->prev_state();
key.repeat_count = evt->repeat_count();
key_events_.push(key);
});
}
WinKeyInputDriver::~WinKeyInputDriver() = default;
X_STATUS WinKeyInputDriver::Setup() { return X_STATUS_SUCCESS; }
X_RESULT WinKeyInputDriver::GetCapabilities(uint32_t user_index, uint32_t flags,
X_INPUT_CAPABILITIES* out_caps) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
// TODO(benvanik): confirm with a real XInput controller.
out_caps->type = 0x01; // XINPUT_DEVTYPE_GAMEPAD
out_caps->sub_type = 0x01; // XINPUT_DEVSUBTYPE_GAMEPAD
out_caps->flags = 0;
out_caps->gamepad.buttons = 0xFFFF;
out_caps->gamepad.left_trigger = 0xFF;
out_caps->gamepad.right_trigger = 0xFF;
out_caps->gamepad.thumb_lx = (int16_t)0xFFFFu;
out_caps->gamepad.thumb_ly = (int16_t)0xFFFFu;
out_caps->gamepad.thumb_rx = (int16_t)0xFFFFu;
out_caps->gamepad.thumb_ry = (int16_t)0xFFFFu;
out_caps->vibration.left_motor_speed = 0;
out_caps->vibration.right_motor_speed = 0;
return X_ERROR_SUCCESS;
}
#define IS_KEY_TOGGLED(key) ((GetKeyState(key) & 0x1) == 0x1)
#define IS_KEY_DOWN(key) ((GetAsyncKeyState(key) & 0x8000) == 0x8000)
X_RESULT WinKeyInputDriver::GetState(uint32_t user_index,
X_INPUT_STATE* out_state) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
packet_number_++;
uint16_t buttons = 0;
uint8_t left_trigger = 0;
uint8_t right_trigger = 0;
int16_t thumb_lx = 0;
int16_t thumb_ly = 0;
int16_t thumb_rx = 0;
int16_t thumb_ry = 0;
if (window_->has_focus()) {
if (IS_KEY_TOGGLED(VK_CAPITAL)) {
// dpad toggled
if (IS_KEY_DOWN(0x41)) {
// A
buttons |= 0x0004; // XINPUT_GAMEPAD_DPAD_LEFT
}
if (IS_KEY_DOWN(0x44)) {
// D
buttons |= 0x0008; // XINPUT_GAMEPAD_DPAD_RIGHT
}
if (IS_KEY_DOWN(0x53)) {
// S
buttons |= 0x0002; // XINPUT_GAMEPAD_DPAD_DOWN
}
if (IS_KEY_DOWN(0x57)) {
// W
buttons |= 0x0001; // XINPUT_GAMEPAD_DPAD_UP
}
} else {
// left stick
if (IS_KEY_DOWN(0x41)) {
// A
thumb_lx += SHRT_MIN;
}
if (IS_KEY_DOWN(0x44)) {
// D
thumb_lx += SHRT_MAX;
}
if (IS_KEY_DOWN(0x53)) {
// S
thumb_ly += SHRT_MIN;
}
if (IS_KEY_DOWN(0x57)) {
// W
thumb_ly += SHRT_MAX;
}
}
// Right stick
if (IS_KEY_DOWN(0x26)) {
// Up
thumb_ry += SHRT_MAX;
}
if (IS_KEY_DOWN(0x28)) {
// Down
thumb_ry += SHRT_MIN;
}
if (IS_KEY_DOWN(0x27)) {
// Right
thumb_rx += SHRT_MAX;
}
if (IS_KEY_DOWN(0x25)) {
// Left
thumb_rx += SHRT_MIN;
}
if (IS_KEY_DOWN(0x4C)) {
// L
buttons |= 0x4000; // XINPUT_GAMEPAD_X
}
if (IS_KEY_DOWN(VK_OEM_7)) {
// '
buttons |= 0x2000; // XINPUT_GAMEPAD_B
}
if (IS_KEY_DOWN(VK_OEM_1)) {
// ;
buttons |= 0x1000; // XINPUT_GAMEPAD_A
}
if (IS_KEY_DOWN(0x50)) {
// P
buttons |= 0x8000; // XINPUT_GAMEPAD_Y
}
if (IS_KEY_DOWN(0x51) || IS_KEY_DOWN(0x49)) {
// Q / I
left_trigger = 0xFF;
}
if (IS_KEY_DOWN(0x45) || IS_KEY_DOWN(0x4F)) {
// E / O
right_trigger = 0xFF;
}
if (IS_KEY_DOWN(0x5A)) {
// Z
buttons |= 0x0020; // XINPUT_GAMEPAD_BACK
}
if (IS_KEY_DOWN(0x58)) {
// X
buttons |= 0x0010; // XINPUT_GAMEPAD_START
}
}
out_state->packet_number = packet_number_;
out_state->gamepad.buttons = buttons;
out_state->gamepad.left_trigger = left_trigger;
out_state->gamepad.right_trigger = right_trigger;
out_state->gamepad.thumb_lx = thumb_lx;
out_state->gamepad.thumb_ly = thumb_ly;
out_state->gamepad.thumb_rx = thumb_rx;
out_state->gamepad.thumb_ry = thumb_ry;
return X_ERROR_SUCCESS;
}
X_RESULT WinKeyInputDriver::SetState(uint32_t user_index,
X_INPUT_VIBRATION* vibration) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
return X_ERROR_SUCCESS;
}
X_RESULT WinKeyInputDriver::GetKeystroke(uint32_t user_index, uint32_t flags,
X_INPUT_KEYSTROKE* out_keystroke) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
X_RESULT result = X_ERROR_EMPTY;
uint16_t virtual_key = 0;
uint16_t unicode = 0;
uint16_t keystroke_flags = 0;
uint8_t hid_code = 0;
// Pop from the queue.
KeyEvent evt;
{
auto global_lock = global_critical_region_.Acquire();
if (key_events_.empty()) {
// No keys!
return X_ERROR_EMPTY;
}
evt = key_events_.front();
key_events_.pop();
}
// TODO(DrChat): Some other way to toggle this...
if (IS_KEY_TOGGLED(VK_CAPITAL)) {
// dpad toggled
if (evt.vkey == (0x41)) {
// A
virtual_key = 0x5812; // VK_PAD_DPAD_LEFT
} else if (evt.vkey == (0x44)) {
// D
virtual_key = 0x5813; // VK_PAD_DPAD_RIGHT
} else if (evt.vkey == (0x53)) {
// S
virtual_key = 0x5811; // VK_PAD_DPAD_DOWN
} else if (evt.vkey == (0x57)) {
// W
virtual_key = 0x5810; // VK_PAD_DPAD_UP
}
} else {
// left stick
if (evt.vkey == (0x57)) {
// W
virtual_key = 0x5820; // VK_PAD_LTHUMB_UP
}
if (evt.vkey == (0x53)) {
// S
virtual_key = 0x5821; // VK_PAD_LTHUMB_DOWN
}
if (evt.vkey == (0x44)) {
// D
virtual_key = 0x5822; // VK_PAD_LTHUMB_RIGHT
}
if (evt.vkey == (0x41)) {
// A
virtual_key = 0x5823; // VK_PAD_LTHUMB_LEFT
}
}
// Right stick
if (evt.vkey == (0x26)) {
// Up
virtual_key = 0x5830;
}
if (evt.vkey == (0x28)) {
// Down
virtual_key = 0x5831;
}
if (evt.vkey == (0x27)) {
// Right
virtual_key = 0x5832;
}
if (evt.vkey == (0x25)) {
// Left
virtual_key = 0x5833;
}
if (evt.vkey == (0x4C)) {
// L
virtual_key = 0x5802; // VK_PAD_X
} else if (evt.vkey == (VK_OEM_7)) {
// '
virtual_key = 0x5801; // VK_PAD_B
} else if (evt.vkey == (VK_OEM_1)) {
// ;
virtual_key = 0x5800; // VK_PAD_A
} else if (evt.vkey == (0x50)) {
// P
virtual_key = 0x5803; // VK_PAD_Y
}
if (evt.vkey == (0x58)) {
// X
virtual_key = 0x5814; // VK_PAD_START
}
if (evt.vkey == (0x5A)) {
// Z
virtual_key = 0x5815; // VK_PAD_BACK
}
if (virtual_key != 0) {
if (evt.transition == true) {
keystroke_flags |= 0x0001; // XINPUT_KEYSTROKE_KEYDOWN
} else if (evt.transition == false) {
keystroke_flags |= 0x0002; // XINPUT_KEYSTROKE_KEYUP
}
if (evt.prev_state == evt.transition) {
keystroke_flags |= 0x0004; // XINPUT_KEYSTROKE_REPEAT
}
result = X_ERROR_SUCCESS;
}
out_keystroke->virtual_key = virtual_key;
out_keystroke->unicode = unicode;
out_keystroke->flags = keystroke_flags;
out_keystroke->user_index = 0;
out_keystroke->hid_code = hid_code;
// X_ERROR_EMPTY if no new keys
// X_ERROR_DEVICE_NOT_CONNECTED if no device
// X_ERROR_SUCCESS if key
return result;
}
} // namespace winkey
} // namespace hid
} // namespace xe
<commit_msg>Added keyboard support for triggers and shoulder buttons<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/hid/winkey/winkey_input_driver.h"
#include "xenia/base/platform_win.h"
#include "xenia/hid/hid_flags.h"
#include "xenia/hid/input_system.h"
#include "xenia/ui/window.h"
namespace xe {
namespace hid {
namespace winkey {
WinKeyInputDriver::WinKeyInputDriver(xe::ui::Window* window)
: InputDriver(window), packet_number_(1) {
// Register a key listener.
window_->on_key_down.AddListener([this](ui::KeyEvent* evt) {
auto global_lock = global_critical_region_.Acquire();
KeyEvent key;
key.vkey = evt->key_code();
key.transition = true;
key.prev_state = evt->prev_state();
key.repeat_count = evt->repeat_count();
key_events_.push(key);
});
window_->on_key_up.AddListener([this](ui::KeyEvent* evt) {
auto global_lock = global_critical_region_.Acquire();
KeyEvent key;
key.vkey = evt->key_code();
key.transition = false;
key.prev_state = evt->prev_state();
key.repeat_count = evt->repeat_count();
key_events_.push(key);
});
}
WinKeyInputDriver::~WinKeyInputDriver() = default;
X_STATUS WinKeyInputDriver::Setup() { return X_STATUS_SUCCESS; }
X_RESULT WinKeyInputDriver::GetCapabilities(uint32_t user_index, uint32_t flags,
X_INPUT_CAPABILITIES* out_caps) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
// TODO(benvanik): confirm with a real XInput controller.
out_caps->type = 0x01; // XINPUT_DEVTYPE_GAMEPAD
out_caps->sub_type = 0x01; // XINPUT_DEVSUBTYPE_GAMEPAD
out_caps->flags = 0;
out_caps->gamepad.buttons = 0xFFFF;
out_caps->gamepad.left_trigger = 0xFF;
out_caps->gamepad.right_trigger = 0xFF;
out_caps->gamepad.thumb_lx = (int16_t)0xFFFFu;
out_caps->gamepad.thumb_ly = (int16_t)0xFFFFu;
out_caps->gamepad.thumb_rx = (int16_t)0xFFFFu;
out_caps->gamepad.thumb_ry = (int16_t)0xFFFFu;
out_caps->vibration.left_motor_speed = 0;
out_caps->vibration.right_motor_speed = 0;
return X_ERROR_SUCCESS;
}
#define IS_KEY_TOGGLED(key) ((GetKeyState(key) & 0x1) == 0x1)
#define IS_KEY_DOWN(key) ((GetAsyncKeyState(key) & 0x8000) == 0x8000)
X_RESULT WinKeyInputDriver::GetState(uint32_t user_index,
X_INPUT_STATE* out_state) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
packet_number_++;
uint16_t buttons = 0;
uint8_t left_trigger = 0;
uint8_t right_trigger = 0;
int16_t thumb_lx = 0;
int16_t thumb_ly = 0;
int16_t thumb_rx = 0;
int16_t thumb_ry = 0;
if (window_->has_focus()) {
if (IS_KEY_TOGGLED(VK_CAPITAL)) {
// dpad toggled
if (IS_KEY_DOWN(0x41)) {
// A
buttons |= 0x0004; // XINPUT_GAMEPAD_DPAD_LEFT
}
if (IS_KEY_DOWN(0x44)) {
// D
buttons |= 0x0008; // XINPUT_GAMEPAD_DPAD_RIGHT
}
if (IS_KEY_DOWN(0x53)) {
// S
buttons |= 0x0002; // XINPUT_GAMEPAD_DPAD_DOWN
}
if (IS_KEY_DOWN(0x57)) {
// W
buttons |= 0x0001; // XINPUT_GAMEPAD_DPAD_UP
}
} else {
// left stick
if (IS_KEY_DOWN(0x41)) {
// A
thumb_lx += SHRT_MIN;
}
if (IS_KEY_DOWN(0x44)) {
// D
thumb_lx += SHRT_MAX;
}
if (IS_KEY_DOWN(0x53)) {
// S
thumb_ly += SHRT_MIN;
}
if (IS_KEY_DOWN(0x57)) {
// W
thumb_ly += SHRT_MAX;
}
}
// Right stick
if (IS_KEY_DOWN(0x26)) {
// Up
thumb_ry += SHRT_MAX;
}
if (IS_KEY_DOWN(0x28)) {
// Down
thumb_ry += SHRT_MIN;
}
if (IS_KEY_DOWN(0x27)) {
// Right
thumb_rx += SHRT_MAX;
}
if (IS_KEY_DOWN(0x25)) {
// Left
thumb_rx += SHRT_MIN;
}
if (IS_KEY_DOWN(0x4C)) {
// L
buttons |= 0x4000; // XINPUT_GAMEPAD_X
}
if (IS_KEY_DOWN(VK_OEM_7)) {
// '
buttons |= 0x2000; // XINPUT_GAMEPAD_B
}
if (IS_KEY_DOWN(VK_OEM_1)) {
// ;
buttons |= 0x1000; // XINPUT_GAMEPAD_A
}
if (IS_KEY_DOWN(0x50)) {
// P
buttons |= 0x8000; // XINPUT_GAMEPAD_Y
}
if (IS_KEY_DOWN(0x51) || IS_KEY_DOWN(0x49)) {
// Q / I
left_trigger = 0xFF;
}
if (IS_KEY_DOWN(0x45) || IS_KEY_DOWN(0x4F)) {
// E / O
right_trigger = 0xFF;
}
if (IS_KEY_DOWN(0x5A)) {
// Z
buttons |= 0x0020; // XINPUT_GAMEPAD_BACK
}
if (IS_KEY_DOWN(0x58)) {
// X
buttons |= 0x0010; // XINPUT_GAMEPAD_START
}
if (IS_KEY_DOWN(0x31)) {
// 1
buttons |= 0x0100; // XINPUT_GAMEPAD_LEFT_SHOULDER
}
if (IS_KEY_DOWN(0x33)) {
// 3
buttons |= 0x0200; // XINPUT_GAMEPAD_RIGHT_SHOULDER
}
}
out_state->packet_number = packet_number_;
out_state->gamepad.buttons = buttons;
out_state->gamepad.left_trigger = left_trigger;
out_state->gamepad.right_trigger = right_trigger;
out_state->gamepad.thumb_lx = thumb_lx;
out_state->gamepad.thumb_ly = thumb_ly;
out_state->gamepad.thumb_rx = thumb_rx;
out_state->gamepad.thumb_ry = thumb_ry;
return X_ERROR_SUCCESS;
}
X_RESULT WinKeyInputDriver::SetState(uint32_t user_index,
X_INPUT_VIBRATION* vibration) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
return X_ERROR_SUCCESS;
}
X_RESULT WinKeyInputDriver::GetKeystroke(uint32_t user_index, uint32_t flags,
X_INPUT_KEYSTROKE* out_keystroke) {
if (user_index != 0) {
return X_ERROR_DEVICE_NOT_CONNECTED;
}
X_RESULT result = X_ERROR_EMPTY;
uint16_t virtual_key = 0;
uint16_t unicode = 0;
uint16_t keystroke_flags = 0;
uint8_t hid_code = 0;
// Pop from the queue.
KeyEvent evt;
{
auto global_lock = global_critical_region_.Acquire();
if (key_events_.empty()) {
// No keys!
return X_ERROR_EMPTY;
}
evt = key_events_.front();
key_events_.pop();
}
// TODO(DrChat): Some other way to toggle this...
if (IS_KEY_TOGGLED(VK_CAPITAL)) {
// dpad toggled
if (evt.vkey == (0x41)) {
// A
virtual_key = 0x5812; // VK_PAD_DPAD_LEFT
} else if (evt.vkey == (0x44)) {
// D
virtual_key = 0x5813; // VK_PAD_DPAD_RIGHT
} else if (evt.vkey == (0x53)) {
// S
virtual_key = 0x5811; // VK_PAD_DPAD_DOWN
} else if (evt.vkey == (0x57)) {
// W
virtual_key = 0x5810; // VK_PAD_DPAD_UP
}
} else {
// left stick
if (evt.vkey == (0x57)) {
// W
virtual_key = 0x5820; // VK_PAD_LTHUMB_UP
}
if (evt.vkey == (0x53)) {
// S
virtual_key = 0x5821; // VK_PAD_LTHUMB_DOWN
}
if (evt.vkey == (0x44)) {
// D
virtual_key = 0x5822; // VK_PAD_LTHUMB_RIGHT
}
if (evt.vkey == (0x41)) {
// A
virtual_key = 0x5823; // VK_PAD_LTHUMB_LEFT
}
}
// Right stick
if (evt.vkey == (0x26)) {
// Up
virtual_key = 0x5830;
}
if (evt.vkey == (0x28)) {
// Down
virtual_key = 0x5831;
}
if (evt.vkey == (0x27)) {
// Right
virtual_key = 0x5832;
}
if (evt.vkey == (0x25)) {
// Left
virtual_key = 0x5833;
}
if (evt.vkey == (0x4C)) {
// L
virtual_key = 0x5802; // VK_PAD_X
} else if (evt.vkey == (VK_OEM_7)) {
// '
virtual_key = 0x5801; // VK_PAD_B
} else if (evt.vkey == (VK_OEM_1)) {
// ;
virtual_key = 0x5800; // VK_PAD_A
} else if (evt.vkey == (0x50)) {
// P
virtual_key = 0x5803; // VK_PAD_Y
}
if (evt.vkey == (0x58)) {
// X
virtual_key = 0x5814; // VK_PAD_START
}
if (evt.vkey == (0x5A)) {
// Z
virtual_key = 0x5815; // VK_PAD_BACK
}
if (evt.vkey == (0x51) || evt.vkey == (0x49)) {
// Q / I
virtual_key = 0x5806; // VK_PAD_LTRIGGER
}
if (evt.vkey == (0x45) || evt.vkey == (0x4F)) {
// E / O
virtual_key = 0x5807; // VK_PAD_RTRIGGER
}
if (evt.vkey == (0x31)) {
// 1
virtual_key = 0x5805; // VK_PAD_LSHOULDER
}
if (evt.vkey == (0x33)) {
// 3
virtual_key = 0x5804; // VK_PAD_RSHOULDER
}
if (virtual_key != 0) {
if (evt.transition == true) {
keystroke_flags |= 0x0001; // XINPUT_KEYSTROKE_KEYDOWN
} else if (evt.transition == false) {
keystroke_flags |= 0x0002; // XINPUT_KEYSTROKE_KEYUP
}
if (evt.prev_state == evt.transition) {
keystroke_flags |= 0x0004; // XINPUT_KEYSTROKE_REPEAT
}
result = X_ERROR_SUCCESS;
}
out_keystroke->virtual_key = virtual_key;
out_keystroke->unicode = unicode;
out_keystroke->flags = keystroke_flags;
out_keystroke->user_index = 0;
out_keystroke->hid_code = hid_code;
// X_ERROR_EMPTY if no new keys
// X_ERROR_DEVICE_NOT_CONNECTED if no device
// X_ERROR_SUCCESS if key
return result;
}
} // namespace winkey
} // namespace hid
} // namespace xe
<|endoftext|>
|
<commit_before>#pragma once
#include <assert.h>
#include <mutex>
#include <iostream>
/** Thread safe output stream.
*
* Insert SafeStream::begin to start a session => lock the stream
* Insert SafeStream::end to stop a session => unlock the stream.
* Insert anything else to insert in the protected stream (requires a session).
*
* @todo It would be better if the open/close session was part of a trait
* class instead of virtual but this would imply partial specialization for
* the insertion operator, which is a pain in the ass in c++O3.
*/
class SafeStream
{
public:
/** @param[in] stream is the stream to protect from concurrent access. */
SafeStream(std::ostream & stream) : lock_taken(false), _output(stream) {}
virtual ~SafeStream() {};
/** Manipulator: type used to begin a session. */
struct Begin {};
/** A static instance of Begin to avoid instantiating one for each session start */
static const Begin begin;
/** Manipulator: type used to end a session. */
struct End {};
/** A static instance of End to avoid instantiating one for each session stop. */
static const End end;
/** The insertion operator.
*
* @tparam T If Begin or End, start or end a session.
* If any other type, append to the stream using operator <<.
* @param[in] ti The object to be output or a manipulator.
*/
template<class T>
SafeStream & operator<< (const T & ti);
private:
/** Open session */
virtual void openSession() {}
/** Close session */
virtual void closeSession() {}
/** Start a session. */
void start() {
lock();
openSession();
}
/** End the current session. */
void stop() {
closeSession();
unlock();
}
/** Lock the stream */
void lock() {
_mutex.lock();
lock_taken = true;
}
/** Unlock the stream */
void unlock() {
assert(lock_taken);
lock_taken = false;
_mutex.unlock();
}
/** The mutex state, for debug purpose only. */
bool lock_taken;
/** The stream mutex*/
std::mutex _mutex;
/** The concurrency access protected stream. */
std::ostream & _output;
};
const SafeStream::Begin SafeStream::begin;
const SafeStream::End SafeStream::end;
/** Add a token to stream. */
template<class T>
SafeStream & SafeStream::operator<< (const T & ti) {
assert(lock_taken);
_output << ti;
return *this;
}
/** Start a session.
*
* Will block if is a session is already started.
*/
template<>
SafeStream & SafeStream::operator<< <SafeStream::Begin> (const SafeStream::Begin &) {
start();
return *this;
}
/** Stop the current session. */
template<>
SafeStream & SafeStream::operator<< <SafeStream::End> (const SafeStream::End &) {
stop();
return *this;
}
<commit_msg>Use cassert instead of assert.h<commit_after>#pragma once
#include <cassert>
#include <mutex>
#include <iostream>
/** Thread safe output stream.
*
* Insert SafeStream::begin to start a session => lock the stream
* Insert SafeStream::end to stop a session => unlock the stream.
* Insert anything else to insert in the protected stream (requires a session).
*
* @todo It would be better if the open/close session was part of a trait
* class instead of virtual but this would imply partial specialization for
* the insertion operator, which is a pain in the ass in c++O3.
*/
class SafeStream
{
public:
/** @param[in] stream is the stream to protect from concurrent access. */
SafeStream(std::ostream & stream) : lock_taken(false), _output(stream) {}
virtual ~SafeStream() {};
/** Manipulator: type used to begin a session. */
struct Begin {};
/** A static instance of Begin to avoid instantiating one for each session start */
static const Begin begin;
/** Manipulator: type used to end a session. */
struct End {};
/** A static instance of End to avoid instantiating one for each session stop. */
static const End end;
/** The insertion operator.
*
* @tparam T If Begin or End, start or end a session.
* If any other type, append to the stream using operator <<.
* @param[in] ti The object to be output or a manipulator.
*/
template<class T>
SafeStream & operator<< (const T & ti);
private:
/** Open session */
virtual void openSession() {}
/** Close session */
virtual void closeSession() {}
/** Start a session. */
void start() {
lock();
openSession();
}
/** End the current session. */
void stop() {
closeSession();
unlock();
}
/** Lock the stream */
void lock() {
_mutex.lock();
lock_taken = true;
}
/** Unlock the stream */
void unlock() {
assert(lock_taken);
lock_taken = false;
_mutex.unlock();
}
/** The mutex state, for debug purpose only. */
bool lock_taken;
/** The stream mutex*/
std::mutex _mutex;
/** The concurrency access protected stream. */
std::ostream & _output;
};
const SafeStream::Begin SafeStream::begin;
const SafeStream::End SafeStream::end;
/** Add a token to stream. */
template<class T>
SafeStream & SafeStream::operator<< (const T & ti) {
assert(lock_taken);
_output << ti;
return *this;
}
/** Start a session.
*
* Will block if is a session is already started.
*/
template<>
SafeStream & SafeStream::operator<< <SafeStream::Begin> (const SafeStream::Begin &) {
start();
return *this;
}
/** Stop the current session. */
template<>
SafeStream & SafeStream::operator<< <SafeStream::End> (const SafeStream::End &) {
stop();
return *this;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2020 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "size_tiered_compaction_strategy.hh"
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
namespace sstables {
size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options(const std::map<sstring, sstring>& options) {
using namespace cql3::statements;
auto tmp_value = compaction_strategy_impl::get_value(options, MIN_SSTABLE_SIZE_KEY);
min_sstable_size = property_definitions::to_long(MIN_SSTABLE_SIZE_KEY, tmp_value, DEFAULT_MIN_SSTABLE_SIZE);
tmp_value = compaction_strategy_impl::get_value(options, BUCKET_LOW_KEY);
bucket_low = property_definitions::to_double(BUCKET_LOW_KEY, tmp_value, DEFAULT_BUCKET_LOW);
tmp_value = compaction_strategy_impl::get_value(options, BUCKET_HIGH_KEY);
bucket_high = property_definitions::to_double(BUCKET_HIGH_KEY, tmp_value, DEFAULT_BUCKET_HIGH);
tmp_value = compaction_strategy_impl::get_value(options, COLD_READS_TO_OMIT_KEY);
cold_reads_to_omit = property_definitions::to_double(COLD_READS_TO_OMIT_KEY, tmp_value, DEFAULT_COLD_READS_TO_OMIT);
}
size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options() {
min_sstable_size = DEFAULT_MIN_SSTABLE_SIZE;
bucket_low = DEFAULT_BUCKET_LOW;
bucket_high = DEFAULT_BUCKET_HIGH;
cold_reads_to_omit = DEFAULT_COLD_READS_TO_OMIT;
}
std::vector<std::pair<sstables::shared_sstable, uint64_t>>
size_tiered_compaction_strategy::create_sstable_and_length_pairs(const std::vector<sstables::shared_sstable>& sstables) {
std::vector<std::pair<sstables::shared_sstable, uint64_t>> sstable_length_pairs;
sstable_length_pairs.reserve(sstables.size());
for(auto& sstable : sstables) {
auto sstable_size = sstable->data_size();
assert(sstable_size != 0);
sstable_length_pairs.emplace_back(sstable, sstable_size);
}
return sstable_length_pairs;
}
std::vector<std::vector<sstables::shared_sstable>>
size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables, size_tiered_compaction_strategy_options options) {
// sstables sorted by size of its data file.
auto sorted_sstables = create_sstable_and_length_pairs(sstables);
std::sort(sorted_sstables.begin(), sorted_sstables.end(), [] (auto& i, auto& j) {
return i.second < j.second;
});
using bucket_type = std::vector<sstables::shared_sstable>;
std::vector<bucket_type> bucket_list;
std::vector<size_t> bucket_average_size_list;
for (auto& pair : sorted_sstables) {
size_t size = pair.second;
// look for a bucket containing similar-sized files:
// group in the same bucket if it's w/in 50% of the average for this bucket,
// or this file and the bucket are all considered "small" (less than `minSSTableSize`)
if (!bucket_list.empty()) {
// FIXME: rename old_average_size since it's being assigned below
auto& old_average_size = bucket_average_size_list.back();
if ((size > (old_average_size * options.bucket_low) && size < (old_average_size * options.bucket_high)) ||
(size < options.min_sstable_size && old_average_size < options.min_sstable_size)) {
auto& bucket = bucket_list.back();
size_t total_size = bucket.size() * old_average_size;
size_t new_average_size = (total_size + size) / (bucket.size() + 1);
bucket.push_back(pair.first);
old_average_size = new_average_size;
continue;
}
}
// no similar bucket found; put it in a new one
bucket_type new_bucket = {pair.first};
bucket_list.push_back(std::move(new_bucket));
bucket_average_size_list.push_back(size);
}
return bucket_list;
}
std::vector<std::vector<sstables::shared_sstable>>
size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables) const {
return get_buckets(sstables, _options);
}
std::vector<sstables::shared_sstable>
size_tiered_compaction_strategy::most_interesting_bucket(std::vector<std::vector<sstables::shared_sstable>> buckets,
unsigned min_threshold, unsigned max_threshold)
{
std::vector<std::pair<std::vector<sstables::shared_sstable>, uint64_t>> pruned_buckets_and_hotness;
pruned_buckets_and_hotness.reserve(buckets.size());
// FIXME: add support to get hotness for each bucket.
for (auto& bucket : buckets) {
// FIXME: the coldest sstables will be trimmed to meet the threshold, so we must add support to this feature
// by converting SizeTieredCompactionStrategy::trimToThresholdWithHotness.
// By the time being, we will only compact buckets that meet the threshold.
bucket.resize(std::min(bucket.size(), size_t(max_threshold)));
if (is_bucket_interesting(bucket, min_threshold)) {
auto avg = avg_size(bucket);
pruned_buckets_and_hotness.push_back({ std::move(bucket), avg });
}
}
if (pruned_buckets_and_hotness.empty()) {
return std::vector<sstables::shared_sstable>();
}
// NOTE: Compacting smallest sstables first, located at the beginning of the sorted vector.
auto& min = *std::min_element(pruned_buckets_and_hotness.begin(), pruned_buckets_and_hotness.end(), [] (auto& i, auto& j) {
// FIXME: ignoring hotness by the time being.
return i.second < j.second;
});
auto hottest = std::move(min.first);
return hottest;
}
compaction_descriptor
size_tiered_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) {
// make local copies so they can't be changed out from under us mid-method
int min_threshold = cfs.min_compaction_threshold();
int max_threshold = cfs.schema()->max_compaction_threshold();
auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds();
// TODO: Add support to filter cold sstables (for reference: SizeTieredCompactionStrategy::filterColdSSTables).
auto buckets = get_buckets(candidates);
if (is_any_bucket_interesting(buckets, min_threshold)) {
std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), min_threshold, max_threshold);
return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority());
}
// If we are not enforcing min_threshold explicitly, try any pair of SStables in the same tier.
if (!cfs.compaction_enforce_min_threshold() && is_any_bucket_interesting(buckets, 2)) {
std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), 2, max_threshold);
return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority());
}
// if there is no sstable to compact in standard way, try compacting single sstable whose droppable tombstone
// ratio is greater than threshold.
// prefer oldest sstables from biggest size tiers because they will be easier to satisfy conditions for
// tombstone purge, i.e. less likely to shadow even older data.
for (auto&& sstables : buckets | boost::adaptors::reversed) {
// filter out sstables which droppable tombstone ratio isn't greater than the defined threshold.
auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool {
return !worth_dropping_tombstones(sst, gc_before);
});
sstables.erase(e, sstables.end());
if (sstables.empty()) {
continue;
}
// find oldest sstable from current tier
auto it = std::min_element(sstables.begin(), sstables.end(), [] (auto& i, auto& j) {
return i->get_stats_metadata().min_timestamp < j->get_stats_metadata().min_timestamp;
});
return sstables::compaction_descriptor({ *it }, cfs.get_sstable_set(), service::get_local_compaction_priority());
}
return sstables::compaction_descriptor();
}
int64_t size_tiered_compaction_strategy::estimated_pending_compactions(const std::vector<sstables::shared_sstable>& sstables,
int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) {
int64_t n = 0;
for (auto& bucket : get_buckets(sstables, options)) {
if (bucket.size() >= size_t(min_threshold)) {
n += std::ceil(double(bucket.size()) / max_threshold);
}
}
return n;
}
int64_t size_tiered_compaction_strategy::estimated_pending_compactions(column_family& cf) const {
int min_threshold = cf.min_compaction_threshold();
int max_threshold = cf.schema()->max_compaction_threshold();
std::vector<sstables::shared_sstable> sstables;
sstables.reserve(cf.sstables_count());
for (auto all_sstables = cf.get_sstables(); auto& entry : *all_sstables) {
sstables.push_back(entry);
}
return estimated_pending_compactions(sstables, min_threshold, max_threshold, _options);
}
std::vector<sstables::shared_sstable>
size_tiered_compaction_strategy::most_interesting_bucket(const std::vector<sstables::shared_sstable>& candidates,
int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) {
size_tiered_compaction_strategy cs(options);
auto buckets = cs.get_buckets(candidates);
std::vector<sstables::shared_sstable> most_interesting = cs.most_interesting_bucket(std::move(buckets),
min_threshold, max_threshold);
return most_interesting;
}
compaction_descriptor
size_tiered_compaction_strategy::get_reshaping_job(std::vector<shared_sstable> input, schema_ptr schema, const ::io_priority_class& iop, reshape_mode mode)
{
size_t offstrategy_threshold = std::max(schema->min_compaction_threshold(), 4);
size_t max_sstables = std::max(schema->max_compaction_threshold(), int(offstrategy_threshold));
if (mode == reshape_mode::relaxed) {
offstrategy_threshold = max_sstables;
}
for (auto& bucket : get_buckets(input)) {
if (bucket.size() >= offstrategy_threshold) {
// reshape job can work on #max_sstables sstables at once, so by reshaping sstables with the smallest tokens first,
// token contiguity is preserved iff sstables are disjoint.
if (bucket.size() > max_sstables) {
std::partial_sort(bucket.begin(), bucket.begin() + max_sstables, bucket.end(), [&schema](const sstables::shared_sstable& a, const sstables::shared_sstable& b) {
return a->get_first_decorated_key().tri_compare(*schema, b->get_first_decorated_key()) <= 0;
});
bucket.resize(max_sstables);
}
compaction_descriptor desc(std::move(bucket), std::optional<sstables::sstable_set>(), iop);
desc.options = compaction_options::make_reshape();
return desc;
}
}
return compaction_descriptor();
}
}
<commit_msg>compaction: size_tiered_compaction_strategy: get_buckets: rename old_average_size to bucket_average_size<commit_after>/*
* Copyright (C) 2020 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "size_tiered_compaction_strategy.hh"
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
namespace sstables {
size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options(const std::map<sstring, sstring>& options) {
using namespace cql3::statements;
auto tmp_value = compaction_strategy_impl::get_value(options, MIN_SSTABLE_SIZE_KEY);
min_sstable_size = property_definitions::to_long(MIN_SSTABLE_SIZE_KEY, tmp_value, DEFAULT_MIN_SSTABLE_SIZE);
tmp_value = compaction_strategy_impl::get_value(options, BUCKET_LOW_KEY);
bucket_low = property_definitions::to_double(BUCKET_LOW_KEY, tmp_value, DEFAULT_BUCKET_LOW);
tmp_value = compaction_strategy_impl::get_value(options, BUCKET_HIGH_KEY);
bucket_high = property_definitions::to_double(BUCKET_HIGH_KEY, tmp_value, DEFAULT_BUCKET_HIGH);
tmp_value = compaction_strategy_impl::get_value(options, COLD_READS_TO_OMIT_KEY);
cold_reads_to_omit = property_definitions::to_double(COLD_READS_TO_OMIT_KEY, tmp_value, DEFAULT_COLD_READS_TO_OMIT);
}
size_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options() {
min_sstable_size = DEFAULT_MIN_SSTABLE_SIZE;
bucket_low = DEFAULT_BUCKET_LOW;
bucket_high = DEFAULT_BUCKET_HIGH;
cold_reads_to_omit = DEFAULT_COLD_READS_TO_OMIT;
}
std::vector<std::pair<sstables::shared_sstable, uint64_t>>
size_tiered_compaction_strategy::create_sstable_and_length_pairs(const std::vector<sstables::shared_sstable>& sstables) {
std::vector<std::pair<sstables::shared_sstable, uint64_t>> sstable_length_pairs;
sstable_length_pairs.reserve(sstables.size());
for(auto& sstable : sstables) {
auto sstable_size = sstable->data_size();
assert(sstable_size != 0);
sstable_length_pairs.emplace_back(sstable, sstable_size);
}
return sstable_length_pairs;
}
std::vector<std::vector<sstables::shared_sstable>>
size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables, size_tiered_compaction_strategy_options options) {
// sstables sorted by size of its data file.
auto sorted_sstables = create_sstable_and_length_pairs(sstables);
std::sort(sorted_sstables.begin(), sorted_sstables.end(), [] (auto& i, auto& j) {
return i.second < j.second;
});
using bucket_type = std::vector<sstables::shared_sstable>;
std::vector<bucket_type> bucket_list;
std::vector<size_t> bucket_average_size_list;
for (auto& pair : sorted_sstables) {
size_t size = pair.second;
// look for a bucket containing similar-sized files:
// group in the same bucket if it's w/in 50% of the average for this bucket,
// or this file and the bucket are all considered "small" (less than `minSSTableSize`)
if (!bucket_list.empty()) {
auto& bucket_average_size = bucket_average_size_list.back();
if ((size > (bucket_average_size * options.bucket_low) && size < (bucket_average_size * options.bucket_high)) ||
(size < options.min_sstable_size && bucket_average_size < options.min_sstable_size)) {
auto& bucket = bucket_list.back();
size_t total_size = bucket.size() * bucket_average_size;
size_t new_average_size = (total_size + size) / (bucket.size() + 1);
bucket.push_back(pair.first);
bucket_average_size = new_average_size;
continue;
}
}
// no similar bucket found; put it in a new one
bucket_type new_bucket = {pair.first};
bucket_list.push_back(std::move(new_bucket));
bucket_average_size_list.push_back(size);
}
return bucket_list;
}
std::vector<std::vector<sstables::shared_sstable>>
size_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables) const {
return get_buckets(sstables, _options);
}
std::vector<sstables::shared_sstable>
size_tiered_compaction_strategy::most_interesting_bucket(std::vector<std::vector<sstables::shared_sstable>> buckets,
unsigned min_threshold, unsigned max_threshold)
{
std::vector<std::pair<std::vector<sstables::shared_sstable>, uint64_t>> pruned_buckets_and_hotness;
pruned_buckets_and_hotness.reserve(buckets.size());
// FIXME: add support to get hotness for each bucket.
for (auto& bucket : buckets) {
// FIXME: the coldest sstables will be trimmed to meet the threshold, so we must add support to this feature
// by converting SizeTieredCompactionStrategy::trimToThresholdWithHotness.
// By the time being, we will only compact buckets that meet the threshold.
bucket.resize(std::min(bucket.size(), size_t(max_threshold)));
if (is_bucket_interesting(bucket, min_threshold)) {
auto avg = avg_size(bucket);
pruned_buckets_and_hotness.push_back({ std::move(bucket), avg });
}
}
if (pruned_buckets_and_hotness.empty()) {
return std::vector<sstables::shared_sstable>();
}
// NOTE: Compacting smallest sstables first, located at the beginning of the sorted vector.
auto& min = *std::min_element(pruned_buckets_and_hotness.begin(), pruned_buckets_and_hotness.end(), [] (auto& i, auto& j) {
// FIXME: ignoring hotness by the time being.
return i.second < j.second;
});
auto hottest = std::move(min.first);
return hottest;
}
compaction_descriptor
size_tiered_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) {
// make local copies so they can't be changed out from under us mid-method
int min_threshold = cfs.min_compaction_threshold();
int max_threshold = cfs.schema()->max_compaction_threshold();
auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds();
// TODO: Add support to filter cold sstables (for reference: SizeTieredCompactionStrategy::filterColdSSTables).
auto buckets = get_buckets(candidates);
if (is_any_bucket_interesting(buckets, min_threshold)) {
std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), min_threshold, max_threshold);
return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority());
}
// If we are not enforcing min_threshold explicitly, try any pair of SStables in the same tier.
if (!cfs.compaction_enforce_min_threshold() && is_any_bucket_interesting(buckets, 2)) {
std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), 2, max_threshold);
return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority());
}
// if there is no sstable to compact in standard way, try compacting single sstable whose droppable tombstone
// ratio is greater than threshold.
// prefer oldest sstables from biggest size tiers because they will be easier to satisfy conditions for
// tombstone purge, i.e. less likely to shadow even older data.
for (auto&& sstables : buckets | boost::adaptors::reversed) {
// filter out sstables which droppable tombstone ratio isn't greater than the defined threshold.
auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool {
return !worth_dropping_tombstones(sst, gc_before);
});
sstables.erase(e, sstables.end());
if (sstables.empty()) {
continue;
}
// find oldest sstable from current tier
auto it = std::min_element(sstables.begin(), sstables.end(), [] (auto& i, auto& j) {
return i->get_stats_metadata().min_timestamp < j->get_stats_metadata().min_timestamp;
});
return sstables::compaction_descriptor({ *it }, cfs.get_sstable_set(), service::get_local_compaction_priority());
}
return sstables::compaction_descriptor();
}
int64_t size_tiered_compaction_strategy::estimated_pending_compactions(const std::vector<sstables::shared_sstable>& sstables,
int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) {
int64_t n = 0;
for (auto& bucket : get_buckets(sstables, options)) {
if (bucket.size() >= size_t(min_threshold)) {
n += std::ceil(double(bucket.size()) / max_threshold);
}
}
return n;
}
int64_t size_tiered_compaction_strategy::estimated_pending_compactions(column_family& cf) const {
int min_threshold = cf.min_compaction_threshold();
int max_threshold = cf.schema()->max_compaction_threshold();
std::vector<sstables::shared_sstable> sstables;
sstables.reserve(cf.sstables_count());
for (auto all_sstables = cf.get_sstables(); auto& entry : *all_sstables) {
sstables.push_back(entry);
}
return estimated_pending_compactions(sstables, min_threshold, max_threshold, _options);
}
std::vector<sstables::shared_sstable>
size_tiered_compaction_strategy::most_interesting_bucket(const std::vector<sstables::shared_sstable>& candidates,
int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) {
size_tiered_compaction_strategy cs(options);
auto buckets = cs.get_buckets(candidates);
std::vector<sstables::shared_sstable> most_interesting = cs.most_interesting_bucket(std::move(buckets),
min_threshold, max_threshold);
return most_interesting;
}
compaction_descriptor
size_tiered_compaction_strategy::get_reshaping_job(std::vector<shared_sstable> input, schema_ptr schema, const ::io_priority_class& iop, reshape_mode mode)
{
size_t offstrategy_threshold = std::max(schema->min_compaction_threshold(), 4);
size_t max_sstables = std::max(schema->max_compaction_threshold(), int(offstrategy_threshold));
if (mode == reshape_mode::relaxed) {
offstrategy_threshold = max_sstables;
}
for (auto& bucket : get_buckets(input)) {
if (bucket.size() >= offstrategy_threshold) {
// reshape job can work on #max_sstables sstables at once, so by reshaping sstables with the smallest tokens first,
// token contiguity is preserved iff sstables are disjoint.
if (bucket.size() > max_sstables) {
std::partial_sort(bucket.begin(), bucket.begin() + max_sstables, bucket.end(), [&schema](const sstables::shared_sstable& a, const sstables::shared_sstable& b) {
return a->get_first_decorated_key().tri_compare(*schema, b->get_first_decorated_key()) <= 0;
});
bucket.resize(max_sstables);
}
compaction_descriptor desc(std::move(bucket), std::optional<sstables::sstable_set>(), iop);
desc.options = compaction_options::make_reshape();
return desc;
}
}
return compaction_descriptor();
}
}
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_MDIVIDE_LEFT_TRI_HPP
#define STAN_MATH_PRIM_MAT_FUN_MDIVIDE_LEFT_TRI_HPP
#include <boost/math/tools/promotion.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/promote_common.hpp>
#include <stan/math/prim/mat/err/check_multiplicable.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
namespace stan {
namespace math {
/**
* Returns the solution of the system Ax=b when A is triangular
* @param A Triangular matrix. Specify upper or lower with TriView
* being Eigen::Upper or Eigen::Lower.
* @param b Right hand side matrix or vector.
* @return x = A^-1 b, solution of the linear system.
* @throws std::domain_error if A is not square or the rows of b don't
* match the size of A.
*/
template <int TriView, typename T1, typename T2, int R1, int C1, int R2, int C2>
inline Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type,
R1, C2>
mdivide_left_tri(const Eigen::Matrix<T1, R1, C1> &A,
const Eigen::Matrix<T2, R2, C2> &b) {
check_square("mdivide_left_tri", "A", A);
check_multiplicable("mdivide_left_tri", "A", A, "b", b);
return promote_common<Eigen::Matrix<T1, R1, C1>, Eigen::Matrix<T2, R1, C1> >(
A)
.template triangularView<TriView>()
.solve(
promote_common<Eigen::Matrix<T1, R2, C2>, Eigen::Matrix<T2, R2, C2> >(
b));
}
/**
* Returns the solution of the system Ax=b when A is triangular and b=I.
* @param A Triangular matrix. Specify upper or lower with TriView
* being Eigen::Upper or Eigen::Lower.
* @return x = A^-1 .
* @throws std::domain_error if A is not square
*/
template <int TriView, typename T, int R1, int C1>
inline Eigen::Matrix<T, R1, C1> mdivide_left_tri(
const Eigen::Matrix<T, R1, C1> &A) {
check_square("mdivide_left_tri", "A", A);
int n = A.rows();
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> b;
b.setIdentity(n, n);
A.template triangularView<TriView>().solveInPlace(b);
return b;
}
} // namespace math
} // namespace stan
#endif
<commit_msg>mdivide prim<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_MDIVIDE_LEFT_TRI_HPP
#define STAN_MATH_PRIM_MAT_FUN_MDIVIDE_LEFT_TRI_HPP
#include <boost/math/tools/promotion.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/promote_common.hpp>
#include <stan/math/prim/mat/err/check_multiplicable.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
#ifdef STAN_OPENCL
#include <stan/math/opencl/opencl_context.hpp>
#include <stan/math/opencl/multiply.hpp>
#include <stan/math/opencl/lower_tri_inverse.hpp>
#include <stan/math/opencl/transpose.hpp>
#include <stan/math/opencl/copy.hpp>
#endif
namespace stan {
namespace math {
/**
* Returns the solution of the system Ax=b when A is triangular
* @param A Triangular matrix. Specify upper or lower with TriView
* being Eigen::Upper or Eigen::Lower.
* @param b Right hand side matrix or vector.
* @return x = A^-1 b, solution of the linear system.
* @throws std::domain_error if A is not square or the rows of b don't
* match the size of A.
*/
template <int TriView, typename T1, typename T2, int R1, int C1, int R2, int C2>
inline Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type,
R1, C2>
mdivide_left_tri(const Eigen::Matrix<T1, R1, C1> &A,
const Eigen::Matrix<T2, R2, C2> &b) {
check_square("mdivide_left_tri", "A", A);
check_multiplicable("mdivide_left_tri", "A", A, "b", b);
return promote_common<Eigen::Matrix<T1, R1, C1>, Eigen::Matrix<T2, R1, C1> >(
A)
.template triangularView<TriView>()
.solve(
promote_common<Eigen::Matrix<T1, R2, C2>, Eigen::Matrix<T2, R2, C2> >(
b));
}
/**
* Returns the solution of the system Ax=b when A is triangular and b=I.
* @param A Triangular matrix. Specify upper or lower with TriView
* being Eigen::Upper or Eigen::Lower.
* @return x = A^-1 .
* @throws std::domain_error if A is not square
*/
template <int TriView, typename T, int R1, int C1>
inline Eigen::Matrix<T, R1, C1> mdivide_left_tri(
const Eigen::Matrix<T, R1, C1> &A) {
check_square("mdivide_left_tri", "A", A);
int n = A.rows();
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> b;
b.setIdentity(n, n);
A.template triangularView<TriView>().solveInPlace(b);
return b;
}
#ifdef STAN_OPENCL
/**
* Returns the solution of the system Ax=b when A is triangular
* @param A Triangular matrix. Specify upper or lower with TriView
* being Eigen::Upper or Eigen::Lower.
* @param b Right hand side matrix or vector.
* @return x = A^-1 b, solution of the linear system.
* @throws std::domain_error if A is not square or the rows of b don't
* match the size of A.
*/
template <int TriView, int R1, int C1, int R2, int C2>
inline Eigen::Matrix<double, R1, C2>
mdivide_left_tri(const Eigen::Matrix<double, R1, C1> &A,
const Eigen::Matrix<double, R2, C2> &b) {
check_square("mdivide_left_tri", "A", A);
check_multiplicable("mdivide_left_tri", "A", A, "b", b);
if (A.rows() >=
opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer) {
matrix_cl A_cl(A);
matrix_cl b_cl(b);
matrix_cl A_inv_cl(A.rows(), A.cols());
if (TriView == Eigen::Lower) {
A_inv_cl = lower_triangular_inverse(A_cl);
} else {
A_inv_cl = transpose(lower_triangular_inverse(transpose(A_cl)));
}
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> C(A.rows(),
A.cols());
auto C_cl = A_inv_cl * b_cl;
copy(C, C_cl); // NOLINT
return C;
} else {
return promote_common<Eigen::Matrix<double, R1, C1>, Eigen::Matrix<double, R1, C1> >(
A)
.template triangularView<TriView>()
.solve(
promote_common<Eigen::Matrix<double, R2, C2>, Eigen::Matrix<double, R2, C2> >(
b));
}
}
/**
* Returns the solution of the system Ax=b when A is triangular and b=I.
* @param A Triangular matrix. Specify upper or lower with TriView
* being Eigen::Upper or Eigen::Lower.
* @return x = A^-1 .
* @note Because OpenCL only works on doubles there are two
* <code>mdivide_left_tri(A)</code> functions. One that works on doubles
* (this one) and another that works on all other types.
* @throws std::domain_error if A is not square
*/
template <int TriView, int R1, int C1>
inline Eigen::Matrix<double, R1, C1> mdivide_left_tri(
const Eigen::Matrix<double, R1, C1> &A) {
check_square("mdivide_left_tri", "A", A);
if (A.rows() >=
opencl_context.tuning_opts().lower_tri_inverse_size_worth_transfer) {
matrix_cl A_cl(A);
matrix_cl A_inv_cl(A.rows(), A.cols());
if (TriView == Eigen::Lower) {
A_inv_cl = lower_triangular_inverse(A_cl);
} else {
//TODO: Should we create an upper_triangular_inverse instea?
// in terms of performance this is fine
A_inv_cl = transpose(lower_triangular_inverse(transpose(A_cl)));
}
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> A_inv(A.rows(),
A.cols());
copy(A_inv, A_inv_cl); // NOLINT
return A_inv;
} else {
int n = A.rows();
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> b;
b.setIdentity(n, n);
A.template triangularView<TriView>().solveInPlace(b);
return b;
}
}
#endif
} // namespace math
} // namespace stan
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/external/gtest.h>
#include <aws/core/utils/Outcome.h>
#include <aws/core/auth/AWSAuthSignerProvider.h>
#include <aws/custom-service/PetStoreClient.h>
#include <aws/custom-service/model/CreatePetRequest.h>
#include <aws/custom-service/model/GetPetRequest.h>
#include <aws/custom-service/model/GetPetsRequest.h>
using namespace Aws::Auth;
using namespace Custom::PetStore;
using namespace Custom::PetStore::Model;
namespace
{
static const char ALLOCATION_TAG[] = "CustomServicePetStoreTest";
// This custom AuthSignerProvider always returns NullSigner.
class CustomAuthSignerProvider : public Aws::Auth::AWSAuthSignerProvider
{
public:
CustomAuthSignerProvider() : m_defaultSigner(Aws::MakeShared<Aws::Client::AWSNullSigner>(ALLOCATION_TAG)) {}
std::shared_ptr<Aws::Client::AWSAuthSigner> GetSigner(const Aws::String& signerName) const override
{
AWS_UNREFERENCED_PARAM(signerName);
return m_defaultSigner;
}
private:
std::shared_ptr<Aws::Client::AWSAuthSigner> m_defaultSigner;
};
class CustomServicePetStoreTest : public ::testing::Test
{
public:
PetStoreClient client;
};
// Test the PetStore specific operations, PetStore is an example provided by API Gateway:
// https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-from-example-console.html
// The resources of PetStore is constant and will not be changed even though we call CreatePet successfully:
// [{ "id": 1, "type": "dog", "price": 249.99 },
// { "id": 2, "type": "cat", "price": 124.99 },
// { "id": 3, "type": "fish", "price": 0.99 }]
TEST_F(CustomServicePetStoreTest, TestPetStoreOperations)
{
// Test CreatePetRequest
CreatePetRequest createPetRequest;
NewPet newPet;
newPet.SetType(PetType::bird);
newPet.SetPrice(9.99);
createPetRequest.SetNewPet(newPet);
auto createPetOutcome = client.CreatePet(createPetRequest);
ASSERT_TRUE(createPetOutcome.IsSuccess());
// Test GetPetRequest
GetPetRequest getPetRequest;
getPetRequest.SetPetId(1);
auto getPetOutcome = client.GetPet(getPetRequest);
ASSERT_TRUE(getPetOutcome.IsSuccess());
ASSERT_EQ("dog", getPetOutcome.GetResult().GetPet().GetType());
ASSERT_EQ(249.99, getPetOutcome.GetResult().GetPet().GetPrice());
// Test GetPetsRequest
GetPetsRequest getPetsRequest;
auto getPetsOutcome = client.GetPets(getPetsRequest);
ASSERT_TRUE(getPetsOutcome.IsSuccess());
auto pets = getPetsOutcome.GetResult().GetPets();
ASSERT_EQ(3u, pets.size());
auto pet = pets[1];
ASSERT_EQ(2 , pet.GetId());
ASSERT_EQ("cat", pet.GetType());
ASSERT_EQ(124.99, pet.GetPrice());
}
TEST_F(CustomServicePetStoreTest, TestCustomSignerProvider)
{
// GetPetsRequest doesn't need signer anyway, we just test the interface to make use of custom signer provider in class constructor here.
std::shared_ptr<Aws::Auth::AWSAuthSignerProvider> customSignerProvider = Aws::MakeShared<CustomAuthSignerProvider>(ALLOCATION_TAG);
auto clientWithCustomSigner = Aws::MakeShared<PetStoreClient>(ALLOCATION_TAG, customSignerProvider);
GetPetsRequest getPetsRequest;
auto getPetsOutcome = client.GetPets(getPetsRequest);
ASSERT_TRUE(getPetsOutcome.IsSuccess());
ASSERT_EQ(3u, getPetsOutcome.GetResult().GetPets().size());
}
}
<commit_msg>Add AddSigner for CustomAuthSignerProvider in custom service integration tests<commit_after>/*
* Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/external/gtest.h>
#include <aws/core/utils/Outcome.h>
#include <aws/core/auth/AWSAuthSignerProvider.h>
#include <aws/custom-service/PetStoreClient.h>
#include <aws/custom-service/model/CreatePetRequest.h>
#include <aws/custom-service/model/GetPetRequest.h>
#include <aws/custom-service/model/GetPetsRequest.h>
using namespace Aws::Auth;
using namespace Custom::PetStore;
using namespace Custom::PetStore::Model;
namespace
{
static const char ALLOCATION_TAG[] = "CustomServicePetStoreTest";
// This custom AuthSignerProvider always returns NullSigner.
class CustomAuthSignerProvider : public Aws::Auth::AWSAuthSignerProvider
{
public:
CustomAuthSignerProvider() : m_defaultSigner(Aws::MakeShared<Aws::Client::AWSNullSigner>(ALLOCATION_TAG)) {}
std::shared_ptr<Aws::Client::AWSAuthSigner> GetSigner(const Aws::String& signerName) const override
{
AWS_UNREFERENCED_PARAM(signerName);
return m_defaultSigner;
}
void AddSigner(std::shared_ptr<Aws::Client::AWSAuthSigner>&)
{
// no-op
}
private:
std::shared_ptr<Aws::Client::AWSAuthSigner> m_defaultSigner;
};
class CustomServicePetStoreTest : public ::testing::Test
{
public:
PetStoreClient client;
};
// Test the PetStore specific operations, PetStore is an example provided by API Gateway:
// https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-from-example-console.html
// The resources of PetStore is constant and will not be changed even though we call CreatePet successfully:
// [{ "id": 1, "type": "dog", "price": 249.99 },
// { "id": 2, "type": "cat", "price": 124.99 },
// { "id": 3, "type": "fish", "price": 0.99 }]
TEST_F(CustomServicePetStoreTest, TestPetStoreOperations)
{
// Test CreatePetRequest
CreatePetRequest createPetRequest;
NewPet newPet;
newPet.SetType(PetType::bird);
newPet.SetPrice(9.99);
createPetRequest.SetNewPet(newPet);
auto createPetOutcome = client.CreatePet(createPetRequest);
ASSERT_TRUE(createPetOutcome.IsSuccess());
// Test GetPetRequest
GetPetRequest getPetRequest;
getPetRequest.SetPetId(1);
auto getPetOutcome = client.GetPet(getPetRequest);
ASSERT_TRUE(getPetOutcome.IsSuccess());
ASSERT_EQ("dog", getPetOutcome.GetResult().GetPet().GetType());
ASSERT_EQ(249.99, getPetOutcome.GetResult().GetPet().GetPrice());
// Test GetPetsRequest
GetPetsRequest getPetsRequest;
auto getPetsOutcome = client.GetPets(getPetsRequest);
ASSERT_TRUE(getPetsOutcome.IsSuccess());
auto pets = getPetsOutcome.GetResult().GetPets();
ASSERT_EQ(3u, pets.size());
auto pet = pets[1];
ASSERT_EQ(2 , pet.GetId());
ASSERT_EQ("cat", pet.GetType());
ASSERT_EQ(124.99, pet.GetPrice());
}
TEST_F(CustomServicePetStoreTest, TestCustomSignerProvider)
{
// GetPetsRequest doesn't need signer anyway, we just test the interface to make use of custom signer provider in class constructor here.
std::shared_ptr<Aws::Auth::AWSAuthSignerProvider> customSignerProvider = Aws::MakeShared<CustomAuthSignerProvider>(ALLOCATION_TAG);
auto clientWithCustomSigner = Aws::MakeShared<PetStoreClient>(ALLOCATION_TAG, customSignerProvider);
GetPetsRequest getPetsRequest;
auto getPetsOutcome = client.GetPets(getPetsRequest);
ASSERT_TRUE(getPetsOutcome.IsSuccess());
ASSERT_EQ(3u, getPetsOutcome.GetResult().GetPets().size());
}
}
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "maemoremotecopyfacility.h"
#include "maemoglobal.h"
#include <QtCore/QDir>
#include <utils/ssh/sshconnection.h>
#include <utils/ssh/sshremoteprocessrunner.h>
using namespace Utils;
namespace Qt4ProjectManager {
namespace Internal {
MaemoRemoteCopyFacility::MaemoRemoteCopyFacility(QObject *parent) :
QObject(parent), m_isCopying(false)
{
}
MaemoRemoteCopyFacility::~MaemoRemoteCopyFacility() {}
void MaemoRemoteCopyFacility::copyFiles(const SshConnection::Ptr &connection,
const QList<MaemoDeployable> &deployables, const QString &mountPoint)
{
Q_ASSERT(connection->state() == SshConnection::Connected);
Q_ASSERT(!m_isCopying);
m_deployables = deployables;
m_mountPoint = mountPoint;
m_copyRunner = SshRemoteProcessRunner::create(connection);
connect(m_copyRunner.data(), SIGNAL(connectionError(Utils::SshError)),
SLOT(handleConnectionError()));
connect(m_copyRunner.data(), SIGNAL(processOutputAvailable(QByteArray)),
SLOT(handleRemoteStdout(QByteArray)));
connect(m_copyRunner.data(),
SIGNAL(processErrorOutputAvailable(QByteArray)),
SLOT(handleRemoteStderr(QByteArray)));
connect(m_copyRunner.data(), SIGNAL(processClosed(int)),
SLOT(handleCopyFinished(int)));
m_isCopying = true;
copyNextFile();
}
void MaemoRemoteCopyFacility::cancel()
{
Q_ASSERT(m_isCopying);
SshRemoteProcessRunner::Ptr killProcess
= SshRemoteProcessRunner::create(m_copyRunner->connection());
killProcess->run("pkill cp");
setFinished();
}
void MaemoRemoteCopyFacility::handleConnectionError()
{
const QString errMsg = m_copyRunner->connection()->errorString();
setFinished();
emit finished(tr("Connection failed: %1").arg(errMsg));
}
void MaemoRemoteCopyFacility::handleRemoteStdout(const QByteArray &output)
{
emit stdoutData(QString::fromUtf8(output));
}
void MaemoRemoteCopyFacility::handleRemoteStderr(const QByteArray &output)
{
emit stderrData(QString::fromUtf8(output));
}
void MaemoRemoteCopyFacility::handleCopyFinished(int exitStatus)
{
if (!m_isCopying)
return;
if (exitStatus != SshRemoteProcess::ExitedNormally
|| m_copyRunner->process()->exitCode() != 0) {
setFinished();
emit finished(tr("Error: Copy command failed."));
} else {
emit fileCopied(m_deployables.takeFirst());
copyNextFile();
}
}
void MaemoRemoteCopyFacility::copyNextFile()
{
Q_ASSERT(m_isCopying);
if (m_deployables.isEmpty()) {
setFinished();
emit finished();
return;
}
const MaemoDeployable &d = m_deployables.first();
QString sourceFilePath = m_mountPoint;
#ifdef Q_OS_WIN
const QString localFilePath = QDir::fromNativeSeparators(d.localFilePath);
sourceFilePath += QLatin1Char('/') + localFilePath.at(0).toLower()
+ localFilePath.mid(2);
#else
sourceFilePath += d.localFilePath;
#endif
QString command = QString::fromLatin1("%1 cp -r %2 %3")
.arg(MaemoGlobal::remoteSudo(m_copyRunner->connection()->connectionParameters().userName),
sourceFilePath, d.remoteDir + QLatin1Char('/'));
emit progress(tr("Copying file '%1' to directory '%2' on the device...")
.arg(d.localFilePath, d.remoteDir));
m_copyRunner->run(command.toUtf8());
}
void MaemoRemoteCopyFacility::setFinished()
{
disconnect(m_copyRunner.data(), 0, this, 0);
m_copyRunner.clear();
m_deployables.clear();
m_isCopying = false;
}
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Maemo: Manually create directories when deploying without packaging.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "maemoremotecopyfacility.h"
#include "maemoglobal.h"
#include <QtCore/QDir>
#include <utils/ssh/sshconnection.h>
#include <utils/ssh/sshremoteprocessrunner.h>
using namespace Utils;
namespace Qt4ProjectManager {
namespace Internal {
MaemoRemoteCopyFacility::MaemoRemoteCopyFacility(QObject *parent) :
QObject(parent), m_isCopying(false)
{
}
MaemoRemoteCopyFacility::~MaemoRemoteCopyFacility() {}
void MaemoRemoteCopyFacility::copyFiles(const SshConnection::Ptr &connection,
const QList<MaemoDeployable> &deployables, const QString &mountPoint)
{
Q_ASSERT(connection->state() == SshConnection::Connected);
Q_ASSERT(!m_isCopying);
m_deployables = deployables;
m_mountPoint = mountPoint;
m_copyRunner = SshRemoteProcessRunner::create(connection);
connect(m_copyRunner.data(), SIGNAL(connectionError(Utils::SshError)),
SLOT(handleConnectionError()));
connect(m_copyRunner.data(), SIGNAL(processOutputAvailable(QByteArray)),
SLOT(handleRemoteStdout(QByteArray)));
connect(m_copyRunner.data(),
SIGNAL(processErrorOutputAvailable(QByteArray)),
SLOT(handleRemoteStderr(QByteArray)));
connect(m_copyRunner.data(), SIGNAL(processClosed(int)),
SLOT(handleCopyFinished(int)));
m_isCopying = true;
copyNextFile();
}
void MaemoRemoteCopyFacility::cancel()
{
Q_ASSERT(m_isCopying);
SshRemoteProcessRunner::Ptr killProcess
= SshRemoteProcessRunner::create(m_copyRunner->connection());
killProcess->run("pkill cp");
setFinished();
}
void MaemoRemoteCopyFacility::handleConnectionError()
{
const QString errMsg = m_copyRunner->connection()->errorString();
setFinished();
emit finished(tr("Connection failed: %1").arg(errMsg));
}
void MaemoRemoteCopyFacility::handleRemoteStdout(const QByteArray &output)
{
emit stdoutData(QString::fromUtf8(output));
}
void MaemoRemoteCopyFacility::handleRemoteStderr(const QByteArray &output)
{
emit stderrData(QString::fromUtf8(output));
}
void MaemoRemoteCopyFacility::handleCopyFinished(int exitStatus)
{
if (!m_isCopying)
return;
if (exitStatus != SshRemoteProcess::ExitedNormally
|| m_copyRunner->process()->exitCode() != 0) {
setFinished();
emit finished(tr("Error: Copy command failed."));
} else {
emit fileCopied(m_deployables.takeFirst());
copyNextFile();
}
}
void MaemoRemoteCopyFacility::copyNextFile()
{
Q_ASSERT(m_isCopying);
if (m_deployables.isEmpty()) {
setFinished();
emit finished();
return;
}
const MaemoDeployable &d = m_deployables.first();
QString sourceFilePath = m_mountPoint;
#ifdef Q_OS_WIN
const QString localFilePath = QDir::fromNativeSeparators(d.localFilePath);
sourceFilePath += QLatin1Char('/') + localFilePath.at(0).toLower()
+ localFilePath.mid(2);
#else
sourceFilePath += d.localFilePath;
#endif
QString command = QString::fromLatin1("%1 mkdir -p %3 && %1 cp -r %2 %3")
.arg(MaemoGlobal::remoteSudo(m_copyRunner->connection()->connectionParameters().userName),
sourceFilePath, d.remoteDir);
emit progress(tr("Copying file '%1' to directory '%2' on the device...")
.arg(d.localFilePath, d.remoteDir));
m_copyRunner->run(command.toUtf8());
}
void MaemoRemoteCopyFacility::setFinished()
{
disconnect(m_copyRunner.data(), 0, this, 0);
m_copyRunner.clear();
m_deployables.clear();
m_isCopying = false;
}
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Kaveh Vahedipour
////////////////////////////////////////////////////////////////////////////////
#include "Inception.h"
#include "Agency/Agent.h"
#include "Agency/GossipCallback.h"
#include "Agency/MeasureCallback.h"
#include "Basics/ConditionLocker.h"
#include "Cluster/ClusterComm.h"
#include <chrono>
#include <numeric>
#include <thread>
using namespace arangodb::consensus;
Inception::Inception() : Thread("Inception"), _agent(nullptr) {}
Inception::Inception(Agent* agent) : Thread("Inception"), _agent(agent) {}
// Shutdown if not already
Inception::~Inception() { shutdown(); }
/// Gossip to others
/// - Get snapshot of gossip peers and agent pool
/// - Create outgoing gossip.
/// - Send to all peers
void Inception::gossip() {
auto s = std::chrono::system_clock::now();
std::chrono::seconds timeout(120);
size_t i = 0;
CONDITION_LOCKER(guard, _cv);
while (!this->isStopping() && !_agent->isStopping()) {
config_t config = _agent->config(); // get a copy of conf
// Build gossip message
query_t out = std::make_shared<Builder>();
out->openObject();
out->add("endpoint", VPackValue(config.endpoint()));
out->add("id", VPackValue(config.id()));
out->add("pool", VPackValue(VPackValueType::Object));
for (auto const& i : config.pool()) {
out->add(i.first, VPackValue(i.second));
}
out->close();
out->close();
std::string path = privApiPrefix + "gossip";
// gossip peers
for (auto const& p : config.gossipPeers()) {
if (p != config.endpoint()) {
std::string clientid = config.id() + std::to_string(i++);
auto hf =
std::make_unique<std::unordered_map<std::string, std::string>>();
arangodb::ClusterComm::instance()->asyncRequest(
clientid, 1, p, rest::RequestType::POST, path,
std::make_shared<std::string>(out->toJson()), hf,
std::make_shared<GossipCallback>(_agent), 1.0, true, 0.5);
}
}
// pool entries
for (auto const& pair : config.pool()) {
if (pair.second != config.endpoint()) {
std::string clientid = config.id() + std::to_string(i++);
auto hf =
std::make_unique<std::unordered_map<std::string, std::string>>();
arangodb::ClusterComm::instance()->asyncRequest(
clientid, 1, pair.second, rest::RequestType::POST, path,
std::make_shared<std::string>(out->toJson()), hf,
std::make_shared<GossipCallback>(_agent), 1.0, true, 0.5);
}
}
// don't panic
_cv.wait(100000);
// Timed out? :(
if ((std::chrono::system_clock::now() - s) > timeout) {
if (config.poolComplete()) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "Stopping active gossipping!";
} else {
LOG_TOPIC(ERR, Logger::AGENCY)
<< "Failed to find complete pool of agents. Giving up!";
}
break;
}
// We're done
if (config.poolComplete()) {
_agent->startConstituent();
break;
}
}
}
// @brief Active agency from persisted database
bool Inception::activeAgencyFromPersistence() {
auto myConfig = _agent->config();
std::string const path = pubApiPrefix + "config";
// Can only be done responcibly, if we are complete
if (myConfig.poolComplete()) {
// Contact hosts on pool in hopes of finding a leader Id
for (auto const& pair : myConfig.pool()) {
if (pair.first != myConfig.id()) {
auto comres = arangodb::ClusterComm::instance()->syncRequest(
myConfig.id(), 1, pair.second, rest::RequestType::GET, path,
std::string(), std::unordered_map<std::string, std::string>(), 1.0);
if (comres->status == CL_COMM_SENT) {
auto body = comres->result->getBodyVelocyPack();
auto theirConfig = body->slice();
std::string leaderId;
// LeaderId in configuration?
try {
leaderId = theirConfig.get("leaderId").copyString();
} catch (std::exception const& e) {
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Failed to get leaderId from" << pair.second << ": "
<< e.what();
}
if (leaderId != "") { // Got leaderId. Let's get do it.
try {
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Found active agency with leader " << leaderId
<< " at endpoint "
<< theirConfig.get("configuration").get(
"pool").get(leaderId).copyString();
} catch (std::exception const& e) {
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Failed to get leaderId from" << pair.second << ": "
<< e.what();
}
auto agency = std::make_shared<Builder>();
agency->openObject();
agency->add("term", theirConfig.get("term"));
agency->add("id", VPackValue(leaderId));
agency->add("active", theirConfig.get("configuration").get("active"));
agency->add("pool", theirConfig.get("configuration").get("pool"));
agency->close();
_agent->notify(agency);
return true;
} else { // No leaderId. Move on.
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Failed to get leaderId from" << pair.second;
}
}
}
}
}
return false;
}
bool Inception::restartingActiveAgent() {
auto myConfig = _agent->config();
std::string const path = pubApiPrefix + "config";
auto s = std::chrono::system_clock::now();
std::chrono::seconds timeout(60);
// Can only be done responcibly, if we are complete
if (myConfig.poolComplete()) {
auto pool = myConfig.pool();
auto active = myConfig.active();
CONDITION_LOCKER(guard, _cv);
while (!this->isStopping() && !_agent->isStopping()) {
active.erase(
std::remove(active.begin(), active.end(), myConfig.id()), active.end());
active.erase(
std::remove(active.begin(), active.end(), ""), active.end());
if (active.empty()) {
return true;
}
for (auto& i : active) {
if (i != myConfig.id() && i != "") {
auto clientId = myConfig.id();
auto comres = arangodb::ClusterComm::instance()->syncRequest(
clientId, 1, pool.at(i), rest::RequestType::GET, path, std::string(),
std::unordered_map<std::string, std::string>(), 2.0);
if (comres->status == CL_COMM_SENT) {
try {
auto theirActive = comres->result->getBodyVelocyPack()->
slice().get("configuration").get("active").toJson();
auto myActive = myConfig.activeToBuilder()->toJson();
if (theirActive != myActive) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "Assumed active RAFT peer and I disagree on active membership."
<< "Administrative intervention needed.";
FATAL_ERROR_EXIT();
return false;
} else {
i = "";
}
} catch (std::exception const& e) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "Assumed active RAFT peer has no active agency list: " << e.what()
<< "Administrative intervention needed.";
FATAL_ERROR_EXIT();
return false;
}
}
}
}
// Timed out? :(
if ((std::chrono::system_clock::now() - s) > timeout) {
if (myConfig.poolComplete()) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "Stopping active gossipping!";
} else {
LOG_TOPIC(ERR, Logger::AGENCY)
<< "Failed to find complete pool of agents. Giving up!";
}
break;
}
_cv.wait(500000);
}
}
return false;
}
inline static int64_t timeStamp() {
using namespace std::chrono;
return duration_cast<microseconds>(
steady_clock::now().time_since_epoch()).count();
}
void Inception::reportIn(std::string const& peerId, uint64_t start) {
MUTEX_LOCKER(lock, _pLock);
_pings.push_back(1.0e-3*(double)(timeStamp()-start));
}
void Inception::reportIn(query_t const& query) {
VPackSlice slice = query->slice();
TRI_ASSERT(slice.isObject());
TRI_ASSERT(slice.hasKey("mean"));
TRI_ASSERT(slice.hasKey("stdev"));
TRI_ASSERT(slice.hasKey("min"));
TRI_ASSERT(slice.hasKey("max"));
MUTEX_LOCKER(lock, _mLock);
_measurements.push_back(
std::vector<double>(
{slice.get("mean").getDouble(), slice.get("stdev").getDouble(),
slice.get("max").getDouble(), slice.get("min").getDouble()} ));
}
bool Inception::estimateRAFTInterval() {
using namespace std::chrono;
std::string path("/_api/agency/config");
auto pool = _agent->config().pool();
auto myid = _agent->id();
for (size_t i = 0; i < 25; ++i) {
for (auto const& peer : pool) {
if (peer.first != myid) {
std::string clientid = peer.first + std::to_string(i);
auto hf =
std::make_unique<std::unordered_map<std::string, std::string>>();
arangodb::ClusterComm::instance()->asyncRequest(
clientid, 1, peer.second, rest::RequestType::GET, path,
std::make_shared<std::string>(), hf,
std::make_shared<MeasureCallback>(this, peer.second, timeStamp()),
2.0, true);
}
}
}
auto s = system_clock::now();
seconds timeout(3);
CONDITION_LOCKER(guard, _cv);
while (true) {
_cv.wait(50000);
{
MUTEX_LOCKER(lock, _pLock);
if (_pings.size() == 25*(pool.size()-1)) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "All pings are in";
break;
}
}
if ((system_clock::now() - s) > timeout) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "Timed out waiting for pings";
break;
}
}
double sum, mean, sq_sum, stdev, mx, mn;
try {
MUTEX_LOCKER(lock, _pLock);
size_t num = _pings.size();
sum = std::accumulate(_pings.begin(), _pings.end(), 0.0);
mean = sum / num;
mx = *std::max_element(_pings.begin(), _pings.end());
mn = *std::min_element(_pings.begin(), _pings.end());
std::transform(_pings.begin(), _pings.end(), _pings.begin(),
std::bind2nd(std::minus<double>(), mean));
sq_sum =
std::inner_product(_pings.begin(), _pings.end(), _pings.begin(), 0.0);
stdev = std::sqrt(sq_sum / num);
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "mean(" << mean << ") stdev(" << stdev<< ")";
} catch (std::exception const& e) {
LOG_TOPIC(WARN, Logger::AGENCY) << e.what();
}
Builder measurement;
measurement.openObject();
measurement.add("mean", VPackValue(mean));
measurement.add("stdev", VPackValue(stdev));
measurement.add("min", VPackValue(mn));
measurement.add("max", VPackValue(mx));
measurement.close();
std::string measjson = measurement.toJson();
path = privApiPrefix + "measure";
for (auto const& peer : pool) {
if (peer.first != myid) {
auto clientId = "1";
auto comres = arangodb::ClusterComm::instance()->syncRequest(
clientId, 1, peer.second, rest::RequestType::POST, path,
measjson, std::unordered_map<std::string, std::string>(), 2.0);
}
}
{
MUTEX_LOCKER(lock, _mLock);
_measurements.push_back(std::vector<double>({mean, stdev, mx, mn}));
}
s = system_clock::now();
while (true) {
_cv.wait(50000);
{
MUTEX_LOCKER(lock, _mLock);
if (_measurements.size() == pool.size()) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "All measurements are in";
break;
}
}
if ((system_clock::now() - s) > timeout) {
LOG_TOPIC(WARN, Logger::AGENCY)
<< "Timed out waiting for other measurements. Auto-adaptation failed!";
return false;
}
}
double maxmean = .0;
double maxstdev = .0;
for (auto const& meas : _measurements) {
if (maxmean < meas[0]) {
maxmean = meas[0];
}
if (maxstdev < meas[1]) {
maxstdev = meas[1];
}
}
LOG_TOPIC(INFO, Logger::AGENCY)
<< "Auto-adapting RAFT timing to: " << 5.*maxmean << " " << 25.*maxmean;
_agent->resetRAFTTimes(5.e-3*maxmean, 25.e-3*maxmean);
return true;
}
// @brief Active agency from persisted database
bool Inception::activeAgencyFromCommandLine() {
return false;
}
// @brief Thread main
void Inception::run() {
// 1. If active agency, do as you're told
if (activeAgencyFromPersistence()) {
_agent->ready(true);
}
// 2. If we think that we used to be active agent
if (!_agent->ready() && restartingActiveAgent()) {
_agent->ready(true);
}
// 3. Else gossip
config_t config = _agent->config();
if (!_agent->ready() && !config.poolComplete()) {
gossip();
}
// 4. If still incomplete bail out :(
config = _agent->config();
if (!_agent->ready() && !config.poolComplete()) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "Failed to build environment for RAFT algorithm. Bailing out!";
FATAL_ERROR_EXIT();
}
estimateRAFTInterval();
_agent->ready(true);
}
// @brief Graceful shutdown
void Inception::beginShutdown() {
Thread::beginShutdown();
CONDITION_LOCKER(guard, _cv);
guard.broadcast();
}
<commit_msg>RAFT timeout estimation output<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Kaveh Vahedipour
////////////////////////////////////////////////////////////////////////////////
#include "Inception.h"
#include "Agency/Agent.h"
#include "Agency/GossipCallback.h"
#include "Agency/MeasureCallback.h"
#include "Basics/ConditionLocker.h"
#include "Cluster/ClusterComm.h"
#include <chrono>
#include <numeric>
#include <thread>
using namespace arangodb::consensus;
Inception::Inception() : Thread("Inception"), _agent(nullptr) {}
Inception::Inception(Agent* agent) : Thread("Inception"), _agent(agent) {}
// Shutdown if not already
Inception::~Inception() { shutdown(); }
/// Gossip to others
/// - Get snapshot of gossip peers and agent pool
/// - Create outgoing gossip.
/// - Send to all peers
void Inception::gossip() {
auto s = std::chrono::system_clock::now();
std::chrono::seconds timeout(120);
size_t i = 0;
CONDITION_LOCKER(guard, _cv);
while (!this->isStopping() && !_agent->isStopping()) {
config_t config = _agent->config(); // get a copy of conf
// Build gossip message
query_t out = std::make_shared<Builder>();
out->openObject();
out->add("endpoint", VPackValue(config.endpoint()));
out->add("id", VPackValue(config.id()));
out->add("pool", VPackValue(VPackValueType::Object));
for (auto const& i : config.pool()) {
out->add(i.first, VPackValue(i.second));
}
out->close();
out->close();
std::string path = privApiPrefix + "gossip";
// gossip peers
for (auto const& p : config.gossipPeers()) {
if (p != config.endpoint()) {
std::string clientid = config.id() + std::to_string(i++);
auto hf =
std::make_unique<std::unordered_map<std::string, std::string>>();
arangodb::ClusterComm::instance()->asyncRequest(
clientid, 1, p, rest::RequestType::POST, path,
std::make_shared<std::string>(out->toJson()), hf,
std::make_shared<GossipCallback>(_agent), 1.0, true, 0.5);
}
}
// pool entries
for (auto const& pair : config.pool()) {
if (pair.second != config.endpoint()) {
std::string clientid = config.id() + std::to_string(i++);
auto hf =
std::make_unique<std::unordered_map<std::string, std::string>>();
arangodb::ClusterComm::instance()->asyncRequest(
clientid, 1, pair.second, rest::RequestType::POST, path,
std::make_shared<std::string>(out->toJson()), hf,
std::make_shared<GossipCallback>(_agent), 1.0, true, 0.5);
}
}
// don't panic
_cv.wait(100000);
// Timed out? :(
if ((std::chrono::system_clock::now() - s) > timeout) {
if (config.poolComplete()) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "Stopping active gossipping!";
} else {
LOG_TOPIC(ERR, Logger::AGENCY)
<< "Failed to find complete pool of agents. Giving up!";
}
break;
}
// We're done
if (config.poolComplete()) {
_agent->startConstituent();
break;
}
}
}
// @brief Active agency from persisted database
bool Inception::activeAgencyFromPersistence() {
auto myConfig = _agent->config();
std::string const path = pubApiPrefix + "config";
// Can only be done responcibly, if we are complete
if (myConfig.poolComplete()) {
// Contact hosts on pool in hopes of finding a leader Id
for (auto const& pair : myConfig.pool()) {
if (pair.first != myConfig.id()) {
auto comres = arangodb::ClusterComm::instance()->syncRequest(
myConfig.id(), 1, pair.second, rest::RequestType::GET, path,
std::string(), std::unordered_map<std::string, std::string>(), 1.0);
if (comres->status == CL_COMM_SENT) {
auto body = comres->result->getBodyVelocyPack();
auto theirConfig = body->slice();
std::string leaderId;
// LeaderId in configuration?
try {
leaderId = theirConfig.get("leaderId").copyString();
} catch (std::exception const& e) {
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Failed to get leaderId from" << pair.second << ": "
<< e.what();
}
if (leaderId != "") { // Got leaderId. Let's get do it.
try {
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Found active agency with leader " << leaderId
<< " at endpoint "
<< theirConfig.get("configuration").get(
"pool").get(leaderId).copyString();
} catch (std::exception const& e) {
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Failed to get leaderId from" << pair.second << ": "
<< e.what();
}
auto agency = std::make_shared<Builder>();
agency->openObject();
agency->add("term", theirConfig.get("term"));
agency->add("id", VPackValue(leaderId));
agency->add("active", theirConfig.get("configuration").get("active"));
agency->add("pool", theirConfig.get("configuration").get("pool"));
agency->close();
_agent->notify(agency);
return true;
} else { // No leaderId. Move on.
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "Failed to get leaderId from" << pair.second;
}
}
}
}
}
return false;
}
bool Inception::restartingActiveAgent() {
auto myConfig = _agent->config();
std::string const path = pubApiPrefix + "config";
auto s = std::chrono::system_clock::now();
std::chrono::seconds timeout(60);
// Can only be done responcibly, if we are complete
if (myConfig.poolComplete()) {
auto pool = myConfig.pool();
auto active = myConfig.active();
CONDITION_LOCKER(guard, _cv);
while (!this->isStopping() && !_agent->isStopping()) {
active.erase(
std::remove(active.begin(), active.end(), myConfig.id()), active.end());
active.erase(
std::remove(active.begin(), active.end(), ""), active.end());
if (active.empty()) {
return true;
}
for (auto& i : active) {
if (i != myConfig.id() && i != "") {
auto clientId = myConfig.id();
auto comres = arangodb::ClusterComm::instance()->syncRequest(
clientId, 1, pool.at(i), rest::RequestType::GET, path, std::string(),
std::unordered_map<std::string, std::string>(), 2.0);
if (comres->status == CL_COMM_SENT) {
try {
auto theirActive = comres->result->getBodyVelocyPack()->
slice().get("configuration").get("active").toJson();
auto myActive = myConfig.activeToBuilder()->toJson();
if (theirActive != myActive) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "Assumed active RAFT peer and I disagree on active membership."
<< "Administrative intervention needed.";
FATAL_ERROR_EXIT();
return false;
} else {
i = "";
}
} catch (std::exception const& e) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "Assumed active RAFT peer has no active agency list: " << e.what()
<< "Administrative intervention needed.";
FATAL_ERROR_EXIT();
return false;
}
}
}
}
// Timed out? :(
if ((std::chrono::system_clock::now() - s) > timeout) {
if (myConfig.poolComplete()) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "Stopping active gossipping!";
} else {
LOG_TOPIC(ERR, Logger::AGENCY)
<< "Failed to find complete pool of agents. Giving up!";
}
break;
}
_cv.wait(500000);
}
}
return false;
}
inline static int64_t timeStamp() {
using namespace std::chrono;
return duration_cast<microseconds>(
steady_clock::now().time_since_epoch()).count();
}
void Inception::reportIn(std::string const& peerId, uint64_t start) {
MUTEX_LOCKER(lock, _pLock);
_pings.push_back(1.0e-3*(double)(timeStamp()-start));
}
void Inception::reportIn(query_t const& query) {
VPackSlice slice = query->slice();
TRI_ASSERT(slice.isObject());
TRI_ASSERT(slice.hasKey("mean"));
TRI_ASSERT(slice.hasKey("stdev"));
TRI_ASSERT(slice.hasKey("min"));
TRI_ASSERT(slice.hasKey("max"));
MUTEX_LOCKER(lock, _mLock);
_measurements.push_back(
std::vector<double>(
{slice.get("mean").getDouble(), slice.get("stdev").getDouble(),
slice.get("max").getDouble(), slice.get("min").getDouble()} ));
}
bool Inception::estimateRAFTInterval() {
using namespace std::chrono;
std::string path("/_api/agency/config");
auto pool = _agent->config().pool();
auto myid = _agent->id();
for (size_t i = 0; i < 25; ++i) {
for (auto const& peer : pool) {
if (peer.first != myid) {
std::string clientid = peer.first + std::to_string(i);
auto hf =
std::make_unique<std::unordered_map<std::string, std::string>>();
arangodb::ClusterComm::instance()->asyncRequest(
clientid, 1, peer.second, rest::RequestType::GET, path,
std::make_shared<std::string>(), hf,
std::make_shared<MeasureCallback>(this, peer.second, timeStamp()),
2.0, true);
}
}
}
auto s = system_clock::now();
seconds timeout(3);
CONDITION_LOCKER(guard, _cv);
while (true) {
_cv.wait(50000);
{
MUTEX_LOCKER(lock, _pLock);
if (_pings.size() == 25*(pool.size()-1)) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "All pings are in";
break;
}
}
if ((system_clock::now() - s) > timeout) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "Timed out waiting for pings";
break;
}
}
double sum, mean, sq_sum, stdev, mx, mn;
try {
MUTEX_LOCKER(lock, _pLock);
size_t num = _pings.size();
sum = std::accumulate(_pings.begin(), _pings.end(), 0.0);
mean = sum / num;
mx = *std::max_element(_pings.begin(), _pings.end());
mn = *std::min_element(_pings.begin(), _pings.end());
std::transform(_pings.begin(), _pings.end(), _pings.begin(),
std::bind2nd(std::minus<double>(), mean));
sq_sum =
std::inner_product(_pings.begin(), _pings.end(), _pings.begin(), 0.0);
stdev = std::sqrt(sq_sum / num);
LOG_TOPIC(DEBUG, Logger::AGENCY)
<< "mean(" << mean << ") stdev(" << stdev<< ")";
} catch (std::exception const& e) {
LOG_TOPIC(WARN, Logger::AGENCY) << e.what();
}
Builder measurement;
measurement.openObject();
measurement.add("mean", VPackValue(mean));
measurement.add("stdev", VPackValue(stdev));
measurement.add("min", VPackValue(mn));
measurement.add("max", VPackValue(mx));
measurement.close();
std::string measjson = measurement.toJson();
path = privApiPrefix + "measure";
for (auto const& peer : pool) {
if (peer.first != myid) {
auto clientId = "1";
auto comres = arangodb::ClusterComm::instance()->syncRequest(
clientId, 1, peer.second, rest::RequestType::POST, path,
measjson, std::unordered_map<std::string, std::string>(), 2.0);
}
}
{
MUTEX_LOCKER(lock, _mLock);
_measurements.push_back(std::vector<double>({mean, stdev, mx, mn}));
}
s = system_clock::now();
while (true) {
_cv.wait(50000);
{
MUTEX_LOCKER(lock, _mLock);
if (_measurements.size() == pool.size()) {
LOG_TOPIC(DEBUG, Logger::AGENCY) << "All measurements are in";
break;
}
}
if ((system_clock::now() - s) > timeout) {
LOG_TOPIC(WARN, Logger::AGENCY)
<< "Timed out waiting for other measurements. Auto-adaptation failed! Will stick to command line arguments";
return false;
}
}
double maxmean = .0;
double maxstdev = .0;
for (auto const& meas : _measurements) {
if (maxmean < meas[0]) {
maxmean = meas[0];
}
if (maxstdev < meas[1]) {
maxstdev = meas[1];
}
}
LOG_TOPIC(INFO, Logger::AGENCY)
<< "Auto-adapting RAFT timing to: " << 5.*maxmean << " " << 25.*maxmean;
_agent->resetRAFTTimes(5.e-3*maxmean, 25.e-3*maxmean);
return true;
}
// @brief Active agency from persisted database
bool Inception::activeAgencyFromCommandLine() {
return false;
}
// @brief Thread main
void Inception::run() {
// 1. If active agency, do as you're told
if (activeAgencyFromPersistence()) {
_agent->ready(true);
}
// 2. If we think that we used to be active agent
if (!_agent->ready() && restartingActiveAgent()) {
_agent->ready(true);
}
// 3. Else gossip
config_t config = _agent->config();
if (!_agent->ready() && !config.poolComplete()) {
gossip();
}
// 4. If still incomplete bail out :(
config = _agent->config();
if (!_agent->ready() && !config.poolComplete()) {
LOG_TOPIC(FATAL, Logger::AGENCY)
<< "Failed to build environment for RAFT algorithm. Bailing out!";
FATAL_ERROR_EXIT();
}
estimateRAFTInterval();
_agent->ready(true);
}
// @brief Graceful shutdown
void Inception::beginShutdown() {
Thread::beginShutdown();
CONDITION_LOCKER(guard, _cv);
guard.broadcast();
}
<|endoftext|>
|
<commit_before>#include <thread>
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <iostream>
using namespace std;
std::mutex mut;
std::condition_variable cond;
bool go = false;
typedef char buffer[4096*2];
using atom = std::atomic<size_t>;
typedef void (*fnc_type)(size_t, size_t);
atom lock_instr_test;
struct {
atom v1;
atom v2;
} __attribute__((aligned(64))) test_same_line;
struct test_different_line {
buffer back;
atom value;
buffer front;
};
test_different_line *lines;
void test_single_add(size_t id, size_t nrun) {
for (size_t i = 0; i < nrun; i++) {
lock_instr_test.fetch_add(1, std::memory_order_relaxed);
}
}
void test_single_cas(size_t id, size_t nrun) {
size_t dummy;
for (size_t i = 0; i < nrun; i++) {
while (!lock_instr_test.compare_exchange_weak(dummy,
dummy+1,
std::memory_order_relaxed,
std::memory_order_relaxed))
{}
}
}
void test_mfence(size_t id, size_t nrun) {
for (size_t i = 0; i < nrun; i++) {
std::atomic_thread_fence(std::memory_order_seq_cst);
}
}
void test_same_line_f(size_t id, size_t nrun) {
atom *a;
if (id % 2) {
a = &test_same_line.v1;
}
else {
a = &test_same_line.v2;
}
for (size_t i = 0; i < nrun; i++) {
a->fetch_add(1, std::memory_order_relaxed);
}
}
void test_different_line_f(size_t id, size_t nrun) {
atom *a = &lines[id].value;
for (size_t i = 0; i < nrun; i++) {
a->fetch_add(1, std::memory_order_relaxed);
}
}
void time_threads(size_t ntesters, size_t nrun, fnc_type op, std::string name) {
std::thread *ths = new std::thread[ntesters];
for (size_t i = 0; i < ntesters; i++) {
ths[i] = std::thread([&]() {
{
std::unique_lock<std::mutex> lck(mut);
cond.wait(lck, [&]() {return go; });
}
op(i, nrun);
});
}
std::this_thread::sleep_for(std::chrono::milliseconds(5));
auto cclock = std::chrono::steady_clock::now();
go = true;
cond.notify_all();
for (size_t i = 0; i < ntesters; i++) {
ths[i].join();
}
auto diff = std::chrono::steady_clock::now() - cclock;
auto td = chrono::duration_cast<chrono::milliseconds>(diff).count() - 5;
double tdiff = ((double)td / 1000.0);
auto nthread = ntesters;
auto total_elem = (nthread * nrun); //* 2 since popping them all
auto elempt = total_elem / tdiff;
auto elemptpt = elempt / nthread;
cout << "Took " << tdiff
<< " seconds for " << nthread << " threads and "
<< nrun << " elements per thread" << endl
<< "This amounts to " << elemptpt
<< " operations per thread per second "
<< "for " << name << endl << endl;
delete[] ths;
}
int main() {
size_t num_test = 3e7;
for (size_t i = 1; i <= 10; i++) {
time_threads(i, num_test, test_single_add, "same add");
time_threads(i, num_test, test_single_cas, "same cas");
time_threads(i, num_test, test_mfence, "mfence");
time_threads(i, num_test, test_same_line_f, "same line");
lines = new test_different_line[i+1];
time_threads(i, num_test, test_different_line_f, "different_lines");
delete[] lines;
cout << endl << endl;
}
return 0;
}
<commit_msg>adding nanoseconds per element<commit_after>#include <thread>
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <iostream>
using namespace std;
std::mutex mut;
std::condition_variable cond;
bool go = false;
typedef char buffer[4096*2];
using atom = std::atomic<size_t>;
typedef void (*fnc_type)(size_t, size_t);
atom lock_instr_test;
struct {
atom v1;
atom v2;
} __attribute__((aligned(64))) test_same_line;
struct test_different_line {
buffer back;
atom value;
buffer front;
};
test_different_line *lines;
void test_single_add(size_t id, size_t nrun) {
for (size_t i = 0; i < nrun; i++) {
lock_instr_test.fetch_add(1, std::memory_order_relaxed);
}
}
void test_single_cas(size_t id, size_t nrun) {
size_t dummy;
for (size_t i = 0; i < nrun; i++) {
while (!lock_instr_test.compare_exchange_weak(dummy,
dummy+1,
std::memory_order_relaxed,
std::memory_order_relaxed))
{}
}
}
void test_mfence(size_t id, size_t nrun) {
for (size_t i = 0; i < nrun; i++) {
std::atomic_thread_fence(std::memory_order_seq_cst);
}
}
void test_same_line_f(size_t id, size_t nrun) {
atom *a;
if (id % 2) {
a = &test_same_line.v1;
}
else {
a = &test_same_line.v2;
}
for (size_t i = 0; i < nrun; i++) {
a->fetch_add(1, std::memory_order_relaxed);
}
}
void test_different_line_f(size_t id, size_t nrun) {
atom *a = &lines[id].value;
for (size_t i = 0; i < nrun; i++) {
a->fetch_add(1, std::memory_order_relaxed);
}
}
void time_threads(size_t ntesters, size_t nrun, fnc_type op, std::string name) {
std::thread *ths = new std::thread[ntesters];
for (size_t i = 0; i < ntesters; i++) {
ths[i] = std::thread([&]() {
{
std::unique_lock<std::mutex> lck(mut);
cond.wait(lck, [&]() {return go; });
}
op(i, nrun);
});
}
std::this_thread::sleep_for(std::chrono::milliseconds(5));
auto cclock = std::chrono::steady_clock::now();
go = true;
cond.notify_all();
for (size_t i = 0; i < ntesters; i++) {
ths[i].join();
}
auto diff = std::chrono::steady_clock::now() - cclock;
auto td = chrono::duration_cast<chrono::milliseconds>(diff).count();
double tdiff = ((double)td / 1000.0);
auto nthread = ntesters;
auto total_elem = (nthread * nrun); //* 2 since popping them all
auto elempt = total_elem / tdiff;
auto elemptpt = elempt / nthread;
auto ns_per_elem = 1e9 * tdiff / nrun;
cout << "Took " << tdiff
<< " seconds for " << nthread << " threads and "
<< nrun << " elements per thread" << endl
<< "This amounts to " << ns_per_elem
<< " nanoseconds per operation "
<< "for " << name << endl << endl;
delete[] ths;
}
int main() {
size_t num_test = 1e8;
for (size_t i = 1; i <= 10; i++) {
time_threads(i, num_test, test_single_add, "same add");
time_threads(i, num_test, test_single_cas, "same cas");
time_threads(i, num_test, test_mfence, "mfence");
time_threads(i, num_test, test_same_line_f, "same line");
lines = new test_different_line[i+1];
time_threads(i, num_test, test_different_line_f, "different_lines");
delete[] lines;
cout << endl << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "Scaly.h"
namespace scaly {
_Page::_Page(size_t size)
: currentPage(this), nextPage(0), previousPage(0), size(size), extendingPage(0) {
reset();
}
_Page** _Page::getLastExtensionPageLocation() {
return ((_Page**) ((char*) this + size)) - 1;
}
_Page* _Page::next() {
if (nextPage == 0)
nextPage = allocateNextPage(this);
else
nextPage->reset();
return nextPage;
}
_Page* _Page::previous() {
return previousPage;
}
void* _Page::operator new(size_t size, void* location) {
return location;
}
void* _Page::allocateObject(size_t size) {
if (this != currentPage) {
// We're already known to be full, so we delegate to the current page
void* newObject = currentPage->allocateObject(size);
// Possibly our current page was also full so we propagate back the new current page
_Page* allocatingPage = ((Object*)newObject)->getPage();
if ((allocatingPage != currentPage) && (allocatingPage->getSize() == _Page::pageSize))
currentPage = allocatingPage;
return newObject;
}
// Try to allocate from ourselves
void* nextLocation = align((char*) nextObject + size);
if (nextLocation <= (void*) nextExtensionPageLocation) {
void* location = nextObject;
nextObject = nextLocation;
return location;
}
// So the space did not fit.
// Check first whether we need an ordinary extension
if ((_Page**)nextObject == nextExtensionPageLocation) {
// Allocate an extension page with default size
_Page* defaultExtensionPage = allocateExtensionPage(1);
// Make it our new current
currentPage = defaultExtensionPage;
// Try again with the new extension page
return defaultExtensionPage->allocateObject(size);
}
// Make the extension page with the desired size.
_Page* extensionPage = allocateExtensionPage(size);
// If it was not an oversize page
if (extensionPage->getSize() <= _Page::pageSize) {
// If we are pretty full, make it the new current page
if (((void*)nextObject) >= (void*)nextExtensionPageLocation )
currentPage = extensionPage;
}
return extensionPage->allocateObject(size);
}
_Page* _Page::allocateExtensionPage(size_t size) {
size_t grossSize = size + sizeof(_Page) + sizeof(_Page**);
if (grossSize < pageSize) {
grossSize = pageSize;
}
else if (grossSize > pageSize) {
grossSize += _alignment;
grossSize &= ~(_alignment - 1);
}
_Page* pageLocation = allocate(grossSize);
if (!pageLocation)
return 0;
*nextExtensionPageLocation = pageLocation;
nextExtensionPageLocation--;
_Page* extensionPage = new (pageLocation) _Page(grossSize);
extensionPage->extendingPage = this;
return extensionPage;
}
_Page* _Page::allocateNextPage(_Page* previousPage) {
void* pageLocation = allocate(pageSize);
if (!pageLocation)
return 0;
_Page* nextPage = new (pageLocation) _Page(pageSize);
nextPage->previousPage = previousPage;
return nextPage;
}
void _Page::reset() {
nextExtensionPageLocation = getLastExtensionPageLocation();
*nextExtensionPageLocation = 0;
nextObject = align((char*) this + sizeof(_Page));
}
_Page* _Page::allocate(size_t size) {
void* pageLocation;
if (posix_memalign(&pageLocation, pageSize, size))
return 0;
else
return (_Page*)pageLocation;
}
bool _Page::extend(void* address, size_t size) {
if (!size)
size = 1;
void* nextLocation = align((char*) address + size);
if (nextLocation == (void*) nextObject)
return true;
if (nextLocation < nextObject)
return false;
if (nextLocation >= (void*) nextExtensionPageLocation)
return false;
nextObject = nextLocation;
return true;
}
void _Page::deallocate() {
// Find the end of the stack Page chain
_Page* page = this;
while (page)
if (page->nextPage == 0)
break;
else
page = page->nextPage;
// Deallocate the chain starting from the end
while (page) {
_Page* previousPage = page->previousPage;
page->deallocatePageExtensions();
free(page);
page = previousPage;
}
}
void _Page::deallocatePageExtensions() {
_Page** currentExtensionPosition = this->getLastExtensionPageLocation();
while (currentExtensionPosition > this->nextExtensionPageLocation) {
_Page* currentExtension = *currentExtensionPosition;
if (currentExtension)
currentExtension->deallocate();
currentExtensionPosition--;
}
}
void _Page::reclaimArray(void* address) {
_Page* page = ((Object*)address)->getPage();
page->extendingPage->freeExtensionPage(page);
}
_Page* _Page::getPage(void* address) {
return (_Page*)
(
((intptr_t)address)
& ~(intptr_t)(pageSize - 1));
}
void _Page::freeExtensionPage(_Page* _page) {
// Find the extension Page pointer
_Page** extensionPosition = getLastExtensionPageLocation();
while (extensionPosition > nextExtensionPageLocation) {
if (*extensionPosition == _page)
break;
extensionPosition--;
}
// Shift the remaining array one position up
for (_Page** shiftedPosition = extensionPosition; shiftedPosition > nextExtensionPageLocation; shiftedPosition--)
*shiftedPosition = *(shiftedPosition - 1);
// Make room for one more extension
nextExtensionPageLocation++;
_page->deallocate();
}
size_t _Page::getSize() {
return size;
}
} // namespace
<commit_msg>Page allocation<commit_after>#include "Scaly.h"
namespace scaly {
_Page::_Page(size_t size)
: currentPage(this), nextPage(0), previousPage(0), size(size), extendingPage(0) {
reset();
}
_Page** _Page::getLastExtensionPageLocation() {
// Frome where the ordinary extension page is pointed to
return ((_Page**) ((char*) this + size)) - 1;
}
_Page* _Page::next() {
if (nextPage == 0)
// This frame is new
nextPage = allocateNextPage(this);
else
// We've already been at that frame, we re-use it
nextPage->reset();
return nextPage;
}
_Page* _Page::previous() {
return previousPage;
}
void* _Page::operator new(size_t size, void* location) {
return location;
}
void* _Page::allocateObject(size_t size) {
if (this != currentPage) {
// We're already known to be full, so we delegate to the current page
void* newObject = currentPage->allocateObject(size);
// Possibly our current page was also full so we propagate back the new current page
_Page* allocatingPage = ((Object*)newObject)->getPage();
if ((allocatingPage != currentPage) && (allocatingPage->getSize() == _Page::pageSize))
currentPage = allocatingPage;
return newObject;
}
// Try to allocate from ourselves
void* nextLocation = align((char*) nextObject + size);
if (nextLocation <= (void*) nextExtensionPageLocation) {
void* location = nextObject;
nextObject = nextLocation;
return location;
}
// So the space did not fit.
// Check first whether we need an ordinary extension
size_t grossSize = sizeof(_Page) + size + sizeof(_Page**) + _alignment;
if ((_Page**)nextObject == getLastExtensionPageLocation() || (grossSize < pageSize)) {
// Allocate an extension page with default size
_Page* defaultExtensionPage = allocateExtensionPage(1);
// Make it our new current
currentPage = defaultExtensionPage;
// Try again with the new extension page
return defaultExtensionPage->allocateObject(size);
}
// Make the oversized extension page.
_Page* extensionPage = allocateExtensionPage(size);
return extensionPage->allocateObject(size);
}
_Page* _Page::allocateExtensionPage(size_t size) {
size_t grossSize = sizeof(_Page) + size + sizeof(_Page**) + _alignment;
if (grossSize < pageSize) {
grossSize = pageSize;
}
else if (grossSize > pageSize) {
grossSize += _alignment;
grossSize &= ~(_alignment - 1);
}
_Page* pageLocation = allocate(grossSize);
if (!pageLocation)
return 0;
_Page* extensionPage = new (pageLocation) _Page(grossSize);
if (grossSize > pageSize) {
*nextExtensionPageLocation = pageLocation;
nextExtensionPageLocation--;
}
else {
*getLastExtensionPageLocation() = pageLocation;
}
extensionPage->extendingPage = this;
return extensionPage;
}
_Page* _Page::allocateNextPage(_Page* previousPage) {
void* pageLocation = allocate(pageSize);
if (!pageLocation)
return 0;
_Page* nextPage = new (pageLocation) _Page(pageSize);
nextPage->previousPage = previousPage;
return nextPage;
}
void _Page::reset() {
// Allocate default extension page pointer and initialize it to zero
nextExtensionPageLocation = getLastExtensionPageLocation();
*nextExtensionPageLocation = 0;
nextExtensionPageLocation--;
// Allocate space for the page itself
nextObject = align((char*) this + sizeof(_Page));
}
_Page* _Page::allocate(size_t size) {
void* pageLocation;
if (posix_memalign(&pageLocation, pageSize, size))
return 0;
else
return (_Page*)pageLocation;
}
bool _Page::extend(void* address, size_t size) {
if (!size)
size = 1;
void* nextLocation = align((char*) address + size);
// If nextObject would not change because of the alignment, that's it
if (nextLocation == (void*) nextObject)
return true;
// If nextObject is already higher, other objects were allocated in the meantime
if (nextLocation < nextObject)
return false;
// Now we still have to check whether we still would have space left
if (nextLocation >= (void*) nextExtensionPageLocation)
return false;
// Allocate the extension
nextObject = nextLocation;
return true;
}
void _Page::deallocate() {
// Find the end of the stack Page chain
_Page* page = this;
while (page)
if (page->nextPage == 0)
break;
else
page = page->nextPage;
// Deallocate the chain starting from the end
while (page) {
_Page* prevPage = page->previousPage;
page->deallocatePageExtensions();
free(page);
page = prevPage;
}
}
void _Page::deallocatePageExtensions() {
// Find the end of the extension Page chain
_Page* page = this;
while (page)
if (*(page->getLastExtensionPageLocation()) == 0)
break;
else
page = *(page->getLastExtensionPageLocation());
// Deallocate the extension page chain starting from the end
while (page) {
_Page* prevExtPage = page->extendingPage;
// Deallocate the oversized pages
for (_Page** ppPage = page->getLastExtensionPageLocation(); ppPage > page->nextExtensionPageLocation; ppPage--)
free(*ppPage);
page = prevExtPage;
}
}
void _Page::reclaimArray(void* address) {
_Page* page = ((Object*)address)->getPage();
page->extendingPage->freeExtensionPage(page);
}
_Page* _Page::getPage(void* address) {
return (_Page*)
(
((intptr_t)address)
& ~(intptr_t)(pageSize - 1));
}
void _Page::freeExtensionPage(_Page* _page) {
// Find the extension Page pointer
_Page** extensionPosition = getLastExtensionPageLocation() - 1;
while (extensionPosition > nextExtensionPageLocation) {
if (*extensionPosition == _page)
break;
extensionPosition--;
}
// Shift the remaining array one position up
for (_Page** shiftedPosition = extensionPosition; shiftedPosition > nextExtensionPageLocation; shiftedPosition--)
*shiftedPosition = *(shiftedPosition - 1);
// Make room for one more extension
nextExtensionPageLocation++;
free(_page);
}
size_t _Page::getSize() {
return size;
}
} // namespace
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/ip_filter.hpp"
#include <boost/utility.hpp>
#include "test.hpp"
#include "libtorrent/socket_io.hpp"
/*
Currently this test only tests that the filter can handle
IPv4 addresses. Maybe it should be extended to IPv6 as well,
but the actual code is just a template, so it is probably
pretty safe to assume that as long as it works for IPv4 it
also works for IPv6.
*/
using namespace libtorrent;
template <class Addr>
bool compare(ip_range<Addr> const& lhs
, ip_range<Addr> const& rhs)
{
return lhs.first == rhs.first
&& lhs.last == rhs.last
&& lhs.flags == rhs.flags;
}
#define IP(x) address::from_string(x, ec)
#define IP4(x) address_v4::from_string(x, ec)
void test_rules_invariant(std::vector<ip_range<address_v4> > const& r, ip_filter const& f)
{
typedef std::vector<ip_range<address_v4> >::const_iterator iterator;
TEST_CHECK(!r.empty());
if (r.empty()) return;
error_code ec;
TEST_CHECK(r.front().first == IP("0.0.0.0"));
TEST_CHECK(r.back().last == IP("255.255.255.255"));
iterator i = r.begin();
iterator j = boost::next(i);
for (iterator i(r.begin()), j(boost::next(r.begin()))
, end(r.end()); j != end; ++j, ++i)
{
TEST_CHECK(f.access(i->last) == i->flags);
TEST_CHECK(f.access(j->first) == j->flags);
TEST_CHECK(i->last.to_ulong() + 1 == j->first.to_ulong());
}
}
int test_main()
{
using namespace libtorrent;
std::vector<ip_range<address_v4> > range;
error_code ec;
// **** test joining of ranges at the end ****
ip_range<address_v4> expected1[] =
{
{IP4("0.0.0.0"), IP4("0.255.255.255"), 0}
, {IP4("1.0.0.0"), IP4("3.0.0.0"), ip_filter::blocked}
, {IP4("3.0.0.1"), IP4("255.255.255.255"), 0}
};
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of ranges at the start ****
{
ip_filter f;
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of overlapping ranges at the start ****
{
ip_filter f;
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
f.add_rule(IP("1.0.0.0"), IP("2.4.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of overlapping ranges at the end ****
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.4.0.0"), ip_filter::blocked);
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of multiple overlapping ranges 1 ****
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
f.add_rule(IP("3.0.0.0"), IP("4.0.0.0"), ip_filter::blocked);
f.add_rule(IP("5.0.0.0"), IP("6.0.0.0"), ip_filter::blocked);
f.add_rule(IP("7.0.0.0"), IP("8.0.0.0"), ip_filter::blocked);
f.add_rule(IP("1.0.1.0"), IP("9.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
ip_range<address_v4> expected[] =
{
{IP4("0.0.0.0"), IP4("0.255.255.255"), 0}
, {IP4("1.0.0.0"), IP4("9.0.0.0"), ip_filter::blocked}
, {IP4("9.0.0.1"), IP4("255.255.255.255"), 0}
};
TEST_CHECK(std::equal(range.begin(), range.end(), expected, &compare<address_v4>));
}
// **** test joining of multiple overlapping ranges 2 ****
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
f.add_rule(IP("3.0.0.0"), IP("4.0.0.0"), ip_filter::blocked);
f.add_rule(IP("5.0.0.0"), IP("6.0.0.0"), ip_filter::blocked);
f.add_rule(IP("7.0.0.0"), IP("8.0.0.0"), ip_filter::blocked);
f.add_rule(IP("0.0.1.0"), IP("7.0.4.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
ip_range<address_v4> expected[] =
{
{IP4("0.0.0.0"), IP4("0.0.0.255"), 0}
, {IP4("0.0.1.0"), IP4("8.0.0.0"), ip_filter::blocked}
, {IP4("8.0.0.1"), IP4("255.255.255.255"), 0}
};
TEST_CHECK(std::equal(range.begin(), range.end(), expected, &compare<address_v4>));
}
port_filter pf;
// default contructed port filter should allow any port
TEST_CHECK(pf.access(0) == 0);
TEST_CHECK(pf.access(65535) == 0);
TEST_CHECK(pf.access(6881) == 0);
// block port 100 - 300
pf.add_rule(100, 300, port_filter::blocked);
TEST_CHECK(pf.access(0) == 0);
TEST_CHECK(pf.access(99) == 0);
TEST_CHECK(pf.access(100) == port_filter::blocked);
TEST_CHECK(pf.access(150) == port_filter::blocked);
TEST_CHECK(pf.access(300) == port_filter::blocked);
TEST_CHECK(pf.access(301) == 0);
TEST_CHECK(pf.access(6881) == 0);
TEST_CHECK(pf.access(65535) == 0);
return 0;
}
<commit_msg>extend ip_filter test to include some IPv6<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/ip_filter.hpp"
#include <boost/utility.hpp>
#include "test.hpp"
#include "libtorrent/socket_io.hpp"
/*
Currently this test only tests that the filter can handle
IPv4 addresses. Maybe it should be extended to IPv6 as well,
but the actual code is just a template, so it is probably
pretty safe to assume that as long as it works for IPv4 it
also works for IPv6.
*/
using namespace libtorrent;
template <class Addr>
bool compare(ip_range<Addr> const& lhs
, ip_range<Addr> const& rhs)
{
return lhs.first == rhs.first
&& lhs.last == rhs.last
&& lhs.flags == rhs.flags;
}
#define IP(x) address::from_string(x, ec)
#define IP4(x) address_v4::from_string(x, ec)
#define IP6(x) address_v6::from_string(x, ec)
template <class T>
void test_rules_invariant(std::vector<ip_range<T> > const& r, ip_filter const& f)
{
typedef typename std::vector<ip_range<T> >::const_iterator iterator;
TEST_CHECK(!r.empty());
if (r.empty()) return;
error_code ec;
if (sizeof(r.front().first) == sizeof(address_v4))
{
TEST_CHECK(r.front().first == IP("0.0.0.0"));
TEST_CHECK(r.back().last == IP("255.255.255.255"));
}
else
{
TEST_CHECK(r.front().first == IP("::0"));
TEST_CHECK(r.back().last == IP("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"));
}
iterator i = r.begin();
iterator j = boost::next(i);
for (iterator i(r.begin()), j(boost::next(r.begin()))
, end(r.end()); j != end; ++j, ++i)
{
TEST_CHECK(f.access(i->last) == i->flags);
TEST_CHECK(f.access(j->first) == j->flags);
TEST_CHECK(detail::plus_one(i->last.to_bytes()) == j->first.to_bytes());
}
}
int test_main()
{
using namespace libtorrent;
std::vector<ip_range<address_v4> > range;
error_code ec;
// **** test joining of ranges at the end ****
ip_range<address_v4> expected1[] =
{
{IP4("0.0.0.0"), IP4("0.255.255.255"), 0}
, {IP4("1.0.0.0"), IP4("3.0.0.0"), ip_filter::blocked}
, {IP4("3.0.0.1"), IP4("255.255.255.255"), 0}
};
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of ranges at the start ****
{
ip_filter f;
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of overlapping ranges at the start ****
{
ip_filter f;
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
f.add_rule(IP("1.0.0.0"), IP("2.4.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of overlapping ranges at the end ****
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.4.0.0"), ip_filter::blocked);
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of multiple overlapping ranges 1 ****
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
f.add_rule(IP("3.0.0.0"), IP("4.0.0.0"), ip_filter::blocked);
f.add_rule(IP("5.0.0.0"), IP("6.0.0.0"), ip_filter::blocked);
f.add_rule(IP("7.0.0.0"), IP("8.0.0.0"), ip_filter::blocked);
f.add_rule(IP("1.0.1.0"), IP("9.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
ip_range<address_v4> expected[] =
{
{IP4("0.0.0.0"), IP4("0.255.255.255"), 0}
, {IP4("1.0.0.0"), IP4("9.0.0.0"), ip_filter::blocked}
, {IP4("9.0.0.1"), IP4("255.255.255.255"), 0}
};
TEST_CHECK(std::equal(range.begin(), range.end(), expected, &compare<address_v4>));
}
// **** test joining of multiple overlapping ranges 2 ****
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
f.add_rule(IP("3.0.0.0"), IP("4.0.0.0"), ip_filter::blocked);
f.add_rule(IP("5.0.0.0"), IP("6.0.0.0"), ip_filter::blocked);
f.add_rule(IP("7.0.0.0"), IP("8.0.0.0"), ip_filter::blocked);
f.add_rule(IP("0.0.1.0"), IP("7.0.4.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
ip_range<address_v4> expected[] =
{
{IP4("0.0.0.0"), IP4("0.0.0.255"), 0}
, {IP4("0.0.1.0"), IP4("8.0.0.0"), ip_filter::blocked}
, {IP4("8.0.0.1"), IP4("255.255.255.255"), 0}
};
TEST_CHECK(std::equal(range.begin(), range.end(), expected, &compare<address_v4>));
}
// **** test IPv6 ****
#if TORRENT_USE_IPV6
ip_range<address_v6> expected2[] =
{
{IP6("::0"), IP6("0:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), 0}
, {IP6("1::"), IP6("3::"), ip_filter::blocked}
, {IP6("3::1"), IP6("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), 0}
};
{
ip_filter f;
f.add_rule(IP("2::1"), IP("3::"), ip_filter::blocked);
f.add_rule(IP("1::"), IP("2::"), ip_filter::blocked);
std::vector<ip_range<address_v6> > range;
range = boost::get<1>(f.export_filter());
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected2, &compare<address_v6>));
}
#endif
port_filter pf;
// default contructed port filter should allow any port
TEST_CHECK(pf.access(0) == 0);
TEST_CHECK(pf.access(65535) == 0);
TEST_CHECK(pf.access(6881) == 0);
// block port 100 - 300
pf.add_rule(100, 300, port_filter::blocked);
TEST_CHECK(pf.access(0) == 0);
TEST_CHECK(pf.access(99) == 0);
TEST_CHECK(pf.access(100) == port_filter::blocked);
TEST_CHECK(pf.access(150) == port_filter::blocked);
TEST_CHECK(pf.access(300) == port_filter::blocked);
TEST_CHECK(pf.access(301) == 0);
TEST_CHECK(pf.access(6881) == 0);
TEST_CHECK(pf.access(65535) == 0);
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/ip_filter.hpp"
#include <boost/utility.hpp>
#include "test.hpp"
#include "libtorrent/socket_io.hpp"
/*
Currently this test only tests that the filter can handle
IPv4 addresses. Maybe it should be extended to IPv6 as well,
but the actual code is just a template, so it is probably
pretty safe to assume that as long as it works for IPv4 it
also works for IPv6.
*/
using namespace libtorrent;
template <class Addr>
bool compare(ip_range<Addr> const& lhs
, ip_range<Addr> const& rhs)
{
return lhs.first == rhs.first
&& lhs.last == rhs.last
&& lhs.flags == rhs.flags;
}
#define IP(x) address::from_string(x, ec)
#define IP4(x) address_v4::from_string(x, ec)
void test_rules_invariant(std::vector<ip_range<address_v4> > const& r, ip_filter const& f)
{
typedef std::vector<ip_range<address_v4> >::const_iterator iterator;
TEST_CHECK(!r.empty());
if (r.empty()) return;
error_code ec;
TEST_CHECK(r.front().first == IP("0.0.0.0"));
TEST_CHECK(r.back().last == IP("255.255.255.255"));
iterator i = r.begin();
iterator j = boost::next(i);
for (iterator i(r.begin()), j(boost::next(r.begin()))
, end(r.end()); j != end; ++j, ++i)
{
TEST_CHECK(f.access(i->last) == i->flags);
TEST_CHECK(f.access(j->first) == j->flags);
TEST_CHECK(i->last.to_ulong() + 1 == j->first.to_ulong());
}
}
int test_main()
{
using namespace libtorrent;
std::vector<ip_range<address_v4> > range;
error_code ec;
// **** test joining of ranges at the end ****
ip_range<address_v4> expected1[] =
{
{IP4("0.0.0.0"), IP4("0.255.255.255"), 0}
, {IP4("1.0.0.0"), IP4("3.0.0.0"), ip_filter::blocked}
, {IP4("3.0.0.1"), IP4("255.255.255.255"), 0}
};
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of ranges at the start ****
{
ip_filter f;
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of overlapping ranges at the start ****
{
ip_filter f;
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
f.add_rule(IP("1.0.0.0"), IP("2.4.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of overlapping ranges at the end ****
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.4.0.0"), ip_filter::blocked);
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of multiple overlapping ranges 1 ****
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
f.add_rule(IP("3.0.0.0"), IP("4.0.0.0"), ip_filter::blocked);
f.add_rule(IP("5.0.0.0"), IP("6.0.0.0"), ip_filter::blocked);
f.add_rule(IP("7.0.0.0"), IP("8.0.0.0"), ip_filter::blocked);
f.add_rule(IP("1.0.1.0"), IP("9.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
ip_range<address_v4> expected[] =
{
{IP4("0.0.0.0"), IP4("0.255.255.255"), 0}
, {IP4("1.0.0.0"), IP4("9.0.0.0"), ip_filter::blocked}
, {IP4("9.0.0.1"), IP4("255.255.255.255"), 0}
};
TEST_CHECK(std::equal(range.begin(), range.end(), expected, &compare<address_v4>));
}
// **** test joining of multiple overlapping ranges 2 ****
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
f.add_rule(IP("3.0.0.0"), IP("4.0.0.0"), ip_filter::blocked);
f.add_rule(IP("5.0.0.0"), IP("6.0.0.0"), ip_filter::blocked);
f.add_rule(IP("7.0.0.0"), IP("8.0.0.0"), ip_filter::blocked);
f.add_rule(IP("0.0.1.0"), IP("7.0.4.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
ip_range<address_v4> expected[] =
{
{IP4("0.0.0.0"), IP4("0.0.0.255"), 0}
, {IP4("0.0.1.0"), IP4("8.0.0.0"), ip_filter::blocked}
, {IP4("8.0.0.1"), IP4("255.255.255.255"), 0}
};
TEST_CHECK(std::equal(range.begin(), range.end(), expected, &compare<address_v4>));
}
port_filter pf;
// default contructed port filter should allow any port
TEST_CHECK(pf.access(0) == 0);
TEST_CHECK(pf.access(65535) == 0);
TEST_CHECK(pf.access(6881) == 0);
// block port 100 - 300
pf.add_rule(100, 300, port_filter::blocked);
TEST_CHECK(pf.access(0) == 0);
TEST_CHECK(pf.access(99) == 0);
TEST_CHECK(pf.access(100) == port_filter::blocked);
TEST_CHECK(pf.access(150) == port_filter::blocked);
TEST_CHECK(pf.access(300) == port_filter::blocked);
TEST_CHECK(pf.access(301) == 0);
TEST_CHECK(pf.access(6881) == 0);
TEST_CHECK(pf.access(65535) == 0);
return 0;
}
<commit_msg>extend ip_filter test to include some IPv6<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/ip_filter.hpp"
#include <boost/utility.hpp>
#include "test.hpp"
#include "libtorrent/socket_io.hpp"
/*
Currently this test only tests that the filter can handle
IPv4 addresses. Maybe it should be extended to IPv6 as well,
but the actual code is just a template, so it is probably
pretty safe to assume that as long as it works for IPv4 it
also works for IPv6.
*/
using namespace libtorrent;
template <class Addr>
bool compare(ip_range<Addr> const& lhs
, ip_range<Addr> const& rhs)
{
return lhs.first == rhs.first
&& lhs.last == rhs.last
&& lhs.flags == rhs.flags;
}
#define IP(x) address::from_string(x, ec)
#define IP4(x) address_v4::from_string(x, ec)
#define IP6(x) address_v6::from_string(x, ec)
template <class T>
void test_rules_invariant(std::vector<ip_range<T> > const& r, ip_filter const& f)
{
typedef typename std::vector<ip_range<T> >::const_iterator iterator;
TEST_CHECK(!r.empty());
if (r.empty()) return;
error_code ec;
if (sizeof(r.front().first) == sizeof(address_v4))
{
TEST_CHECK(r.front().first == IP("0.0.0.0"));
TEST_CHECK(r.back().last == IP("255.255.255.255"));
}
else
{
TEST_CHECK(r.front().first == IP("::0"));
TEST_CHECK(r.back().last == IP("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"));
}
iterator i = r.begin();
iterator j = boost::next(i);
for (iterator i(r.begin()), j(boost::next(r.begin()))
, end(r.end()); j != end; ++j, ++i)
{
TEST_CHECK(f.access(i->last) == i->flags);
TEST_CHECK(f.access(j->first) == j->flags);
TEST_CHECK(detail::plus_one(i->last.to_bytes()) == j->first.to_bytes());
}
}
int test_main()
{
using namespace libtorrent;
std::vector<ip_range<address_v4> > range;
error_code ec;
// **** test joining of ranges at the end ****
ip_range<address_v4> expected1[] =
{
{IP4("0.0.0.0"), IP4("0.255.255.255"), 0}
, {IP4("1.0.0.0"), IP4("3.0.0.0"), ip_filter::blocked}
, {IP4("3.0.0.1"), IP4("255.255.255.255"), 0}
};
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of ranges at the start ****
{
ip_filter f;
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of overlapping ranges at the start ****
{
ip_filter f;
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
f.add_rule(IP("1.0.0.0"), IP("2.4.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of overlapping ranges at the end ****
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.4.0.0"), ip_filter::blocked);
f.add_rule(IP("2.0.0.1"), IP("3.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected1, &compare<address_v4>));
}
// **** test joining of multiple overlapping ranges 1 ****
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
f.add_rule(IP("3.0.0.0"), IP("4.0.0.0"), ip_filter::blocked);
f.add_rule(IP("5.0.0.0"), IP("6.0.0.0"), ip_filter::blocked);
f.add_rule(IP("7.0.0.0"), IP("8.0.0.0"), ip_filter::blocked);
f.add_rule(IP("1.0.1.0"), IP("9.0.0.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
ip_range<address_v4> expected[] =
{
{IP4("0.0.0.0"), IP4("0.255.255.255"), 0}
, {IP4("1.0.0.0"), IP4("9.0.0.0"), ip_filter::blocked}
, {IP4("9.0.0.1"), IP4("255.255.255.255"), 0}
};
TEST_CHECK(std::equal(range.begin(), range.end(), expected, &compare<address_v4>));
}
// **** test joining of multiple overlapping ranges 2 ****
{
ip_filter f;
f.add_rule(IP("1.0.0.0"), IP("2.0.0.0"), ip_filter::blocked);
f.add_rule(IP("3.0.0.0"), IP("4.0.0.0"), ip_filter::blocked);
f.add_rule(IP("5.0.0.0"), IP("6.0.0.0"), ip_filter::blocked);
f.add_rule(IP("7.0.0.0"), IP("8.0.0.0"), ip_filter::blocked);
f.add_rule(IP("0.0.1.0"), IP("7.0.4.0"), ip_filter::blocked);
#if TORRENT_USE_IPV6
range = boost::get<0>(f.export_filter());
#else
range = f.export_filter();
#endif
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
ip_range<address_v4> expected[] =
{
{IP4("0.0.0.0"), IP4("0.0.0.255"), 0}
, {IP4("0.0.1.0"), IP4("8.0.0.0"), ip_filter::blocked}
, {IP4("8.0.0.1"), IP4("255.255.255.255"), 0}
};
TEST_CHECK(std::equal(range.begin(), range.end(), expected, &compare<address_v4>));
}
// **** test IPv6 ****
#if TORRENT_USE_IPV6
ip_range<address_v6> expected2[] =
{
{IP6("::0"), IP6("0:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), 0}
, {IP6("1::"), IP6("3::"), ip_filter::blocked}
, {IP6("3::1"), IP6("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), 0}
};
{
ip_filter f;
f.add_rule(IP("2::1"), IP("3::"), ip_filter::blocked);
f.add_rule(IP("1::"), IP("2::"), ip_filter::blocked);
std::vector<ip_range<address_v6> > range;
range = boost::get<1>(f.export_filter());
test_rules_invariant(range, f);
TEST_CHECK(range.size() == 3);
TEST_CHECK(std::equal(range.begin(), range.end(), expected2, &compare<address_v6>));
}
#endif
port_filter pf;
// default contructed port filter should allow any port
TEST_CHECK(pf.access(0) == 0);
TEST_CHECK(pf.access(65535) == 0);
TEST_CHECK(pf.access(6881) == 0);
// block port 100 - 300
pf.add_rule(100, 300, port_filter::blocked);
TEST_CHECK(pf.access(0) == 0);
TEST_CHECK(pf.access(99) == 0);
TEST_CHECK(pf.access(100) == port_filter::blocked);
TEST_CHECK(pf.access(150) == port_filter::blocked);
TEST_CHECK(pf.access(300) == port_filter::blocked);
TEST_CHECK(pf.access(301) == 0);
TEST_CHECK(pf.access(6881) == 0);
TEST_CHECK(pf.access(65535) == 0);
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007, Un Shyam
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include <iostream>
#include "libtorrent/hasher.hpp"
#include "libtorrent/pe_crypto.hpp"
#include "libtorrent/session.hpp"
#include "setup_transfer.hpp"
#include "test.hpp"
#ifndef TORRENT_DISABLE_ENCRYPTION
char const* pe_policy(libtorrent::pe_settings::enc_policy policy)
{
using namespace libtorrent;
if (policy == pe_settings::disabled) return "disabled";
else if (policy == pe_settings::enabled) return "enabled";
else if (policy == pe_settings::forced) return "forced";
return "unknown";
}
void display_pe_settings(libtorrent::pe_settings s)
{
using namespace libtorrent;
fprintf(stderr, "out_enc_policy - %s\tin_enc_policy - %s\n"
, pe_policy(s.out_enc_policy), pe_policy(s.in_enc_policy));
fprintf(stderr, "enc_level - %s\t\tprefer_rc4 - %s\n"
, s.allowed_enc_level == pe_settings::plaintext ? "plaintext"
: s.allowed_enc_level == pe_settings::rc4 ? "rc4"
: s.allowed_enc_level == pe_settings::both ? "both" : "unknown"
, s.prefer_rc4 ? "true": "false");
}
void test_transfer(libtorrent::pe_settings::enc_policy policy,
libtorrent::pe_settings::enc_level level = libtorrent::pe_settings::both,
bool pref_rc4 = false)
{
using namespace libtorrent;
// these are declared before the session objects
// so that they are destructed last. This enables
// the sessions to destruct in parallel
session_proxy p1;
session_proxy p2;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48800, 49000), "0.0.0.0", 0);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49800, 50000), "0.0.0.0", 0);
pe_settings s;
s.out_enc_policy = libtorrent::pe_settings::enabled;
s.in_enc_policy = libtorrent::pe_settings::enabled;
s.allowed_enc_level = pe_settings::both;
ses2.set_pe_settings(s);
s.out_enc_policy = policy;
s.in_enc_policy = policy;
s.allowed_enc_level = level;
s.prefer_rc4 = pref_rc4;
ses1.set_pe_settings(s);
s = ses1.get_pe_settings();
fprintf(stderr, " Session1 \n");
display_pe_settings(s);
s = ses2.get_pe_settings();
fprintf(stderr, " Session2 \n");
display_pe_settings(s);
torrent_handle tor1;
torrent_handle tor2;
using boost::tuples::ignore;
boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0, true, false, true
, "_pe", 16 * 1024, 0, false, 0, true);
fprintf(stderr, "waiting for transfer to complete\n");
for (int i = 0; i < 50; ++i)
{
torrent_status s = tor2.status();
print_alerts(ses1, "ses1");
print_alerts(ses2, "ses2");
if (s.is_seeding) break;
test_sleep(1000);
}
TEST_CHECK(tor2.status().is_seeding);
if (tor2.status().is_seeding) fprintf(stderr, "done\n");
ses1.remove_torrent(tor1);
ses2.remove_torrent(tor2);
// this allows shutting down the sessions in parallel
p1 = ses1.abort();
p2 = ses2.abort();
error_code ec;
remove_all("tmp1_pe", ec);
remove_all("tmp2_pe", ec);
remove_all("tmp3_pe", ec);
}
void test_enc_handler(libtorrent::encryption_handler* a, libtorrent::encryption_handler* b)
{
int repcount = 128;
for (int rep = 0; rep < repcount; ++rep)
{
std::size_t buf_len = rand() % (512 * 1024);
char* buf = new char[buf_len];
char* cmp_buf = new char[buf_len];
std::generate(buf, buf + buf_len, &std::rand);
std::memcpy(cmp_buf, buf, buf_len);
a->encrypt(buf, buf_len);
TEST_CHECK(!std::equal(buf, buf + buf_len, cmp_buf));
b->decrypt(buf, buf_len);
TEST_CHECK(std::equal(buf, buf + buf_len, cmp_buf));
b->encrypt(buf, buf_len);
TEST_CHECK(!std::equal(buf, buf + buf_len, cmp_buf));
a->decrypt(buf, buf_len);
TEST_CHECK(std::equal(buf, buf + buf_len, cmp_buf));
delete[] buf;
delete[] cmp_buf;
}
}
#endif
int test_main()
{
using namespace libtorrent;
#ifndef TORRENT_DISABLE_ENCRYPTION
int repcount = 128;
for (int rep = 0; rep < repcount; ++rep)
{
dh_key_exchange DH1, DH2;
DH1.compute_secret(DH2.get_local_key());
DH2.compute_secret(DH1.get_local_key());
TEST_CHECK(std::equal(DH1.get_secret(), DH1.get_secret() + 96, DH2.get_secret()));
}
dh_key_exchange DH1, DH2;
DH1.compute_secret(DH2.get_local_key());
DH2.compute_secret(DH1.get_local_key());
TEST_CHECK(std::equal(DH1.get_secret(), DH1.get_secret() + 96, DH2.get_secret()));
sha1_hash test1_key = hasher("test1_key",8).final();
sha1_hash test2_key = hasher("test2_key",8).final();
fprintf(stderr, "testing RC4 handler\n");
rc4_handler rc41;
rc41.set_incoming_key(&test2_key[0], 20);
rc41.set_outgoing_key(&test1_key[0], 20);
rc4_handler rc42;
rc42.set_incoming_key(&test1_key[0], 20);
rc42.set_outgoing_key(&test2_key[0], 20);
test_enc_handler(&rc41, &rc42);
test_transfer(pe_settings::disabled);
test_transfer(pe_settings::forced, pe_settings::plaintext);
test_transfer(pe_settings::forced, pe_settings::rc4);
test_transfer(pe_settings::forced, pe_settings::both, false);
test_transfer(pe_settings::forced, pe_settings::both, true);
test_transfer(pe_settings::enabled, pe_settings::plaintext);
test_transfer(pe_settings::enabled, pe_settings::rc4);
test_transfer(pe_settings::enabled, pe_settings::both, false);
test_transfer(pe_settings::enabled, pe_settings::both, true);
#else
fprintf(stderr, "PE test not run because it's disabled\n");
#endif
return 0;
}
<commit_msg>attempt to make test_pe_crypto pass under valgrind in reasonable time<commit_after>/*
Copyright (c) 2007, Un Shyam
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include <iostream>
#include "libtorrent/hasher.hpp"
#include "libtorrent/pe_crypto.hpp"
#include "libtorrent/session.hpp"
#include "setup_transfer.hpp"
#include "test.hpp"
#ifndef TORRENT_DISABLE_ENCRYPTION
char const* pe_policy(libtorrent::pe_settings::enc_policy policy)
{
using namespace libtorrent;
if (policy == pe_settings::disabled) return "disabled";
else if (policy == pe_settings::enabled) return "enabled";
else if (policy == pe_settings::forced) return "forced";
return "unknown";
}
void display_pe_settings(libtorrent::pe_settings s)
{
using namespace libtorrent;
fprintf(stderr, "out_enc_policy - %s\tin_enc_policy - %s\n"
, pe_policy(s.out_enc_policy), pe_policy(s.in_enc_policy));
fprintf(stderr, "enc_level - %s\t\tprefer_rc4 - %s\n"
, s.allowed_enc_level == pe_settings::plaintext ? "plaintext"
: s.allowed_enc_level == pe_settings::rc4 ? "rc4"
: s.allowed_enc_level == pe_settings::both ? "both" : "unknown"
, s.prefer_rc4 ? "true": "false");
}
void test_transfer(libtorrent::pe_settings::enc_policy policy
, int timeout
, libtorrent::pe_settings::enc_level level = libtorrent::pe_settings::both
, bool pref_rc4 = false)
{
using namespace libtorrent;
// these are declared before the session objects
// so that they are destructed last. This enables
// the sessions to destruct in parallel
session_proxy p1;
session_proxy p2;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48800, 49000), "0.0.0.0", 0);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49800, 50000), "0.0.0.0", 0);
pe_settings s;
s.out_enc_policy = libtorrent::pe_settings::enabled;
s.in_enc_policy = libtorrent::pe_settings::enabled;
s.allowed_enc_level = pe_settings::both;
ses2.set_pe_settings(s);
s.out_enc_policy = policy;
s.in_enc_policy = policy;
s.allowed_enc_level = level;
s.prefer_rc4 = pref_rc4;
ses1.set_pe_settings(s);
s = ses1.get_pe_settings();
fprintf(stderr, " Session1 \n");
display_pe_settings(s);
s = ses2.get_pe_settings();
fprintf(stderr, " Session2 \n");
display_pe_settings(s);
torrent_handle tor1;
torrent_handle tor2;
using boost::tuples::ignore;
boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0, true, false, true
, "_pe", 16 * 1024, 0, false, 0, true);
fprintf(stderr, "waiting for transfer to complete\n");
for (int i = 0; i < timeout * 10; ++i)
{
torrent_status s = tor2.status();
print_alerts(ses1, "ses1");
print_alerts(ses2, "ses2");
if (s.is_seeding) break;
test_sleep(100);
}
TEST_CHECK(tor2.status().is_seeding);
if (tor2.status().is_seeding) fprintf(stderr, "done\n");
ses1.remove_torrent(tor1);
ses2.remove_torrent(tor2);
// this allows shutting down the sessions in parallel
p1 = ses1.abort();
p2 = ses2.abort();
error_code ec;
remove_all("tmp1_pe", ec);
remove_all("tmp2_pe", ec);
remove_all("tmp3_pe", ec);
}
void test_enc_handler(libtorrent::encryption_handler* a, libtorrent::encryption_handler* b)
{
#ifdef TORRENT_USE_VALGRIND
const int repcount = 10;
#else
const int repcount = 128;
#endif
for (int rep = 0; rep < repcount; ++rep)
{
std::size_t buf_len = rand() % (512 * 1024);
char* buf = new char[buf_len];
char* cmp_buf = new char[buf_len];
std::generate(buf, buf + buf_len, &std::rand);
std::memcpy(cmp_buf, buf, buf_len);
a->encrypt(buf, buf_len);
TEST_CHECK(!std::equal(buf, buf + buf_len, cmp_buf));
b->decrypt(buf, buf_len);
TEST_CHECK(std::equal(buf, buf + buf_len, cmp_buf));
b->encrypt(buf, buf_len);
TEST_CHECK(!std::equal(buf, buf + buf_len, cmp_buf));
a->decrypt(buf, buf_len);
TEST_CHECK(std::equal(buf, buf + buf_len, cmp_buf));
delete[] buf;
delete[] cmp_buf;
}
}
#endif
int test_main()
{
using namespace libtorrent;
#ifndef TORRENT_DISABLE_ENCRYPTION
#ifdef TORRENT_USE_VALGRIND
const int repcount = 10;
#else
const int repcount = 128;
#endif
for (int rep = 0; rep < repcount; ++rep)
{
dh_key_exchange DH1, DH2;
DH1.compute_secret(DH2.get_local_key());
DH2.compute_secret(DH1.get_local_key());
TEST_CHECK(std::equal(DH1.get_secret(), DH1.get_secret() + 96, DH2.get_secret()));
}
dh_key_exchange DH1, DH2;
DH1.compute_secret(DH2.get_local_key());
DH2.compute_secret(DH1.get_local_key());
TEST_CHECK(std::equal(DH1.get_secret(), DH1.get_secret() + 96, DH2.get_secret()));
sha1_hash test1_key = hasher("test1_key",8).final();
sha1_hash test2_key = hasher("test2_key",8).final();
fprintf(stderr, "testing RC4 handler\n");
rc4_handler rc41;
rc41.set_incoming_key(&test2_key[0], 20);
rc41.set_outgoing_key(&test1_key[0], 20);
rc4_handler rc42;
rc42.set_incoming_key(&test1_key[0], 20);
rc42.set_outgoing_key(&test2_key[0], 20);
test_enc_handler(&rc41, &rc42);
#ifdef TORRENT_USE_VALGRIND
const int timeout = 10;
#else
const int timeout = 5;
#endif
test_transfer(pe_settings::disabled, timeout);
test_transfer(pe_settings::forced, timeout, pe_settings::plaintext);
test_transfer(pe_settings::forced, timeout, pe_settings::rc4);
test_transfer(pe_settings::forced, timeout, pe_settings::both, false);
test_transfer(pe_settings::forced, timeout, pe_settings::both, true);
test_transfer(pe_settings::enabled, timeout, pe_settings::plaintext);
test_transfer(pe_settings::enabled, timeout, pe_settings::rc4);
test_transfer(pe_settings::enabled, timeout, pe_settings::both, false);
test_transfer(pe_settings::enabled, timeout, pe_settings::both, true);
#else
fprintf(stderr, "PE test not run because it's disabled\n");
#endif
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief Arithmetic テンプレート @n
※テキストの数式を展開して、計算結果を得る。@n
演算式解析
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2015, 2020 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/R8C/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
#include "common/bitset.hpp"
namespace utils {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief Arithmetic クラス
@param[in] VTYPE 基本型
@param[in] SYMBOL シンボルクラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <typename VTYPE>
struct basic_arith {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief エラー・タイプ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class error : uint8_t {
fatal, ///< エラー
number_fatal, ///< 数字の変換に関するエラー
zero_divide, ///< 0除算エラー
binary_fatal, ///< 2進データの変換に関するエラー
octal_fatal, ///< 8進データの変換に関するエラー
hexdecimal_fatal, ///< 16進データの変換に関するエラー
num_fatal, ///< 数値の変換に関するエラー
symbol_fatal, ///< シンボルデータの変換に関するエラー
};
typedef bitset<uint16_t, error> error_t;
private:
const char* tx_;
char ch_;
error_t error_;
VTYPE value_;
void skip_space_() {
while(ch_ == ' ' || ch_ == '\t') {
ch_ = *tx_++;
}
}
VTYPE number_() {
bool inv = false;
/// bool neg = false;
bool point = false;
int32_t v = 0;
uint32_t fp = 0;
uint32_t fs = 1;
skip_space_();
// 符号、反転の判定
if(ch_ == '-') {
inv = true;
ch_ = *tx_++;
} else if(ch_ == '+') {
ch_ = *tx_++;
// } else if(ch_ == '!' || ch_ == '~') {
// neg = true;
// ch_ = *tx_++;
}
skip_space_();
if(ch_ == '(') {
v = factor_();
} else {
skip_space_();
// if(ch_ >= 'A' && ch_ <= 'Z') symbol = true;
// else if(ch_ >= 'a' && ch_ <= 'z') symbol = true;
// else if(ch_ == '_' || ch_ == '?') symbol = true;
while(ch_ != 0) {
if(ch_ == '+') break;
else if(ch_ == '-') break;
else if(ch_ == '*') break;
else if(ch_ == '/') break;
// else if(ch_ == '&') break;
// else if(ch_ == '^') break;
// else if(ch_ == '|') break;
// else if(ch_ == '%') break;
else if(ch_ == ')') break;
// else if(ch_ == '<') break;
// else if(ch_ == '>') break;
// else if(ch_ == '!') break;
// else if(ch_ == '~') break;
else if(ch_ == '.') {
if(point) {
error_.set(error::fatal);
break;
} else {
point = true;
}
} else if(ch_ >= '0' && ch_ <= '9') {
if(point) {
fp *= 10;
fp += ch_ - '0';
fs *= 10;
} else {
v *= 10;
v += ch_ - '0';
}
}
ch_ = *tx_++;
}
#if 0
if(symbol) {
symbol_map_cit cit = symbol_.find(sym);
if(cit != symbol_.end()) {
v = (*cit).second;
} else {
error_.set(error::symbol_fatal);
}
}
#endif
}
if(inv) { v = -v; }
/// if(neg) { v = ~v; }
if(point) {
return static_cast<VTYPE>(v) + static_cast<VTYPE>(fp) / static_cast<VTYPE>(fs);
} else {
return static_cast<VTYPE>(v);
}
}
VTYPE factor_() {
VTYPE v = 0;
if(ch_ == '(') {
ch_ = *tx_++;
v = expression_();
if(ch_ == ')') {
ch_ = *tx_++;
} else {
error_.set(error::fatal);
}
} else {
v = number_();
}
return v;
}
VTYPE term_() {
VTYPE v = factor_();
VTYPE tmp;
while(error_() == 0) {
switch(ch_) {
case ' ':
case '\t':
ch_ = *tx_++;
break;
case '*':
ch_ = *tx_++;
v *= factor_();
break;
#if 0
case '%':
ch_ = *tx_++;
tmp = factor_();
if(tmp == 0) {
error_.set(error::zero_divide);
break;
}
v %= tmp;
break;
#endif
case '/':
ch_ = *tx_++;
if(ch_ == '/') {
ch_ = *tx_++;
tmp = factor_();
if(tmp == 0) {
error_.set(error::zero_divide);
break;
}
/// v %= tmp;
} else {
tmp = factor_();
if(tmp == 0) {
error_.set(error::zero_divide);
break;
}
v /= tmp;
}
break;
#if 0
case '<':
ch_ = *tx_++;
if(ch_ == '<') {
ch_ = *tx_++;
v <<= factor_();
} else {
error_.set(error::fatal);
}
break;
case '>':
ch_ = *tx_++;
if(ch_ == '>') {
ch_ = *tx_++;
v <<= factor_();
} else {
error_.set(error::fatal);
}
break;
#endif
default:
return v;
break;
}
}
return v;
}
VTYPE expression_() {
VTYPE v = term_();
while(error_() == 0) {
switch(ch_) {
case ' ':
case '\t':
ch_ = *tx_++;
break;
case '+':
ch_ = *tx_++;
v += term_();
break;
case '-':
ch_ = *tx_++;
v -= term_();
break;
#if 0
case '&':
ch_ = *tx_++;
v &= term_();
break;
case '^':
ch_ = *tx_++;
v ^= term_();
break;
case '|':
ch_ = *tx_++;
v |= term_();
break;
#endif
default:
return v;
break;
}
}
return v;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
basic_arith() : tx_(nullptr), ch_(0), error_(), value_(0) { }
//-----------------------------------------------------------------//
/*!
@brief 解析を開始
@param[in] text 解析テキスト
@return 文法にエラーがあった場合、「false」
*/
//-----------------------------------------------------------------//
bool analize(const char* text) {
if(text == nullptr) {
error_.set(error::fatal);
return false;
}
tx_ = text;
error_.clear();
ch_ = *tx_++;
if(ch_ != 0) {
value_ = expression_();
} else {
error_.set(error::fatal);
}
if(error_() != 0) {
return false;
} else if(ch_ != 0) {
error_.set(error::fatal);
return false;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief エラーを受け取る
@return エラー
*/
//-----------------------------------------------------------------//
const error_t& get_error() const { return error_; }
//-----------------------------------------------------------------//
/*!
@brief 結果を取得
@return 結果
*/
//-----------------------------------------------------------------//
VTYPE get() const { return value_; }
//-----------------------------------------------------------------//
/*!
@brief () で結果を取得
@return 結果
*/
//-----------------------------------------------------------------//
VTYPE operator() () const { return value_; }
};
}
<commit_msg>Update: cleanup<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief Arithmetic テンプレート @n
※テキストの数式を展開して、計算結果を得る。@n
NVAL には、Boost Multiprecision Library を利用する事を前提にしている。
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2015, 2020 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
#include "common/bitset.hpp"
namespace utils {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief Arithmetic クラス
@param[in] NVAL 基本型
@param[in] SYMBOL 変数クラス
@param[in] FUNC 関数クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class NVAL, class SYMBOL, class FUNC>
struct basic_arith {
static const uint32_t NUMBER_NUM = 50; // 最大桁数
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief エラー・タイプ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class error : uint8_t {
fatal, ///< エラー
number_fatal, ///< 数字の変換に関するエラー
zero_divide, ///< 0除算エラー
binary_fatal, ///< 2進データの変換に関するエラー
octal_fatal, ///< 8進データの変換に関するエラー
hexdecimal_fatal, ///< 16進データの変換に関するエラー
num_fatal, ///< 数値の変換に関するエラー
symbol_fatal, ///< シンボルデータの変換に関するエラー
func_fatal, ///< 関数の変換に関するエラー
};
typedef bitset<uint16_t, error> error_t;
private:
SYMBOL& symbol_;
FUNC& func_;
const char* tx_;
char ch_;
error_t error_;
NVAL value_;
// スペース、TAB を取り除く
void skip_space_() noexcept
{
while(ch_ == ' ' || ch_ == '\t') {
ch_ = *tx_++;
}
}
// 関数内パラメーターの取得
bool param_(char* dst, uint32_t len)
{
if(ch_ != '(') return false;
while(ch_ != 0) {
--len;
if(len == 0) break;
}
return true;
}
NVAL number_()
{
bool minus = false;
char tmp[NUMBER_NUM];
skip_space_();
// 符号、反転の判定
if(ch_ == '-') {
minus = true;
ch_ = *tx_++;
} else if(ch_ == '+') {
ch_ = *tx_++;
}
skip_space_();
NVAL nval;
if(static_cast<uint8_t>(ch_) >= 0x80) { // symbol?, func?
if(static_cast<uint8_t>(ch_) >= 0xC0) { // func ?
auto fc = static_cast<typename FUNC::NAME>(ch_);
ch_ = *tx_++;
if(ch_ == '(') {
ch_ = *tx_++;
auto param = expression_();
if(ch_ == ')') {
ch_ = *tx_++;
if(!func_(fc, param, nval)) {
error_.set(error::func_fatal);
}
} else {
error_.set(error::fatal);
}
} else {
error_.set(error::func_fatal);
}
} else { // to symbol
if(symbol_(static_cast<typename SYMBOL::NAME>(ch_), nval)) {
ch_ = *tx_++;
} else {
error_.set(error::symbol_fatal);
}
}
return nval;
}
if(ch_ == '(') {
nval = factor_();
} else {
uint32_t idx = 0;
while(ch_ != 0) {
if(ch_ == '+') break;
else if(ch_ == '-') break;
else if(ch_ == '*') break;
else if(ch_ == '/') break;
else if(ch_ == ')') break;
else if((ch_ >= '0' && ch_ <= '9') || ch_=='.' || ch_=='e' || ch_=='E') {
tmp[idx] = ch_;
idx++;
} else {
error_.set(error::fatal);
break;
}
ch_ = *tx_++;
}
tmp[idx] = 0;
if(error_() == 0) {
nval.assign(tmp);
}
}
if(minus) { nval = -nval; }
return nval;
}
auto factor_()
{
NVAL v(0.0);
if(ch_ == '(') {
ch_ = *tx_++;
v = expression_();
if(ch_ == ')') {
ch_ = *tx_++;
} else {
error_.set(error::fatal);
}
} else {
v = number_();
}
return v;
}
NVAL term_() {
NVAL v = factor_();
NVAL tmp;
while(error_() == 0) {
switch(ch_) {
case ' ':
case '\t':
ch_ = *tx_++;
break;
case '*':
ch_ = *tx_++;
v *= factor_();
break;
#if 0
case '%':
ch_ = *tx_++;
tmp = factor_();
if(tmp == 0) {
error_.set(error::zero_divide);
break;
}
v %= tmp;
break;
#endif
case '/':
ch_ = *tx_++;
if(ch_ == '/') {
ch_ = *tx_++;
tmp = factor_();
if(tmp == 0) {
error_.set(error::zero_divide);
break;
}
} else {
tmp = factor_();
if(tmp == 0) {
error_.set(error::zero_divide);
break;
}
v /= tmp;
}
break;
#if 0
case '<':
ch_ = *tx_++;
if(ch_ == '<') {
ch_ = *tx_++;
v <<= factor_();
} else {
error_.set(error::fatal);
}
break;
case '>':
ch_ = *tx_++;
if(ch_ == '>') {
ch_ = *tx_++;
v <<= factor_();
} else {
error_.set(error::fatal);
}
break;
#endif
default:
return v;
break;
}
}
return v;
}
NVAL expression_() {
NVAL v = term_();
while(error_() == 0) {
switch(ch_) {
case ' ':
case '\t':
ch_ = *tx_++;
break;
case '+':
ch_ = *tx_++;
v += term_();
break;
case '-':
ch_ = *tx_++;
v -= term_();
break;
#if 0
case '&':
ch_ = *tx_++;
v &= term_();
break;
case '^':
ch_ = *tx_++;
v ^= term_();
break;
case '|':
ch_ = *tx_++;
v |= term_();
break;
#endif
default:
return v;
break;
}
}
return v;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] func 関数クラス
*/
//-----------------------------------------------------------------//
basic_arith(SYMBOL& symbol, FUNC& func) noexcept : symbol_(symbol), func_(func),
tx_(nullptr), ch_(0), error_(), value_()
{ }
//-----------------------------------------------------------------//
/*!
@brief 解析を開始
@param[in] text 解析テキスト
@return 文法にエラーがあった場合、「false」
*/
//-----------------------------------------------------------------//
bool analize(const char* text)
{
if(text == nullptr) {
error_.set(error::fatal);
return false;
}
tx_ = text;
error_.clear();
ch_ = *tx_++;
if(ch_ != 0) {
value_ = expression_();
} else {
error_.set(error::fatal);
}
if(error_() != 0) {
return false;
} else if(ch_ != 0) {
error_.set(error::fatal);
return false;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief エラーを受け取る
@return エラー
*/
//-----------------------------------------------------------------//
const error_t& get_error() const { return error_; }
//-----------------------------------------------------------------//
/*!
@brief エラーメッセージを取得
@return エラーメッセージ
*/
//-----------------------------------------------------------------//
template <class STR>
STR get_error() const {
STR str;
return str;
}
//-----------------------------------------------------------------//
/*!
@brief 埋め込まれた、シンボル、関数名を展開
@param[in] in 入力文字列
@param[out] out 展開文字列
@param[in] len 展開文字列サイズ
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool parse(const char* in, char* out, uint32_t len) const
{
char ch;
while(len > 1 && (ch = *in++) != 0) {
uint8_t n = static_cast<uint8_t>(ch);
if(n < 0x80) {
*out++ = ch;
len--;
} else if(n < 0xc0) { // シンボル
} else { // 関数
}
}
*out = 0;
return len > 1;
}
//-----------------------------------------------------------------//
/*!
@brief () で結果を取得
@return 結果
*/
//-----------------------------------------------------------------//
NVAL operator() () const { return value_; }
};
}
<|endoftext|>
|
<commit_before>// Copyright 2021 MozoLM Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "mozolm/models/language_model.h"
#include <algorithm>
#include "ngram/ngram-model.h"
#include "absl/strings/str_cat.h"
#include "nisaba/port/utf8_util.h"
namespace mozolm {
namespace models {
int LanguageModel::ContextState(const std::string& context, int init_state) {
int this_state = init_state < 0 ? start_state_ : init_state;
if (!context.empty()) {
const std::vector<int> context_utf8 =
nisaba::utf8::StrSplitByCharToUnicode(context);
for (const auto& sym : context_utf8) {
this_state = NextState(this_state, static_cast<int>(sym));
if (this_state < 0) {
// Returns to start state if symbol not found.
// TODO: should it return to a null context state?
this_state = start_state_;
}
}
}
return this_state;
}
absl::StatusOr<std::vector<std::pair<double, std::string>>>
GetTopHypotheses(const LMScores &scores, int top_n) {
const int num_entries = scores.probabilities().size();
if (num_entries != scores.symbols().size()) {
return absl::InternalError(absl::StrCat(
"Mismatching number of probabilities (", num_entries,
") and symbols (", scores.symbols().size(), ")"));
}
if (num_entries <= top_n) {
return absl::InternalError(absl::StrCat(
"Too many candidates requested: ", top_n));
} else if (num_entries == 0) {
return absl::InternalError("No scores to return");
}
std::vector<std::pair<double, std::string>> hyps;
hyps.reserve(num_entries);
for (int i = 0; i < num_entries; ++i) {
hyps.push_back({ scores.probabilities(i), scores.symbols(i) });
}
std::sort(hyps.begin(), hyps.end(),
[](const std::pair<double, std::string> &a,
const std::pair<double, std::string> &b) {
return a.first > b.first;
});
if (top_n > 0) {
hyps = std::vector(hyps.begin(), hyps.begin() + top_n);
}
return std::move(hyps);
}
void SoftmaxRenormalize(std::vector<double> *neg_log_probs) {
double tot_prob = (*neg_log_probs)[0];
double kahan_factor = 0.0;
for (int i = 1; i < neg_log_probs->size(); ++i) {
tot_prob =
ngram::NegLogSum(tot_prob, (*neg_log_probs)[i], &kahan_factor);
}
for (int i = 0; i < neg_log_probs->size(); ++i) {
(*neg_log_probs)[i] -= tot_prob;
}
}
} // namespace models
} // namespace mozolm
<commit_msg>Cosmetic change: Getting rid of silly no-op static cast.<commit_after>// Copyright 2021 MozoLM Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "mozolm/models/language_model.h"
#include <algorithm>
#include "ngram/ngram-model.h"
#include "absl/strings/str_cat.h"
#include "nisaba/port/utf8_util.h"
namespace mozolm {
namespace models {
int LanguageModel::ContextState(const std::string& context, int init_state) {
int this_state = init_state < 0 ? start_state_ : init_state;
if (!context.empty()) {
const std::vector<int> context_utf8 =
nisaba::utf8::StrSplitByCharToUnicode(context);
for (auto sym : context_utf8) {
this_state = NextState(this_state, sym);
if (this_state < 0) {
// Returns to start state if symbol not found.
// TODO: should it return to a null context state?
this_state = start_state_;
}
}
}
return this_state;
}
absl::StatusOr<std::vector<std::pair<double, std::string>>>
GetTopHypotheses(const LMScores &scores, int top_n) {
const int num_entries = scores.probabilities().size();
if (num_entries != scores.symbols().size()) {
return absl::InternalError(absl::StrCat(
"Mismatching number of probabilities (", num_entries,
") and symbols (", scores.symbols().size(), ")"));
}
if (num_entries <= top_n) {
return absl::InternalError(absl::StrCat(
"Too many candidates requested: ", top_n));
} else if (num_entries == 0) {
return absl::InternalError("No scores to return");
}
std::vector<std::pair<double, std::string>> hyps;
hyps.reserve(num_entries);
for (int i = 0; i < num_entries; ++i) {
hyps.push_back({ scores.probabilities(i), scores.symbols(i) });
}
std::sort(hyps.begin(), hyps.end(),
[](const std::pair<double, std::string> &a,
const std::pair<double, std::string> &b) {
return a.first > b.first;
});
if (top_n > 0) {
hyps = std::vector(hyps.begin(), hyps.begin() + top_n);
}
return std::move(hyps);
}
void SoftmaxRenormalize(std::vector<double> *neg_log_probs) {
double tot_prob = (*neg_log_probs)[0];
double kahan_factor = 0.0;
for (int i = 1; i < neg_log_probs->size(); ++i) {
tot_prob =
ngram::NegLogSum(tot_prob, (*neg_log_probs)[i], &kahan_factor);
}
for (int i = 0; i < neg_log_probs->size(); ++i) {
(*neg_log_probs)[i] -= tot_prob;
}
}
} // namespace models
} // namespace mozolm
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/set_process_title.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "build/build_config.h"
#if defined(OS_POSIX)
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#endif
#if defined(OS_LINUX)
#include <sys/prctl.h>
// Linux/glibc doesn't natively have setproctitle().
#include "content/common/set_process_title_linux.h"
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_SOLARIS) && \
defined(OS_OPENBSD)
void SetProcessTitleFromCommandLine(const char** main_argv) {
// Build a single string which consists of all the arguments separated
// by spaces. We can't actually keep them separate due to the way the
// setproctitle() function works.
std::string title;
bool have_argv0 = false;
#if defined(OS_LINUX)
if (main_argv)
setproctitle_init(main_argv);
// In Linux we sometimes exec ourselves from /proc/self/exe, but this makes us
// show up as "exe" in process listings. Read the symlink /proc/self/exe and
// use the path it points at for our process title. Note that this is only for
// display purposes and has no TOCTTOU security implications.
FilePath target;
FilePath self_exe("/proc/self/exe");
if (file_util::ReadSymbolicLink(self_exe, &target)) {
have_argv0 = true;
title = target.value();
// If the binary has since been deleted, Linux appends " (deleted)" to the
// symlink target. Remove it, since this is not really part of our name.
const std::string kDeletedSuffix = " (deleted)";
if (EndsWith(title, kDeletedSuffix, true))
title.resize(title.size() - kDeletedSuffix.size());
#if defined(PR_SET_NAME)
// If PR_SET_NAME is available at compile time, we try using it. We ignore
// any errors if the kernel does not support it at runtime though. When
// available, this lets us set the short process name that shows when the
// full command line is not being displayed in most process listings.
prctl(PR_SET_NAME, FilePath(title).BaseName().value().c_str());
#endif
}
#endif
const CommandLine* command_line = CommandLine::ForCurrentProcess();
for (size_t i = 1; i < command_line->argv().size(); ++i) {
if (!title.empty())
title += " ";
title += command_line->argv()[i];
}
// Disable prepending argv[0] with '-' if we prepended it ourselves above.
setproctitle(have_argv0 ? "-%s" : "%s", title.c_str());
}
#else
// All other systems (basically Windows & Mac) have no need or way to implement
// this function.
void SetProcessTitleFromCommandLine(const char** /* main_argv */) {
}
#endif
<commit_msg>Linux: Fix bad #define for SetProcessTitleFromCommandLine().<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/set_process_title.h"
#include "build/build_config.h"
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_SOLARIS)
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include "base/command_line.h"
#endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_SOLARIS)
#if defined(OS_LINUX)
#include <sys/prctl.h>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/string_util.h"
// Linux/glibc doesn't natively have setproctitle().
#include "content/common/set_process_title_linux.h"
#endif // defined(OS_LINUX)
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_SOLARIS)
void SetProcessTitleFromCommandLine(const char** main_argv) {
// Build a single string which consists of all the arguments separated
// by spaces. We can't actually keep them separate due to the way the
// setproctitle() function works.
std::string title;
bool have_argv0 = false;
#if defined(OS_LINUX)
if (main_argv)
setproctitle_init(main_argv);
// In Linux we sometimes exec ourselves from /proc/self/exe, but this makes us
// show up as "exe" in process listings. Read the symlink /proc/self/exe and
// use the path it points at for our process title. Note that this is only for
// display purposes and has no TOCTTOU security implications.
FilePath target;
FilePath self_exe("/proc/self/exe");
if (file_util::ReadSymbolicLink(self_exe, &target)) {
have_argv0 = true;
title = target.value();
// If the binary has since been deleted, Linux appends " (deleted)" to the
// symlink target. Remove it, since this is not really part of our name.
const std::string kDeletedSuffix = " (deleted)";
if (EndsWith(title, kDeletedSuffix, true))
title.resize(title.size() - kDeletedSuffix.size());
#if defined(PR_SET_NAME)
// If PR_SET_NAME is available at compile time, we try using it. We ignore
// any errors if the kernel does not support it at runtime though. When
// available, this lets us set the short process name that shows when the
// full command line is not being displayed in most process listings.
prctl(PR_SET_NAME, FilePath(title).BaseName().value().c_str());
#endif // defined(PR_SET_NAME)
}
#endif // defined(OS_LINUX)
const CommandLine* command_line = CommandLine::ForCurrentProcess();
for (size_t i = 1; i < command_line->argv().size(); ++i) {
if (!title.empty())
title += " ";
title += command_line->argv()[i];
}
// Disable prepending argv[0] with '-' if we prepended it ourselves above.
setproctitle(have_argv0 ? "-%s" : "%s", title.c_str());
}
#else
// All other systems (basically Windows & Mac) have no need or way to implement
// this function.
void SetProcessTitleFromCommandLine(const char** /* main_argv */) {
}
#endif
<|endoftext|>
|
<commit_before>#ifndef VIENNAGRID_METAINFO_HPP
#define VIENNAGRID_METAINFO_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp rupp@iue.tuwien.ac.at
Josef Weinbub weinbub@iue.tuwien.ac.at
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
namespace viennagrid
{
namespace metainfo
{
struct random_access_tag {};
struct associative_access_tag {};
namespace result_of
{
template<typename container_type>
struct associative_container_value_type
{
typedef typename container_type::value_type type;
};
template<typename key_type, typename value_type, typename compare, typename allocator>
struct associative_container_value_type< std::map<key_type, value_type, compare, allocator> >
{
typedef value_type type;
};
template<typename container_type>
struct associative_container_access_tag
{
typedef random_access_tag type;
};
template<typename key_type, typename value_type, typename compare, typename allocator>
struct associative_container_access_tag< std::map<key_type, value_type, compare, allocator> >
{
typedef associative_access_tag type;
};
}
template<typename geometric_container_type, typename element_type>
typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element, random_access_tag )
{
return container[ element.id().get() ];
}
template<typename geometric_container_type, typename element_type>
typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element, associative_access_tag )
{
typename geometric_container_type::iterator it = container.find( element.id() );
return it->second;
}
template<typename geometric_container_type, typename element_type>
typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element )
{
return look_up(container, element, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
}
template<typename geometric_container_type, typename element_type>
const typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( const geometric_container_type & container, const element_type & element, random_access_tag )
{
return container[ element.id().get() ];
}
template<typename geometric_container_type, typename element_type>
const typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( const geometric_container_type & container, const element_type & element, associative_access_tag )
{
typename geometric_container_type::iterator it = container.find( element.id() );
return it->second;
}
template<typename geometric_container_type, typename element_type>
const typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( const geometric_container_type & container, const element_type & element )
{
return look_up(container, element, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
}
template<typename geometric_container_type, typename element_type>
void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info, random_access_tag )
{
if (container.size() >= element.id().get() )
container.resize( element.id().get()+1 );
container[ element.id().get() ] = info;
}
template<typename geometric_container_type, typename element_type>
void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info, associative_access_tag )
{
container.insert(
std::make_pair( element.id(), info )
);
}
template<typename geometric_container_type, typename element_type>
void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info )
{
set(container, element, info, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
}
}
}
namespace viennagrid
{
namespace result_of
{
template<typename container_collection_type, typename element_type, typename metainfo_type>
struct info_container;
template<typename container_typemap, typename element_type, typename metainfo_type>
struct info_container< viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type >
{
typedef typename viennagrid::storage::result_of::container_of< viennagrid::storage::collection_t<container_typemap>, viennameta::static_pair<element_type, metainfo_type> >::type type;
};
}
template< typename element_type, typename metainfo_type, typename container_typemap >
typename result_of::info_container< viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type>::type & get_info( viennagrid::storage::collection_t<container_typemap> & container_collection )
{
return viennagrid::storage::collection::get< viennameta::static_pair<element_type, metainfo_type> >(container_collection);
}
template< typename element_type, typename metainfo_type, typename container_typemap >
const typename result_of::info_container<viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type>::type & get_info( const viennagrid::storage::collection_t<container_typemap> & container_collection )
{
return viennagrid::storage::collection::get< viennameta::static_pair<element_type, metainfo_type> >(container_collection);
}
template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
typename metainfo::result_of::associative_container_value_type<
typename result_of::info_container<
viennagrid::storage::collection_t<metainfo_container_typemap>,
element_type,
metainfo_type
>::type
>::type & look_up(
viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
const element_type & element
)
{
return metainfo::look_up( get_info<element_type, metainfo_type>(metainfo_collection), element );
}
template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
const typename metainfo::result_of::associative_container_value_type<
typename result_of::info_container<
viennagrid::storage::collection_t<metainfo_container_typemap>,
element_type,
metainfo_type
>::type
>::type & look_up(
const viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
const element_type & element
)
{
return metainfo::look_up( get_info<element_type, metainfo_type>(metainfo_collection), element );
}
template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
void set(
viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
const element_type & element,
const typename metainfo::result_of::associative_container_value_type<
typename result_of::info_container<
viennagrid::storage::collection_t<metainfo_container_typemap>,
element_type,
metainfo_type
>::type
>::type & meta_info )
{
metainfo::set( get_info<element_type, metainfo_type>(metainfo_collection), element, meta_info );
}
namespace metainfo
{
template<typename element_type, typename cur_typemap>
struct for_each_element_helper;
template<typename element_type, typename cur_element_type, typename cur_metainfo_type, typename container_type, typename tail>
struct for_each_element_helper<
element_type,
viennameta::typelist_t<
viennameta::static_pair<
viennameta::static_pair<
cur_element_type,
cur_metainfo_type
>,
container_type
>,
tail>
>
{
template<typename metainfo_container_typemap, typename functor_type>
static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
{
for_each_element_helper<element_type, tail>::exec(collection, functor);
}
};
template<typename element_type, typename cur_metainfo_type, typename container_type, typename tail>
struct for_each_element_helper<
element_type,
viennameta::typelist_t<
viennameta::static_pair<
viennameta::static_pair<
element_type,
cur_metainfo_type
>,
container_type
>,
tail>
>
{
template<typename metainfo_container_typemap, typename functor_type>
static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
{
functor( get_info<element_type, cur_metainfo_type>(collection) );
//get_info<element_type, cur_metainfo_type>(collection).resize( size );
for_each_element_helper<element_type, tail>::exec(collection, functor);
}
};
template<typename element_type>
struct for_each_element_helper<
element_type,
viennameta::null_type
>
{
template<typename metainfo_container_typemap, typename functor_type>
static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
{}
};
class resize_functor
{
public:
resize_functor(std::size_t size_) : size(size_) {}
template<typename container_type>
void operator() ( container_type & container )
{
container.resize(size);
}
private:
std::size_t size;
};
template<typename element_type, typename metainfo_container_typemap>
void resize_container( storage::collection_t<metainfo_container_typemap> & collection, std::size_t size )
{
for_each_element_helper<element_type, metainfo_container_typemap>::exec(collection, resize_functor(size) );
}
class increment_size_functor
{
public:
increment_size_functor() {}
template<typename container_type>
void operator() ( container_type & container )
{
container.resize( container.size()+1 );
}
};
template<typename element_type, typename metainfo_container_typemap>
void increment_size( storage::collection_t<metainfo_container_typemap> & collection )
{
for_each_element_helper<element_type, metainfo_container_typemap>::exec(collection, increment_size_functor() );
}
}
namespace result_of
{
template<typename pair_type, typename container_config, typename topologic_domain_config>
struct metainfo_container;
template<typename element_type, typename metainfo_type, typename container_config, typename topologic_domain_config>
struct metainfo_container< viennameta::static_pair<element_type, metainfo_type>, container_config, topologic_domain_config >
{
typedef typename viennameta::typemap::result_of::find<container_config, viennameta::static_pair<element_type, metainfo_type> >::type search_result;
typedef typename viennameta::typemap::result_of::find<container_config, viennagrid::storage::default_tag>::type default_container;
typedef typename viennameta::_if<
!viennameta::_equal<search_result, viennameta::not_found>::value,
search_result,
default_container
>::type container_tag_pair;
//typedef typename viennagrid::storage::result_of::container_from_tag<value_type, typename container_tag_pair::second>::type type;
typedef typename viennagrid::storage::result_of::container<metainfo_type, typename container_tag_pair::second>::type type;
};
template<typename element_list, typename container_config, typename topologic_domain_config>
struct metainfo_container_typemap;
template<typename container_config, typename topologic_domain_config>
struct metainfo_container_typemap<viennameta::null_type, container_config, topologic_domain_config>
{
typedef viennameta::null_type type;
};
template<typename element_tag, typename metainfo_type, typename tail, typename container_config, typename topologic_domain_config>
struct metainfo_container_typemap<viennameta::typelist_t< viennameta::static_pair<element_tag, metainfo_type>, tail>, container_config, topologic_domain_config>
{
typedef typename viennagrid::result_of::element<topologic_domain_config, element_tag>::type element_type;
typedef viennameta::typelist_t<
typename viennameta::static_pair<
viennameta::static_pair<element_type, metainfo_type>,
typename metainfo_container< viennameta::static_pair<element_type, metainfo_type>, container_config, topologic_domain_config>::type
>,
typename metainfo_container_typemap<tail, container_config, topologic_domain_config>::type
> type;
};
}
}
#endif
<commit_msg>fixed const correctness<commit_after>#ifndef VIENNAGRID_METAINFO_HPP
#define VIENNAGRID_METAINFO_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp rupp@iue.tuwien.ac.at
Josef Weinbub weinbub@iue.tuwien.ac.at
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
namespace viennagrid
{
namespace metainfo
{
struct random_access_tag {};
struct associative_access_tag {};
namespace result_of
{
template<typename container_type>
struct associative_container_value_type
{
typedef typename container_type::value_type type;
};
template<typename key_type, typename value_type, typename compare, typename allocator>
struct associative_container_value_type< std::map<key_type, value_type, compare, allocator> >
{
typedef value_type type;
};
template<typename container_type>
struct associative_container_access_tag
{
typedef random_access_tag type;
};
template<typename key_type, typename value_type, typename compare, typename allocator>
struct associative_container_access_tag< std::map<key_type, value_type, compare, allocator> >
{
typedef associative_access_tag type;
};
}
template<typename geometric_container_type, typename element_type>
typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element, random_access_tag )
{
return container[ element.id().get() ];
}
template<typename geometric_container_type, typename element_type>
typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element, associative_access_tag )
{
typename geometric_container_type::iterator it = container.find( element.id() );
return it->second;
}
template<typename geometric_container_type, typename element_type>
typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( geometric_container_type & container, const element_type & element )
{
return look_up(container, element, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
}
template<typename geometric_container_type, typename element_type>
const typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( const geometric_container_type & container, const element_type & element, random_access_tag )
{
return container[ element.id().get() ];
}
template<typename geometric_container_type, typename element_type>
const typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( const geometric_container_type & container, const element_type & element, associative_access_tag )
{
typename geometric_container_type::const_iterator it = container.find( element.id() );
return it->second;
}
template<typename geometric_container_type, typename element_type>
const typename result_of::associative_container_value_type<geometric_container_type>::type & look_up( const geometric_container_type & container, const element_type & element )
{
return look_up(container, element, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
}
template<typename geometric_container_type, typename element_type>
void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info, random_access_tag )
{
if (container.size() >= element.id().get() )
container.resize( element.id().get()+1 );
container[ element.id().get() ] = info;
}
template<typename geometric_container_type, typename element_type>
void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info, associative_access_tag )
{
container.insert(
std::make_pair( element.id(), info )
);
}
template<typename geometric_container_type, typename element_type>
void set( geometric_container_type & container, const element_type & element, const typename result_of::associative_container_value_type<geometric_container_type>::type & info )
{
set(container, element, info, typename result_of::associative_container_access_tag<geometric_container_type>::type() );
}
}
}
namespace viennagrid
{
namespace result_of
{
template<typename container_collection_type, typename element_type, typename metainfo_type>
struct info_container;
template<typename container_typemap, typename element_type, typename metainfo_type>
struct info_container< viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type >
{
typedef typename viennagrid::storage::result_of::container_of< viennagrid::storage::collection_t<container_typemap>, viennameta::static_pair<element_type, metainfo_type> >::type type;
};
}
template< typename element_type, typename metainfo_type, typename container_typemap >
typename result_of::info_container< viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type>::type & get_info( viennagrid::storage::collection_t<container_typemap> & container_collection )
{
return viennagrid::storage::collection::get< viennameta::static_pair<element_type, metainfo_type> >(container_collection);
}
template< typename element_type, typename metainfo_type, typename container_typemap >
const typename result_of::info_container<viennagrid::storage::collection_t<container_typemap>, element_type, metainfo_type>::type & get_info( const viennagrid::storage::collection_t<container_typemap> & container_collection )
{
return viennagrid::storage::collection::get< viennameta::static_pair<element_type, metainfo_type> >(container_collection);
}
template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
typename metainfo::result_of::associative_container_value_type<
typename result_of::info_container<
viennagrid::storage::collection_t<metainfo_container_typemap>,
element_type,
metainfo_type
>::type
>::type & look_up(
viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
const element_type & element
)
{
return metainfo::look_up( get_info<element_type, metainfo_type>(metainfo_collection), element );
}
template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
const typename metainfo::result_of::associative_container_value_type<
typename result_of::info_container<
viennagrid::storage::collection_t<metainfo_container_typemap>,
element_type,
metainfo_type
>::type
>::type & look_up(
const viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
const element_type & element
)
{
return metainfo::look_up( get_info<element_type, metainfo_type>(metainfo_collection), element );
}
template<typename metainfo_type, typename metainfo_container_typemap, typename element_type>
void set(
viennagrid::storage::collection_t<metainfo_container_typemap> & metainfo_collection,
const element_type & element,
const typename metainfo::result_of::associative_container_value_type<
typename result_of::info_container<
viennagrid::storage::collection_t<metainfo_container_typemap>,
element_type,
metainfo_type
>::type
>::type & meta_info )
{
metainfo::set( get_info<element_type, metainfo_type>(metainfo_collection), element, meta_info );
}
namespace metainfo
{
template<typename element_type, typename cur_typemap>
struct for_each_element_helper;
template<typename element_type, typename cur_element_type, typename cur_metainfo_type, typename container_type, typename tail>
struct for_each_element_helper<
element_type,
viennameta::typelist_t<
viennameta::static_pair<
viennameta::static_pair<
cur_element_type,
cur_metainfo_type
>,
container_type
>,
tail>
>
{
template<typename metainfo_container_typemap, typename functor_type>
static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
{
for_each_element_helper<element_type, tail>::exec(collection, functor);
}
};
template<typename element_type, typename cur_metainfo_type, typename container_type, typename tail>
struct for_each_element_helper<
element_type,
viennameta::typelist_t<
viennameta::static_pair<
viennameta::static_pair<
element_type,
cur_metainfo_type
>,
container_type
>,
tail>
>
{
template<typename metainfo_container_typemap, typename functor_type>
static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
{
functor( get_info<element_type, cur_metainfo_type>(collection) );
//get_info<element_type, cur_metainfo_type>(collection).resize( size );
for_each_element_helper<element_type, tail>::exec(collection, functor);
}
};
template<typename element_type>
struct for_each_element_helper<
element_type,
viennameta::null_type
>
{
template<typename metainfo_container_typemap, typename functor_type>
static void exec( storage::collection_t<metainfo_container_typemap> & collection, functor_type functor)
{}
};
class resize_functor
{
public:
resize_functor(std::size_t size_) : size(size_) {}
template<typename container_type>
void operator() ( container_type & container )
{
container.resize(size);
}
private:
std::size_t size;
};
template<typename element_type, typename metainfo_container_typemap>
void resize_container( storage::collection_t<metainfo_container_typemap> & collection, std::size_t size )
{
for_each_element_helper<element_type, metainfo_container_typemap>::exec(collection, resize_functor(size) );
}
class increment_size_functor
{
public:
increment_size_functor() {}
template<typename container_type>
void operator() ( container_type & container )
{
container.resize( container.size()+1 );
}
};
template<typename element_type, typename metainfo_container_typemap>
void increment_size( storage::collection_t<metainfo_container_typemap> & collection )
{
for_each_element_helper<element_type, metainfo_container_typemap>::exec(collection, increment_size_functor() );
}
}
namespace result_of
{
template<typename pair_type, typename container_config, typename topologic_domain_config>
struct metainfo_container;
template<typename element_type, typename metainfo_type, typename container_config, typename topologic_domain_config>
struct metainfo_container< viennameta::static_pair<element_type, metainfo_type>, container_config, topologic_domain_config >
{
typedef typename viennameta::typemap::result_of::find<container_config, viennameta::static_pair<element_type, metainfo_type> >::type search_result;
typedef typename viennameta::typemap::result_of::find<container_config, viennagrid::storage::default_tag>::type default_container;
typedef typename viennameta::_if<
!viennameta::_equal<search_result, viennameta::not_found>::value,
search_result,
default_container
>::type container_tag_pair;
//typedef typename viennagrid::storage::result_of::container_from_tag<value_type, typename container_tag_pair::second>::type type;
typedef typename viennagrid::storage::result_of::container<metainfo_type, typename container_tag_pair::second>::type type;
};
template<typename element_list, typename container_config, typename topologic_domain_config>
struct metainfo_container_typemap;
template<typename container_config, typename topologic_domain_config>
struct metainfo_container_typemap<viennameta::null_type, container_config, topologic_domain_config>
{
typedef viennameta::null_type type;
};
template<typename element_tag, typename metainfo_type, typename tail, typename container_config, typename topologic_domain_config>
struct metainfo_container_typemap<viennameta::typelist_t< viennameta::static_pair<element_tag, metainfo_type>, tail>, container_config, topologic_domain_config>
{
typedef typename viennagrid::result_of::element<topologic_domain_config, element_tag>::type element_type;
typedef viennameta::typelist_t<
typename viennameta::static_pair<
viennameta::static_pair<element_type, metainfo_type>,
typename metainfo_container< viennameta::static_pair<element_type, metainfo_type>, container_config, topologic_domain_config>::type
>,
typename metainfo_container_typemap<tail, container_config, topologic_domain_config>::type
> type;
};
}
}
#endif
<|endoftext|>
|
<commit_before>/*
Implement parallel vectorize workqueue on top of Intel TBB.
*/
#define TBB_PREVIEW_WAITING_FOR_WORKERS 1
/* tbb.h redefines these */
#include "../../_pymodule.h"
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif
#ifdef _XOPEN_SOURCE
#undef _XOPEN_SOURCE
#endif
#include <tbb/tbb.h>
#include <string.h>
#include <stdio.h>
#include <thread>
#include "workqueue.h"
#include "gufunc_scheduler.h"
/* TBB 2019 U5 is the minimum required version as this is needed:
* https://github.com/intel/tbb/blob/18070344d755ece04d169e6cc40775cae9288cee/CHANGES#L133-L134
* and therefore
* https://github.com/intel/tbb/blob/18070344d755ece04d169e6cc40775cae9288cee/CHANGES#L128-L129
* from here:
* https://github.com/intel/tbb/blob/2019_U5/include/tbb/tbb_stddef.h#L29
*/
#if TBB_INTERFACE_VERSION < 12010
#error "TBB version is too old, 2021 update 1, i.e. TBB_INTERFACE_VERSION >= 12010 required"
#endif
#define _DEBUG 0
#define _TRACE_SPLIT 0
static tbb::task_group *tg = NULL;
static tbb::task_scheduler_handle tsh;
static bool tsh_was_initialized = false;
#ifdef _MSC_VER
#define THREAD_LOCAL(ty) __declspec(thread) ty
#else
/* Non-standard C99 extension that's understood by gcc and clang */
#define THREAD_LOCAL(ty) __thread ty
#endif
// This is the number of threads that is default, it is set on initialisation of
// the threading backend via the launch_threads() call
static int _INIT_NUM_THREADS = -1;
// This is the per-thread thread mask, each thread can carry its own mask.
static THREAD_LOCAL(int) _TLS_num_threads = 0;
static void
set_num_threads(int count)
{
_TLS_num_threads = count;
}
static int
get_num_threads(void)
{
if (_TLS_num_threads == 0)
{
// This is a thread that did not call launch_threads() but is still a
// "main" thread, probably from e.g. threading.Thread() use, it still
// has a TLS slot which is 0 from the lack of launch_threads() call
_TLS_num_threads = _INIT_NUM_THREADS;
}
return _TLS_num_threads;
}
static int
get_thread_id(void)
{
return tbb::this_task_arena::current_thread_index();
}
// watch the arena, if it decides to create more threads/add threads into the
// arena then make sure they get the right thread count
class fix_tls_observer: public tbb::task_scheduler_observer {
int mask_val;
void on_scheduler_entry( bool is_worker ) override;
public:
fix_tls_observer(tbb::task_arena &arena, int mask) : tbb::task_scheduler_observer(arena), mask_val(mask)
{
observe(true);
}
};
void fix_tls_observer::on_scheduler_entry(bool worker) {
set_num_threads(mask_val);
}
static void
add_task(void *fn, void *args, void *dims, void *steps, void *data)
{
tg->run([=]
{
auto func = reinterpret_cast<void (*)(void *args, void *dims, void *steps, void *data)>(fn);
func(args, dims, steps, data);
});
}
static void
parallel_for(void *fn, char **args, size_t *dimensions, size_t *steps, void *data,
size_t inner_ndim, size_t array_count, int num_threads)
{
static bool printed = false;
if(!printed && _DEBUG)
{
puts("Using parallel_for");
printed = true;
}
// args = <ir.Argument '.1' of type i8**>,
// dimensions = <ir.Argument '.2' of type i64*>
// steps = <ir.Argument '.3' of type i64*>
// data = <ir.Argument '.4' of type i8*>
const size_t arg_len = (inner_ndim + 1);
if(_DEBUG && _TRACE_SPLIT)
{
printf("inner_ndim: %lu\n",inner_ndim);
printf("arg_len: %lu\n", arg_len);
printf("total: %lu\n", dimensions[0]);
printf("dimensions: ");
for(size_t j = 0; j < arg_len; j++)
printf("%lu, ", ((size_t *)dimensions)[j]);
printf("\nsteps: ");
for(size_t j = 0; j < array_count; j++)
printf("%lu, ", steps[j]);
printf("\n*args: ");
for(size_t j = 0; j < array_count; j++)
printf("%p, ", (void *)args[j]);
printf("\n");
}
// This is making the assumption that the calling thread knows the truth
// about num_threads, which should be correct via the following:
// program starts/reinits and the threadpool launches, num_threads TLS is
// set as default. Any thread spawned on init making a call to this function
// will have a valid num_threads TLS slot and so the task_arena is sized
// appropriately and it's value is used in the observer that fixes the TLS
// slots of any subsequent threads joining the task_arena. This leads to
// all threads in a task_arena having valid num_threads TLS slots prior to
// doing any work. Any further call to query the TLS slot value made by any
// thread in the arena is then safe and were any thread to create a nested
// parallel region the same logic applies as per program start/reinit.
tbb::task_arena limited(num_threads);
fix_tls_observer observer(limited, num_threads);
limited.execute([&]{
using range_t = tbb::blocked_range<size_t>;
tbb::parallel_for(range_t(0, dimensions[0]), [=](const range_t &range)
{
size_t * count_space = (size_t *)alloca(sizeof(size_t) * arg_len);
char ** array_arg_space = (char**)alloca(sizeof(char*) * array_count);
memcpy(count_space, dimensions, arg_len * sizeof(size_t));
count_space[0] = range.size();
if(_DEBUG && _TRACE_SPLIT > 1)
{
printf("THREAD %p:", count_space);
printf("count_space: ");
for(size_t j = 0; j < arg_len; j++)
printf("%lu, ", count_space[j]);
printf("\n");
}
for(size_t j = 0; j < array_count; j++)
{
char * base = args[j];
size_t step = steps[j];
ptrdiff_t offset = step * range.begin();
array_arg_space[j] = base + offset;
if(_DEBUG && _TRACE_SPLIT > 2)
{
printf("Index %ld\n", j);
printf("-->Got base %p\n", (void *)base);
printf("-->Got step %lu\n", step);
printf("-->Got offset %ld\n", offset);
printf("-->Got addr %p\n", (void *)array_arg_space[j]);
}
}
if(_DEBUG && _TRACE_SPLIT > 2)
{
printf("array_arg_space: ");
for(size_t j = 0; j < array_count; j++)
printf("%p, ", (void *)array_arg_space[j]);
printf("\n");
}
auto func = reinterpret_cast<void (*)(char **args, size_t *dims, size_t *steps, void *data)>(fn);
func(array_arg_space, count_space, steps, data);
});
});
}
static std::thread::id init_thread_id;
static THREAD_LOCAL(bool) need_reinit_after_fork = false;
static void set_main_thread()
{
init_thread_id = std::this_thread::get_id();
}
static bool is_main_thread()
{
return std::this_thread::get_id() == init_thread_id;
}
static void prepare_fork(void)
{
if(_DEBUG)
{
puts("Suspending TBB: prepare fork");
}
if (tsh_was_initialized)
{
if(is_main_thread())
{
if (tbb::finalize(tsh, std::nothrow))
{
tsh_was_initialized = false;
need_reinit_after_fork = true;
}
else
{
puts("Unable to join threads to shut down before fork(). "
"This can break multithreading in child processes.\n");
}
}
else
{
fprintf(stderr, "Numba: Attempted to fork from a non-main thread, "
"the TBB library may be in an invalid state in the "
"child process.\n");
}
}
}
static void reset_after_fork(void)
{
if(_DEBUG)
{
puts("Resuming TBB: after fork");
}
if(need_reinit_after_fork)
{
tsh = tbb::task_scheduler_handle::get();
set_main_thread();
need_reinit_after_fork = false;
}
}
static void unload_tbb(void)
{
if (tg)
{
if(_DEBUG)
{
puts("Unloading TBB");
}
tg->wait();
delete tg;
tg = NULL;
}
if (tsh_was_initialized)
{
// blocking terminate is not strictly required here, ignore return value
(void)tbb::finalize(tsh, std::nothrow);
tsh_was_initialized = false;
}
}
static void launch_threads(int count)
{
if(tg)
return;
if(_DEBUG)
puts("Using TBB");
if(count < 1)
count = tbb::task_arena::automatic;
tsh = tbb::task_scheduler_handle::get();
tsh_was_initialized = true;
tg = new tbb::task_group;
tg->run([] {}); // start creating threads asynchronously
_INIT_NUM_THREADS = count;
set_main_thread();
#ifndef _MSC_VER
pthread_atfork(prepare_fork, reset_after_fork, reset_after_fork);
#endif
}
static void synchronize(void)
{
tg->wait();
}
static void ready(void)
{
}
MOD_INIT(tbbpool)
{
PyObject *m;
MOD_DEF(m, "tbbpool", "No docs", NULL)
if (m == NULL)
return MOD_ERROR_VAL;
PyModuleDef *md = PyModule_GetDef(m);
if (md)
{
md->m_free = (freefunc)unload_tbb;
}
PyObject_SetAttrString(m, "launch_threads",
PyLong_FromVoidPtr((void*)&launch_threads));
PyObject_SetAttrString(m, "synchronize",
PyLong_FromVoidPtr((void*)&synchronize));
PyObject_SetAttrString(m, "ready",
PyLong_FromVoidPtr((void*)&ready));
PyObject_SetAttrString(m, "add_task",
PyLong_FromVoidPtr((void*)&add_task));
PyObject_SetAttrString(m, "parallel_for",
PyLong_FromVoidPtr((void*)¶llel_for));
PyObject_SetAttrString(m, "do_scheduling_signed",
PyLong_FromVoidPtr((void*)&do_scheduling_signed));
PyObject_SetAttrString(m, "do_scheduling_unsigned",
PyLong_FromVoidPtr((void*)&do_scheduling_unsigned));
PyObject_SetAttrString(m, "set_num_threads",
PyLong_FromVoidPtr((void*)&set_num_threads));
PyObject_SetAttrString(m, "get_num_threads",
PyLong_FromVoidPtr((void*)&get_num_threads));
PyObject_SetAttrString(m, "get_thread_id",
PyLong_FromVoidPtr((void*)&get_thread_id));
return MOD_SUCCESS_VAL(m);
}
<commit_msg>Fix lifetime of task_scheduler_handle<commit_after>/*
Implement parallel vectorize workqueue on top of Intel TBB.
*/
#define TBB_PREVIEW_WAITING_FOR_WORKERS 1
/* tbb.h redefines these */
#include "../../_pymodule.h"
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif
#ifdef _XOPEN_SOURCE
#undef _XOPEN_SOURCE
#endif
#include <tbb/tbb.h>
#include <string.h>
#include <stdio.h>
#include <thread>
#include "workqueue.h"
#include "gufunc_scheduler.h"
/* TBB 2019 U5 is the minimum required version as this is needed:
* https://github.com/intel/tbb/blob/18070344d755ece04d169e6cc40775cae9288cee/CHANGES#L133-L134
* and therefore
* https://github.com/intel/tbb/blob/18070344d755ece04d169e6cc40775cae9288cee/CHANGES#L128-L129
* from here:
* https://github.com/intel/tbb/blob/2019_U5/include/tbb/tbb_stddef.h#L29
*/
#if TBB_INTERFACE_VERSION < 12010
#error "TBB version is too old, 2021 update 1, i.e. TBB_INTERFACE_VERSION >= 12010 required"
#endif
#define _DEBUG 0
#define _TRACE_SPLIT 0
static tbb::task_group *tg = NULL;
static tbb::task_scheduler_handle tsh;
static bool tsh_was_initialized = false;
#ifdef _MSC_VER
#define THREAD_LOCAL(ty) __declspec(thread) ty
#else
/* Non-standard C99 extension that's understood by gcc and clang */
#define THREAD_LOCAL(ty) __thread ty
#endif
// This is the number of threads that is default, it is set on initialisation of
// the threading backend via the launch_threads() call
static int _INIT_NUM_THREADS = -1;
// This is the per-thread thread mask, each thread can carry its own mask.
static THREAD_LOCAL(int) _TLS_num_threads = 0;
static void
set_num_threads(int count)
{
_TLS_num_threads = count;
}
static int
get_num_threads(void)
{
if (_TLS_num_threads == 0)
{
// This is a thread that did not call launch_threads() but is still a
// "main" thread, probably from e.g. threading.Thread() use, it still
// has a TLS slot which is 0 from the lack of launch_threads() call
_TLS_num_threads = _INIT_NUM_THREADS;
}
return _TLS_num_threads;
}
static int
get_thread_id(void)
{
return tbb::this_task_arena::current_thread_index();
}
// watch the arena, if it decides to create more threads/add threads into the
// arena then make sure they get the right thread count
class fix_tls_observer: public tbb::task_scheduler_observer {
int mask_val;
void on_scheduler_entry( bool is_worker ) override;
public:
fix_tls_observer(tbb::task_arena &arena, int mask) : tbb::task_scheduler_observer(arena), mask_val(mask)
{
observe(true);
}
};
void fix_tls_observer::on_scheduler_entry(bool worker) {
set_num_threads(mask_val);
}
static void
add_task(void *fn, void *args, void *dims, void *steps, void *data)
{
tg->run([=]
{
auto func = reinterpret_cast<void (*)(void *args, void *dims, void *steps, void *data)>(fn);
func(args, dims, steps, data);
});
}
static void
parallel_for(void *fn, char **args, size_t *dimensions, size_t *steps, void *data,
size_t inner_ndim, size_t array_count, int num_threads)
{
static bool printed = false;
if(!printed && _DEBUG)
{
puts("Using parallel_for");
printed = true;
}
// args = <ir.Argument '.1' of type i8**>,
// dimensions = <ir.Argument '.2' of type i64*>
// steps = <ir.Argument '.3' of type i64*>
// data = <ir.Argument '.4' of type i8*>
const size_t arg_len = (inner_ndim + 1);
if(_DEBUG && _TRACE_SPLIT)
{
printf("inner_ndim: %lu\n",inner_ndim);
printf("arg_len: %lu\n", arg_len);
printf("total: %lu\n", dimensions[0]);
printf("dimensions: ");
for(size_t j = 0; j < arg_len; j++)
printf("%lu, ", ((size_t *)dimensions)[j]);
printf("\nsteps: ");
for(size_t j = 0; j < array_count; j++)
printf("%lu, ", steps[j]);
printf("\n*args: ");
for(size_t j = 0; j < array_count; j++)
printf("%p, ", (void *)args[j]);
printf("\n");
}
// This is making the assumption that the calling thread knows the truth
// about num_threads, which should be correct via the following:
// program starts/reinits and the threadpool launches, num_threads TLS is
// set as default. Any thread spawned on init making a call to this function
// will have a valid num_threads TLS slot and so the task_arena is sized
// appropriately and it's value is used in the observer that fixes the TLS
// slots of any subsequent threads joining the task_arena. This leads to
// all threads in a task_arena having valid num_threads TLS slots prior to
// doing any work. Any further call to query the TLS slot value made by any
// thread in the arena is then safe and were any thread to create a nested
// parallel region the same logic applies as per program start/reinit.
tbb::task_arena limited(num_threads);
fix_tls_observer observer(limited, num_threads);
limited.execute([&]{
using range_t = tbb::blocked_range<size_t>;
tbb::parallel_for(range_t(0, dimensions[0]), [=](const range_t &range)
{
size_t * count_space = (size_t *)alloca(sizeof(size_t) * arg_len);
char ** array_arg_space = (char**)alloca(sizeof(char*) * array_count);
memcpy(count_space, dimensions, arg_len * sizeof(size_t));
count_space[0] = range.size();
if(_DEBUG && _TRACE_SPLIT > 1)
{
printf("THREAD %p:", count_space);
printf("count_space: ");
for(size_t j = 0; j < arg_len; j++)
printf("%lu, ", count_space[j]);
printf("\n");
}
for(size_t j = 0; j < array_count; j++)
{
char * base = args[j];
size_t step = steps[j];
ptrdiff_t offset = step * range.begin();
array_arg_space[j] = base + offset;
if(_DEBUG && _TRACE_SPLIT > 2)
{
printf("Index %ld\n", j);
printf("-->Got base %p\n", (void *)base);
printf("-->Got step %lu\n", step);
printf("-->Got offset %ld\n", offset);
printf("-->Got addr %p\n", (void *)array_arg_space[j]);
}
}
if(_DEBUG && _TRACE_SPLIT > 2)
{
printf("array_arg_space: ");
for(size_t j = 0; j < array_count; j++)
printf("%p, ", (void *)array_arg_space[j]);
printf("\n");
}
auto func = reinterpret_cast<void (*)(char **args, size_t *dims, size_t *steps, void *data)>(fn);
func(array_arg_space, count_space, steps, data);
});
});
}
static std::thread::id init_thread_id;
static THREAD_LOCAL(bool) need_reinit_after_fork = false;
static void set_main_thread()
{
init_thread_id = std::this_thread::get_id();
}
static bool is_main_thread()
{
return std::this_thread::get_id() == init_thread_id;
}
static void prepare_fork(void)
{
if(_DEBUG)
{
puts("Suspending TBB: prepare fork");
}
if (tsh_was_initialized)
{
if(is_main_thread())
{
if (!tbb::finalize(tsh, std::nothrow))
{
tbb::task_scheduler_handle::release(tsh);
puts("Unable to join threads to shut down before fork(). "
"This can break multithreading in child processes.\n");
}
tsh_was_initialized = false;
need_reinit_after_fork = true;
}
else
{
fprintf(stderr, "Numba: Attempted to fork from a non-main thread, "
"the TBB library may be in an invalid state in the "
"child process.\n");
}
}
}
static void reset_after_fork(void)
{
if(_DEBUG)
{
puts("Resuming TBB: after fork");
}
if(need_reinit_after_fork)
{
tsh = tbb::task_scheduler_handle::get();
set_main_thread();
tsh_was_initialized = true;
need_reinit_after_fork = false;
}
}
static void unload_tbb(void)
{
if (tg)
{
if(_DEBUG)
{
puts("Unloading TBB");
}
tg->wait();
delete tg;
tg = NULL;
}
if (tsh_was_initialized)
{
// blocking terminate is not strictly required here, ignore return value
(void)tbb::finalize(tsh, std::nothrow);
tsh_was_initialized = false;
}
}
static void launch_threads(int count)
{
if(tg)
return;
if(_DEBUG)
puts("Using TBB");
if(count < 1)
count = tbb::task_arena::automatic;
tsh = tbb::task_scheduler_handle::get();
tsh_was_initialized = true;
tg = new tbb::task_group;
tg->run([] {}); // start creating threads asynchronously
_INIT_NUM_THREADS = count;
set_main_thread();
#ifndef _MSC_VER
pthread_atfork(prepare_fork, reset_after_fork, reset_after_fork);
#endif
}
static void synchronize(void)
{
tg->wait();
}
static void ready(void)
{
}
MOD_INIT(tbbpool)
{
PyObject *m;
MOD_DEF(m, "tbbpool", "No docs", NULL)
if (m == NULL)
return MOD_ERROR_VAL;
PyModuleDef *md = PyModule_GetDef(m);
if (md)
{
md->m_free = (freefunc)unload_tbb;
}
PyObject_SetAttrString(m, "launch_threads",
PyLong_FromVoidPtr((void*)&launch_threads));
PyObject_SetAttrString(m, "synchronize",
PyLong_FromVoidPtr((void*)&synchronize));
PyObject_SetAttrString(m, "ready",
PyLong_FromVoidPtr((void*)&ready));
PyObject_SetAttrString(m, "add_task",
PyLong_FromVoidPtr((void*)&add_task));
PyObject_SetAttrString(m, "parallel_for",
PyLong_FromVoidPtr((void*)¶llel_for));
PyObject_SetAttrString(m, "do_scheduling_signed",
PyLong_FromVoidPtr((void*)&do_scheduling_signed));
PyObject_SetAttrString(m, "do_scheduling_unsigned",
PyLong_FromVoidPtr((void*)&do_scheduling_unsigned));
PyObject_SetAttrString(m, "set_num_threads",
PyLong_FromVoidPtr((void*)&set_num_threads));
PyObject_SetAttrString(m, "get_num_threads",
PyLong_FromVoidPtr((void*)&get_num_threads));
PyObject_SetAttrString(m, "get_thread_id",
PyLong_FromVoidPtr((void*)&get_thread_id));
return MOD_SUCCESS_VAL(m);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: staticassert.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2003-12-09 11:47:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
#ifndef WW_STATICASSERT_HXX
#define WW_STATICASSERT_HXX
/*
Lifted direct from:
Modern C++ Design: Generic Programming and Design Patterns Applied
Section 2.1
by Andrei Alexandrescu
*/
namespace ww
{
template<bool> class compile_time_check
{
public:
compile_time_check(...) {}
};
template<> class compile_time_check<false>
{
};
}
/*
Similiar to assert, StaticAssert is only in operation when NDEBUG is not
defined. It will test its first argument at compile time and on failure
report the error message of the second argument, which must be a valid c++
classname. i.e. no spaces, punctuation or reserved keywords.
*/
#ifndef NDEBUG
# define StaticAssert(test, errormsg) \
do { \
struct ERROR_##errormsg {}; \
typedef ww::compile_time_check< (test) != 0 > tmplimpl; \
tmplimpl aTemp = tmplimpl(ERROR_##errormsg()); \
sizeof(aTemp); \
} while (0)
#else
# define StaticAssert(test, errormsg) \
do {} while (0)
#endif
#endif
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.896); FILE MERGED 2005/09/05 13:42:29 rt 1.4.896.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: staticassert.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 06:05:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
#ifndef WW_STATICASSERT_HXX
#define WW_STATICASSERT_HXX
/*
Lifted direct from:
Modern C++ Design: Generic Programming and Design Patterns Applied
Section 2.1
by Andrei Alexandrescu
*/
namespace ww
{
template<bool> class compile_time_check
{
public:
compile_time_check(...) {}
};
template<> class compile_time_check<false>
{
};
}
/*
Similiar to assert, StaticAssert is only in operation when NDEBUG is not
defined. It will test its first argument at compile time and on failure
report the error message of the second argument, which must be a valid c++
classname. i.e. no spaces, punctuation or reserved keywords.
*/
#ifndef NDEBUG
# define StaticAssert(test, errormsg) \
do { \
struct ERROR_##errormsg {}; \
typedef ww::compile_time_check< (test) != 0 > tmplimpl; \
tmplimpl aTemp = tmplimpl(ERROR_##errormsg()); \
sizeof(aTemp); \
} while (0)
#else
# define StaticAssert(test, errormsg) \
do {} while (0)
#endif
#endif
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<|endoftext|>
|
<commit_before>#ifndef VIENNAGRID_ALGORITHM_ANGLE_HPP
#define VIENNAGRID_ALGORITHM_ANGLE_HPP
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
namespace viennagrid
{
namespace detail
{
template<typename DomainType, typename ScalarType, typename PointAccessorType>
void scale_impl(DomainType& domain, ScalarType factor, PointAccessorType accessor)
{
typedef typename viennagrid::result_of::element<DomainType, viennagrid::vertex_tag>::type VertexType;
typedef typename viennagrid::result_of::element_range<DomainType, viennagrid::vertex_tag>::type VertexContainer;
typedef typename viennagrid::result_of::iterator<VertexContainer>::type VertexIterator;
VertexContainer vertices = viennagrid::elements<VertexType>(domain);
for ( VertexIterator vit = vertices.begin();
vit != vertices.end();
++vit )
{
accessor(*vit) *= factor;
}
}
} // detail
template<typename DomainType, typename ScalarType>
void scale(DomainType& domain, ScalarType factor)
{
viennagrid::detail::scale_impl(domain, factor, viennagrid::default_point_accessor(domain));
}
} // viennagrid
#endif
<commit_msg>Fixed include guard<commit_after>#ifndef VIENNAGRID_ALGORITHM_SCALE_HPP
#define VIENNAGRID_ALGORITHM_SCALE_HPP
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
namespace viennagrid
{
namespace detail
{
template<typename DomainType, typename ScalarType, typename PointAccessorType>
void scale_impl(DomainType& domain, ScalarType factor, PointAccessorType accessor)
{
typedef typename viennagrid::result_of::element<DomainType, viennagrid::vertex_tag>::type VertexType;
typedef typename viennagrid::result_of::element_range<DomainType, viennagrid::vertex_tag>::type VertexContainer;
typedef typename viennagrid::result_of::iterator<VertexContainer>::type VertexIterator;
VertexContainer vertices = viennagrid::elements<VertexType>(domain);
for ( VertexIterator vit = vertices.begin();
vit != vertices.end();
++vit )
{
accessor(*vit) *= factor;
}
}
} // detail
template<typename DomainType, typename ScalarType>
void scale(DomainType& domain, ScalarType factor)
{
viennagrid::detail::scale_impl(domain, factor, viennagrid::default_point_accessor(domain));
}
} // viennagrid
#endif
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.