{"text":"\/* Copyright (C) 2012,2013 IBM Corp.\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n#include \"FHE.h\"\n#include \"timing.h\"\n#include \"EncryptedArray.h\"\n#include \n\n#include \n\n\nZZX makeIrredPoly(long p, long d)\n{\n assert(d >= 1);\n assert(ProbPrime(p));\n\n if (d == 1) return ZZX(1, 1); \/\/ the monomial X\n\n zz_pBak bak; bak.save();\n zz_p::init(p);\n return to_ZZX(BuildIrred_zz_pX(d));\n}\n\n\ntemplate \nclass RunningSumMatrix : public PlaintextMatrixInterface {\npublic:\n PA_INJECT(type) \n\nprivate:\n const EncryptedArray& ea;\n\npublic:\n ~RunningSumMatrix() { cerr << \"destructor: running sum matrix\\n\"; }\n\n RunningSumMatrix(const EncryptedArray& _ea) : ea(_ea) { }\n\n virtual const EncryptedArray& getEA() const {\n return ea;\n }\n\n virtual void get(RX& out, long i, long j) const {\n assert(i >= 0 && i < ea.size());\n assert(j >= 0 && j < ea.size());\n if (j >= i)\n out = 1;\n else\n out = 0;\n }\n};\n\n\nPlaintextMatrixBaseInterface *\nbuildRunningSumMatrix(const EncryptedArray& ea)\n{\n switch (ea.getContext().alMod.getTag()) {\n case PA_GF2_tag: {\n return new RunningSumMatrix(ea);\n }\n\n case PA_zz_p_tag: {\n return new RunningSumMatrix(ea);\n }\n\n default: return 0;\n }\n}\n\n\ntemplate \nclass RandomMatrix : public PlaintextMatrixInterface {\npublic:\n PA_INJECT(type) \n\nprivate:\n const EncryptedArray& ea;\n\n vector< vector< RX > > data;\n\npublic:\n ~RandomMatrix() { cerr << \"destructor: random matrix\\n\"; }\n\n RandomMatrix(const EncryptedArray& _ea) : ea(_ea) { \n long n = ea.size();\n long d = ea.getDegree();\n\n RBak bak; bak.save(); ea.getContext().alMod.restoreContext();\n\n data.resize(n);\n for (long i = 0; i < n; i++) {\n data[i].resize(n);\n for (long j = 0; j < n; j++)\n random(data[i][j], d);\n }\n }\n\n virtual const EncryptedArray& getEA() const {\n return ea;\n }\n\n virtual void get(RX& out, long i, long j) const {\n assert(i >= 0 && i < ea.size());\n assert(j >= 0 && j < ea.size());\n out = data[i][j];\n }\n};\n\n\nPlaintextMatrixBaseInterface *\nbuildRandomMatrix(const EncryptedArray& ea)\n{\n switch (ea.getContext().alMod.getTag()) {\n case PA_GF2_tag: {\n return new RandomMatrix(ea);\n }\n\n case PA_zz_p_tag: {\n return new RandomMatrix(ea);\n }\n\n default: return 0;\n }\n}\n\n\n\n\n\nvoid TestIt(long R, long p, long r, long d, long c, long k, long w, \n long L, long m)\n{\n cerr << \"*** TestIt: R=\" << R \n << \", p=\" << p\n << \", r=\" << r\n << \", d=\" << d\n << \", c=\" << c\n << \", k=\" << k\n << \", w=\" << w\n << \", L=\" << L\n << \", m=\" << m\n << endl;\n\n FHEcontext context(m, p, r);\n buildModChain(context, L, c);\n\n context.zMStar.printout();\n cerr << endl;\n\n FHESecKey secretKey(context);\n const FHEPubKey& publicKey = secretKey;\n secretKey.GenSecKey(w); \/\/ A Hamming-weight-w secret key\n\n\n ZZX G;\n\n if (d == 0)\n G = context.alMod.getFactorsOverZZ()[0];\n else\n G = makeIrredPoly(p, d); \n\n cerr << \"G = \" << G << \"\\n\";\n cerr << \"generating key-switching matrices... \";\n addSome1DMatrices(secretKey); \/\/ compute key-switching matrices that we need\n cerr << \"done\\n\";\n\n printAllTimers();\n resetAllTimers();\n\n cerr << \"computing masks and tables for rotation...\";\n EncryptedArray ea(context, G);\n cerr << \"done\\n\";\n\n PlaintextMatrixBaseInterface *ptr =\n buildRandomMatrix(ea);\n\n PlaintextArray v(ea);\n\n\/*\n v.encode(1);\n \n v.print(cout); cout << \"\\n\";\n\n v.alt_mul(*ptr);\n\n v.print(cout); cout << \"\\n\";\n*\/\n\n v.random();\n \/\/ v.print(cout); cout << \"\\n\";\n\n PlaintextArray v1(ea);\n v1 = v;\n\n Ctxt ctxt(publicKey);\n ea.encrypt(ctxt, publicKey, v);\n\n v.mat_mul(*ptr);\n\n ea.mat_mul(ctxt, *ptr);\n ea.decrypt(ctxt, secretKey, v1);\n\n \/\/ v.print(cout); cout << \"\\n\";\n \/\/ v1.print(cout); cout << \"\\n\";\n\n if (v.equals(v1))\n cout << \"Nice!!\\n\";\n else\n cout << \"Grrr...\\n\";\n\n}\n\nvoid usage(char *prog) \n{\n cerr << \"Usage: \"< factors[0] defined the extension)\\n\";\n cerr << \" c is number of columns in the key-switching matrices [default=2]\\n\";\n cerr << \" k is the security parameter [default=80]\\n\";\n cerr << \" L is the # of primes in the modulus chai [default=4*R]\\n\";\n cerr << \" s is the minimum number of slots [default=4]\\n\";\n cerr << \" m defined the cyclotomic polynomial Phi_m(X)\\n\";\n exit(0);\n}\n\n\nint main(int argc, char *argv[]) \n{\n argmap_t argmap;\n argmap[\"R\"] = \"1\";\n argmap[\"p\"] = \"2\";\n argmap[\"r\"] = \"1\";\n argmap[\"d\"] = \"1\";\n argmap[\"c\"] = \"2\";\n argmap[\"k\"] = \"80\";\n argmap[\"L\"] = \"0\";\n argmap[\"s\"] = \"0\";\n argmap[\"m\"] = \"0\";\n\n \/\/ get parameters from the command line\n if (!parseArgs(argc, argv, argmap)) usage(argv[0]);\n\n long R = atoi(argmap[\"R\"]);\n long p = atoi(argmap[\"p\"]);\n long r = atoi(argmap[\"r\"]);\n long d = atoi(argmap[\"d\"]);\n long c = atoi(argmap[\"c\"]);\n long k = atoi(argmap[\"k\"]);\n \/\/ long z = atoi(argmap[\"z\"]);\n long L = atoi(argmap[\"L\"]);\n if (L==0) { \/\/ determine L based on R,r\n if (r==1) L = 2*R+2;\n else L = 4*R;\n }\n long s = atoi(argmap[\"s\"]);\n long chosen_m = atoi(argmap[\"m\"]);\n\n long w = 64; \/\/ Hamming weight of secret key\n \/\/ long L = z*R; \/\/ number of levels\n\n long m = FindM(k, L, c, p, d, s, chosen_m, true);\n\n setTimersOn();\n TestIt(R, p, r, d, c, k, w, L, m);\n\n cerr << endl;\n printAllTimers();\n cerr << endl;\n\n}\n\nAdded comments in the code\/* Copyright (C) 2012,2013 IBM Corp.\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n#include \"FHE.h\"\n#include \"timing.h\"\n#include \"EncryptedArray.h\"\n#include \n\n#include \n\n\nZZX makeIrredPoly(long p, long d)\n{\n assert(d >= 1);\n assert(ProbPrime(p));\n\n if (d == 1) return ZZX(1, 1); \/\/ the monomial X\n\n zz_pBak bak; bak.save();\n zz_p::init(p);\n return to_ZZX(BuildIrred_zz_pX(d));\n}\n\n\ntemplate \nclass RunningSumMatrix : public PlaintextMatrixInterface {\npublic:\n PA_INJECT(type) \n\nprivate:\n const EncryptedArray& ea;\n\npublic:\n ~RunningSumMatrix() { cerr << \"destructor: running sum matrix\\n\"; }\n\n RunningSumMatrix(const EncryptedArray& _ea) : ea(_ea) { }\n\n virtual const EncryptedArray& getEA() const {\n return ea;\n }\n\n virtual void get(RX& out, long i, long j) const {\n assert(i >= 0 && i < ea.size());\n assert(j >= 0 && j < ea.size());\n if (j >= i)\n out = 1;\n else\n out = 0;\n }\n};\n\n\nPlaintextMatrixBaseInterface *\nbuildRunningSumMatrix(const EncryptedArray& ea)\n{\n switch (ea.getContext().alMod.getTag()) {\n case PA_GF2_tag: {\n return new RunningSumMatrix(ea);\n }\n\n case PA_zz_p_tag: {\n return new RunningSumMatrix(ea);\n }\n\n default: return 0;\n }\n}\n\n\ntemplate \nclass RandomMatrix : public PlaintextMatrixInterface {\npublic:\n PA_INJECT(type) \n\nprivate:\n const EncryptedArray& ea;\n\n vector< vector< RX > > data;\n\npublic:\n ~RandomMatrix() { cerr << \"destructor: random matrix\\n\"; }\n\n RandomMatrix(const EncryptedArray& _ea) : ea(_ea) { \n long n = ea.size();\n long d = ea.getDegree();\n\n RBak bak; bak.save(); ea.getContext().alMod.restoreContext();\n\n data.resize(n);\n for (long i = 0; i < n; i++) {\n data[i].resize(n);\n for (long j = 0; j < n; j++)\n random(data[i][j], d);\n }\n }\n\n virtual const EncryptedArray& getEA() const {\n return ea;\n }\n\n virtual void get(RX& out, long i, long j) const {\n assert(i >= 0 && i < ea.size());\n assert(j >= 0 && j < ea.size());\n out = data[i][j];\n }\n};\n\n\nPlaintextMatrixBaseInterface *\nbuildRandomMatrix(const EncryptedArray& ea)\n{\n switch (ea.getContext().alMod.getTag()) {\n case PA_GF2_tag: {\n return new RandomMatrix(ea);\n }\n\n case PA_zz_p_tag: {\n return new RandomMatrix(ea);\n }\n\n default: return 0;\n }\n}\n\n\n\n\n\nvoid TestIt(long R, long p, long r, long d, long c, long k, long w, \n long L, long m)\n{\n cerr << \"*** TestIt: R=\" << R \n << \", p=\" << p\n << \", r=\" << r\n << \", d=\" << d\n << \", c=\" << c\n << \", k=\" << k\n << \", w=\" << w\n << \", L=\" << L\n << \", m=\" << m\n << endl;\n\n FHEcontext context(m, p, r);\n buildModChain(context, L, c);\n\n context.zMStar.printout();\n cerr << endl;\n\n FHESecKey secretKey(context);\n const FHEPubKey& publicKey = secretKey;\n secretKey.GenSecKey(w); \/\/ A Hamming-weight-w secret key\n\n\n ZZX G;\n\n if (d == 0)\n G = context.alMod.getFactorsOverZZ()[0];\n else\n G = makeIrredPoly(p, d); \n\n cerr << \"G = \" << G << \"\\n\";\n cerr << \"generating key-switching matrices... \";\n addSome1DMatrices(secretKey); \/\/ compute key-switching matrices that we need\n cerr << \"done\\n\";\n\n printAllTimers();\n resetAllTimers();\n\n cerr << \"computing masks and tables for rotation...\";\n EncryptedArray ea(context, G);\n cerr << \"done\\n\";\n\n \/\/ choose a random plaintext square matrix\n PlaintextMatrixBaseInterface *ptr = buildRandomMatrix(ea);\n\n \/\/ choose a random plaintext vector\n PlaintextArray v(ea);\n\n\/* v.encode(1); \n v.print(cout); cout << \"\\n\";\n v.alt_mul(*ptr);\n*\/\n v.random();\n \/\/ v.print(cout); cout << \"\\n\";\n\n \/\/ encrypt the random vector\n Ctxt ctxt(publicKey);\n ea.encrypt(ctxt, publicKey, v);\n\n v.mat_mul(*ptr); \/\/ multiply the plaintext vector\n ea.mat_mul(ctxt, *ptr); \/\/ multiply the ciphertext vector\n\n PlaintextArray v1(ea);\n \/\/ v1 = v;\n ea.decrypt(ctxt, secretKey, v1); \/\/ decrypt the ciphertext vector\n\n if (v.equals(v1)) \/\/ check that we've got the right answer\n cout << \"Nice!!\\n\";\n else\n cout << \"Grrr...\\n\";\n\n \/\/ v.print(cout); cout << \"\\n\";\n \/\/ v1.print(cout); cout << \"\\n\";\n}\n\nvoid usage(char *prog) \n{\n cerr << \"Usage: \"< factors[0] defined the extension)\\n\";\n cerr << \" c is number of columns in the key-switching matrices [default=2]\\n\";\n cerr << \" k is the security parameter [default=80]\\n\";\n cerr << \" L is the # of primes in the modulus chai [default=4*R]\\n\";\n cerr << \" s is the minimum number of slots [default=4]\\n\";\n cerr << \" m defined the cyclotomic polynomial Phi_m(X)\\n\";\n exit(0);\n}\n\n\nint main(int argc, char *argv[]) \n{\n argmap_t argmap;\n argmap[\"R\"] = \"1\";\n argmap[\"p\"] = \"2\";\n argmap[\"r\"] = \"1\";\n argmap[\"d\"] = \"1\";\n argmap[\"c\"] = \"2\";\n argmap[\"k\"] = \"80\";\n argmap[\"L\"] = \"0\";\n argmap[\"s\"] = \"0\";\n argmap[\"m\"] = \"0\";\n\n \/\/ get parameters from the command line\n if (!parseArgs(argc, argv, argmap)) usage(argv[0]);\n\n long R = atoi(argmap[\"R\"]);\n long p = atoi(argmap[\"p\"]);\n long r = atoi(argmap[\"r\"]);\n long d = atoi(argmap[\"d\"]);\n long c = atoi(argmap[\"c\"]);\n long k = atoi(argmap[\"k\"]);\n \/\/ long z = atoi(argmap[\"z\"]);\n long L = atoi(argmap[\"L\"]);\n if (L==0) { \/\/ determine L based on R,r\n if (r==1) L = 2*R+2;\n else L = 4*R;\n }\n long s = atoi(argmap[\"s\"]);\n long chosen_m = atoi(argmap[\"m\"]);\n\n long w = 64; \/\/ Hamming weight of secret key\n \/\/ long L = z*R; \/\/ number of levels\n\n long m = FindM(k, L, c, p, d, s, chosen_m, true);\n\n setTimersOn();\n TestIt(R, p, r, d, c, k, w, L, m);\n\n cerr << endl;\n printAllTimers();\n cerr << endl;\n\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: testfactreg.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 13:34:44 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_extensions.hxx\"\n#include \n\n#include \/\/ for EXTERN_SERVICE_CALLTYPE\n\n#include \n#include \"testfactreg.hxx\"\n\n\n#ifndef _VOS_NO_NAMESPACE\nusing namespace vos;\nusing namespace usr;\n#endif\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\nBOOL EXTERN_SERVICE_CALLTYPE exService_writeRegEntry(\n const UNO_INTERFACE(XRegistryKey)* xUnoKey)\n\n{\n XRegistryKeyRef xKey;\n uno2smart(xKey, *xUnoKey);\n\n UString str = UString( L\"\/\" ) + OPipeTest_getImplementationName() + UString( L\"\/UNO\/SERVICES\" );\n XRegistryKeyRef xNewKey = xKey->createKey( str );\n xNewKey->createKey( OPipeTest_getServiceName() );\n\n str = UString( L\"\/\" ) + ODataStreamTest_getImplementationName(1) + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( ODataStreamTest_getServiceName(1) );\n\n str = UString( L\"\/\" ) + ODataStreamTest_getImplementationName(2) + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( ODataStreamTest_getServiceName(2) );\n\n str = UString( L\"\/\" ) + OObjectStreamTest_getImplementationName(1) + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( OObjectStreamTest_getServiceName(1) );\n\n str = UString( L\"\/\" ) + OObjectStreamTest_getImplementationName(2) + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( OObjectStreamTest_getServiceName(2) );\n\n str = UString( L\"\/\" ) + OMarkableOutputStreamTest_getImplementationName() + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( OMarkableOutputStreamTest_getServiceName() );\n\n str = UString( L\"\/\" ) + OMarkableInputStreamTest_getImplementationName() + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( OMarkableInputStreamTest_getServiceName() );\n\n str = UString( L\"\/\" ) + OMyPersistObject_getImplementationName() + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( OMyPersistObject_getServiceName() );\n\n return TRUE;\n}\n\n\nUNO_INTERFACE(XInterface) EXTERN_SERVICE_CALLTYPE exService_getFactory\n(\n const wchar_t* implementationName,\n const UNO_INTERFACE(XMultiServiceFactory)* xUnoFact,\n const UNO_INTERFACE(XRegistryKey)*\n)\n{\n UNO_INTERFACE(XInterface) xUnoRet = {0, 0};\n\n XInterfaceRef xRet;\n XMultiServiceFactoryRef xSMgr;\n UString aImplementationName(implementationName);\n\n uno2smart(xSMgr, *xUnoFact);\n\n if (aImplementationName == OPipeTest_getImplementationName() )\n {\n xRet = createSingleFactory( xSMgr, implementationName,\n OPipeTest_CreateInstance,\n OPipeTest_getSupportedServiceNames() );\n }\n else if( aImplementationName == ODataStreamTest_getImplementationName(1) ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n ODataStreamTest_CreateInstance,\n ODataStreamTest_getSupportedServiceNames(1) );\n }\n else if( aImplementationName == ODataStreamTest_getImplementationName(2) ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n ODataStreamTest_CreateInstance,\n ODataStreamTest_getSupportedServiceNames(2) );\n }\n else if( aImplementationName == OObjectStreamTest_getImplementationName(1) ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n OObjectStreamTest_CreateInstance,\n OObjectStreamTest_getSupportedServiceNames(1) );\n }\n else if( aImplementationName == OObjectStreamTest_getImplementationName(2) ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n OObjectStreamTest_CreateInstance,\n OObjectStreamTest_getSupportedServiceNames(2) );\n }\n else if( aImplementationName == OMarkableOutputStreamTest_getImplementationName() ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n OMarkableOutputStreamTest_CreateInstance,\n OMarkableOutputStreamTest_getSupportedServiceNames() );\n }\n else if( aImplementationName == OMarkableInputStreamTest_getImplementationName() ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n OMarkableInputStreamTest_CreateInstance,\n OMarkableInputStreamTest_getSupportedServiceNames() );\n }\n else if( aImplementationName == OMyPersistObject_getImplementationName() ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n OMyPersistObject_CreateInstance,\n OMyPersistObject_getSupportedServiceNames() );\n }\n if (xRet.is())\n {\n smart2uno(xRet, xUnoRet);\n }\n\n return xUnoRet;\n}\n\n#ifdef __cplusplus\n}\n#endif\n\nSequence createSeq( char * p )\n{\n Sequence seq( strlen( p )+1 );\n strcpy( (char * ) seq.getArray() , p );\n return seq;\n}\n\nSequence createIntSeq( INT32 i )\n{\n char pcCount[20];\n sprintf( pcCount , \"%d\" , i );\n return createSeq( pcCount );\n}\n\nINTEGRATION: CWS changefileheader (1.3.276); FILE MERGED 2008\/03\/31 12:32:36 rt 1.3.276.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: testfactreg.cxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_extensions.hxx\"\n#include \n\n#include \/\/ for EXTERN_SERVICE_CALLTYPE\n\n#include \n#include \"testfactreg.hxx\"\n\n\n#ifndef _VOS_NO_NAMESPACE\nusing namespace vos;\nusing namespace usr;\n#endif\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\nBOOL EXTERN_SERVICE_CALLTYPE exService_writeRegEntry(\n const UNO_INTERFACE(XRegistryKey)* xUnoKey)\n\n{\n XRegistryKeyRef xKey;\n uno2smart(xKey, *xUnoKey);\n\n UString str = UString( L\"\/\" ) + OPipeTest_getImplementationName() + UString( L\"\/UNO\/SERVICES\" );\n XRegistryKeyRef xNewKey = xKey->createKey( str );\n xNewKey->createKey( OPipeTest_getServiceName() );\n\n str = UString( L\"\/\" ) + ODataStreamTest_getImplementationName(1) + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( ODataStreamTest_getServiceName(1) );\n\n str = UString( L\"\/\" ) + ODataStreamTest_getImplementationName(2) + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( ODataStreamTest_getServiceName(2) );\n\n str = UString( L\"\/\" ) + OObjectStreamTest_getImplementationName(1) + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( OObjectStreamTest_getServiceName(1) );\n\n str = UString( L\"\/\" ) + OObjectStreamTest_getImplementationName(2) + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( OObjectStreamTest_getServiceName(2) );\n\n str = UString( L\"\/\" ) + OMarkableOutputStreamTest_getImplementationName() + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( OMarkableOutputStreamTest_getServiceName() );\n\n str = UString( L\"\/\" ) + OMarkableInputStreamTest_getImplementationName() + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( OMarkableInputStreamTest_getServiceName() );\n\n str = UString( L\"\/\" ) + OMyPersistObject_getImplementationName() + UString( L\"\/UNO\/SERVICES\" );\n xNewKey = xKey->createKey( str );\n xNewKey->createKey( OMyPersistObject_getServiceName() );\n\n return TRUE;\n}\n\n\nUNO_INTERFACE(XInterface) EXTERN_SERVICE_CALLTYPE exService_getFactory\n(\n const wchar_t* implementationName,\n const UNO_INTERFACE(XMultiServiceFactory)* xUnoFact,\n const UNO_INTERFACE(XRegistryKey)*\n)\n{\n UNO_INTERFACE(XInterface) xUnoRet = {0, 0};\n\n XInterfaceRef xRet;\n XMultiServiceFactoryRef xSMgr;\n UString aImplementationName(implementationName);\n\n uno2smart(xSMgr, *xUnoFact);\n\n if (aImplementationName == OPipeTest_getImplementationName() )\n {\n xRet = createSingleFactory( xSMgr, implementationName,\n OPipeTest_CreateInstance,\n OPipeTest_getSupportedServiceNames() );\n }\n else if( aImplementationName == ODataStreamTest_getImplementationName(1) ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n ODataStreamTest_CreateInstance,\n ODataStreamTest_getSupportedServiceNames(1) );\n }\n else if( aImplementationName == ODataStreamTest_getImplementationName(2) ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n ODataStreamTest_CreateInstance,\n ODataStreamTest_getSupportedServiceNames(2) );\n }\n else if( aImplementationName == OObjectStreamTest_getImplementationName(1) ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n OObjectStreamTest_CreateInstance,\n OObjectStreamTest_getSupportedServiceNames(1) );\n }\n else if( aImplementationName == OObjectStreamTest_getImplementationName(2) ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n OObjectStreamTest_CreateInstance,\n OObjectStreamTest_getSupportedServiceNames(2) );\n }\n else if( aImplementationName == OMarkableOutputStreamTest_getImplementationName() ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n OMarkableOutputStreamTest_CreateInstance,\n OMarkableOutputStreamTest_getSupportedServiceNames() );\n }\n else if( aImplementationName == OMarkableInputStreamTest_getImplementationName() ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n OMarkableInputStreamTest_CreateInstance,\n OMarkableInputStreamTest_getSupportedServiceNames() );\n }\n else if( aImplementationName == OMyPersistObject_getImplementationName() ) {\n xRet = createSingleFactory( xSMgr , implementationName,\n OMyPersistObject_CreateInstance,\n OMyPersistObject_getSupportedServiceNames() );\n }\n if (xRet.is())\n {\n smart2uno(xRet, xUnoRet);\n }\n\n return xUnoRet;\n}\n\n#ifdef __cplusplus\n}\n#endif\n\nSequence createSeq( char * p )\n{\n Sequence seq( strlen( p )+1 );\n strcpy( (char * ) seq.getArray() , p );\n return seq;\n}\n\nSequence createIntSeq( INT32 i )\n{\n char pcCount[20];\n sprintf( pcCount , \"%d\" , i );\n return createSeq( pcCount );\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n\/\/Boost includes\n#include \"constants.hpp\"\n#include \n\nusing namespace std;\nusing namespace boost::filesystem;\n\n\/\/Key len in bytes (Will be encoded in hex)s\nstatic const path DIR_PATH = path(KEY_NAME_PATH);\n\nstatic const char hexValues[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};\n\nint main(int argc, char** argv)\n{\n if(argc != 6) {\n cout << \"usage: agfs-keygen {host dns name\/ip addr} {port} {user} {local mount point} {key file name}\" << endl;\n return 0;\n }\n \n if(!exists(DIR_PATH)) {\n if(!create_directory(DIR_PATH)) {\n cerr << \"Could not create key directory\" << endl;\n return -ENOENT;\n }\n }\n\n fstream devRandom;\n devRandom.open(\"\/dev\/urandom\", fstream::in);\n\n fstream keyListFile;\n keyListFile.open(KEY_LIST_PATH, fstream::out | fstream::app);\n\n if(!keyListFile.is_open()){\n cerr << \"Could not open keyListFile\" <> 4];\n keyStr += upperByte;\n keyStr += lowerByte;\n ++count;\n }\n\n \/\/print the key to the keyfile\n keyFile << keyStr << endl;\n\n \/\/print mount point, uname, key to the key list file\n keyListFile << argv[4] << \" \" << argv[3] << \" \" << keyStr << endl;\n\n \/\/Close files\n devRandom.close();\n keyFile.close();\n keyListFile.close();\n\n cerr << \"Successfuly created new key file\" << endl;\n \n return 0;\n}\nModified the keygen file to produce a more informative usage message.#include \n#include \n#include \n#include \n#include \n\n\/\/Boost includes\n#include \"constants.hpp\"\n#include \n\nusing namespace std;\nusing namespace boost::filesystem;\n\n\/\/Key len in bytes (Will be encoded in hex)s\nstatic const path DIR_PATH{KEY_NAME_PATH};\n\nstatic const char hexValues[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};\n\nvoid usage()\n{\n cout << \"usage: agfs-keygen {host dns name\/ip addr} {port} {user} {local mount point} {key file name}\" << endl;\n cout << \" {host dns name\/ip addr}\" << endl;\n cout << \" Your dns name or ip address.\" << endl << endl;\n cout << \" {port}\" << endl;\n cout << \" The end port clients should use to communicate with you.\" << endl << endl;\n cout << \" {user}\" << endl;\n cout << \" The user account on your system clients with this key will be able to use.\" << endl << endl;\n cout << \" {local mount point}\" << endl;\n cout << \" Where clients will mount your local file system.\" << endl << endl;\n cout << \" {key file name}\" << endl;\n cout << \" The name of the key file on the local machine.\" << endl << endl << endl;\n cout << \" This program is meant to be run on an AgFS server to generate keys for other users to copy to their machines.\" << endl;\n}\n\nint main(int argc, char** argv)\n{\n if(argc != 6) {\n usage();\n return 0;\n }\n \n if(!exists(DIR_PATH)) {\n if(!create_directory(DIR_PATH)) {\n cerr << \"Could not create key directory\" << endl;\n return -ENOENT;\n }\n }\n\n fstream devRandom;\n devRandom.open(\"\/dev\/urandom\", fstream::in);\n\n fstream keyListFile;\n keyListFile.open(KEY_LIST_PATH, fstream::out | fstream::app);\n\n if(!keyListFile.is_open()){\n cerr << \"Could not open keyListFile\" <> 4];\n keyStr += upperByte;\n keyStr += lowerByte;\n ++count;\n }\n\n \/\/print the key to the keyfile\n keyFile << keyStr << endl;\n\n \/\/print mount point, uname, key to the key list file\n keyListFile << argv[4] << \" \" << argv[3] << \" \" << keyStr << endl;\n\n \/\/Close files\n devRandom.close();\n keyFile.close();\n keyListFile.close();\n\n cerr << \"Successfuly created new key file\" << endl;\n \n return 0;\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2015 Far Group\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n3. The name of the authors may not be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\nOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\nIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\nTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\nsuppress C5031 in VS2015 Update 1\/*\nCopyright 2015 Far Group\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n3. The name of the authors may not be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\nOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\nIN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\nTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#ifdef _MSC_VER\n#pragma warning(suppress: 5031) \/\/ no page #pragma warning(pop): likely mismatch, popping warning state pushed in different file\n#pragma warning(pop)\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: octree.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 19:27:16 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include \n#ifndef _SV_BMPACC_HXX\n#include \n#endif\n#ifndef _SV_IMPOCT_HXX\n#include \n#endif\n#include \n\n\/\/ ---------\n\/\/ - pMask -\n\/\/ ---------\n\nstatic BYTE pImplMask[8] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };\n\n\/\/ -------------\n\/\/ - NodeCache -\n\/\/ -------------\n\nImpNodeCache::ImpNodeCache( const ULONG nInitSize ) :\n pActNode( NULL )\n{\n const ULONG nSize = nInitSize + 4;\n\n for( ULONG i = 0; i < nSize; i++ )\n {\n OctreeNode* pNewNode = new NODE;\n\n pNewNode->pNextInCache = pActNode;\n pActNode = pNewNode;\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nImpNodeCache::~ImpNodeCache()\n{\n while( pActNode )\n {\n OctreeNode* pNode = pActNode;\n\n pActNode = pNode->pNextInCache;\n delete pNode;\n }\n}\n\n\/\/ ----------\n\/\/ - Octree -\n\/\/ ----------\n\nOctree::Octree( ULONG nColors ) :\n nMax ( nColors ),\n nLeafCount ( 0L ),\n pTree ( NULL ),\n pAcc ( NULL )\n{\n pNodeCache = new ImpNodeCache( nColors );\n memset( pReduce, 0, ( OCTREE_BITS + 1 ) * sizeof( PNODE ) );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nOctree::Octree( const BitmapReadAccess& rReadAcc, ULONG nColors ) :\n nMax ( nColors ),\n nLeafCount ( 0L ),\n pTree ( NULL ),\n pAcc ( &rReadAcc )\n{\n pNodeCache = new ImpNodeCache( nColors );\n memset( pReduce, 0, ( OCTREE_BITS + 1 ) * sizeof( PNODE ) );\n ImplCreateOctree();\n}\n\n\/\/ ------------------------------------------------------------------------\n\nOctree::~Octree()\n{\n ImplDeleteOctree( &pTree );\n delete pNodeCache;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::AddColor( const BitmapColor& rColor )\n{\n pColor = &(BitmapColor&) rColor;\n nLevel = 0L;\n ImplAdd( &pTree );\n\n while( nLeafCount > nMax )\n ImplReduce();\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::ImplCreateOctree()\n{\n if( !!*pAcc )\n {\n const long nWidth = pAcc->Width();\n const long nHeight = pAcc->Height();\n\n if( pAcc->HasPalette() )\n {\n for( long nY = 0; nY < nHeight; nY++ )\n {\n for( long nX = 0; nX < nWidth; nX++ )\n {\n pColor = &(BitmapColor&) pAcc->GetPaletteColor( pAcc->GetPixel( nY, nX ) );\n nLevel = 0L;\n ImplAdd( &pTree );\n\n while( nLeafCount > nMax )\n ImplReduce();\n }\n }\n }\n else\n {\n BitmapColor aColor;\n\n pColor = &aColor;\n\n for( long nY = 0; nY < nHeight; nY++ )\n {\n for( long nX = 0; nX < nWidth; nX++ )\n {\n aColor = pAcc->GetPixel( nY, nX );\n nLevel = 0L;\n ImplAdd( &pTree );\n\n while( nLeafCount > nMax )\n ImplReduce();\n }\n }\n }\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::ImplDeleteOctree( PPNODE ppNode )\n{\n for ( ULONG i = 0UL; i < 8UL; i++ )\n {\n if ( (*ppNode)->pChild[ i ] )\n ImplDeleteOctree( &(*ppNode)->pChild[ i ] );\n }\n\n pNodeCache->ImplReleaseNode( *ppNode );\n *ppNode = NULL;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::ImplAdd( PPNODE ppNode )\n{\n \/\/ ggf. neuen Knoten erzeugen\n if( !*ppNode )\n {\n *ppNode = pNodeCache->ImplGetFreeNode();\n (*ppNode)->bLeaf = ( OCTREE_BITS == nLevel );\n\n if( (*ppNode)->bLeaf )\n nLeafCount++;\n else\n {\n (*ppNode)->pNext = pReduce[ nLevel ];\n pReduce[ nLevel ] = *ppNode;\n }\n }\n\n if( (*ppNode)->bLeaf )\n {\n (*ppNode)->nCount++;\n (*ppNode)->nRed += pColor->GetRed();\n (*ppNode)->nGreen += pColor->GetGreen();\n (*ppNode)->nBlue += pColor->GetBlue();\n }\n else\n {\n const ULONG nShift = 7 - nLevel;\n const BYTE cMask = pImplMask[ nLevel ];\n const ULONG nIndex = ( ( ( pColor->GetRed() & cMask ) >> nShift ) << 2 ) |\n ( ( ( pColor->GetGreen() & cMask ) >> nShift ) << 1 ) |\n ( ( pColor->GetBlue() & cMask ) >> nShift );\n\n nLevel++;\n ImplAdd( &(*ppNode)->pChild[ nIndex ] );\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::ImplReduce()\n{\n ULONG i;\n PNODE pNode;\n ULONG nRedSum = 0L;\n ULONG nGreenSum = 0L;\n ULONG nBlueSum = 0L;\n ULONG nChilds = 0L;\n\n for ( i = OCTREE_BITS - 1; i && !pReduce[i]; i-- ) {}\n\n pNode = pReduce[ i ];\n pReduce[ i ] = pNode->pNext;\n\n for ( i = 0; i < 8; i++ )\n {\n if ( pNode->pChild[ i ] )\n {\n PNODE pChild = pNode->pChild[ i ];\n\n nRedSum += pChild->nRed;\n nGreenSum += pChild->nGreen;\n nBlueSum += pChild->nBlue;\n pNode->nCount += pChild->nCount;\n\n pNodeCache->ImplReleaseNode( pNode->pChild[ i ] );\n pNode->pChild[ i ] = NULL;\n nChilds++;\n }\n }\n\n pNode->bLeaf = TRUE;\n pNode->nRed = nRedSum;\n pNode->nGreen = nGreenSum;\n pNode->nBlue = nBlueSum;\n nLeafCount -= --nChilds;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::CreatePalette( PNODE pNode )\n{\n if( pNode->bLeaf )\n {\n pNode->nPalIndex = nPalIndex;\n aPal[ nPalIndex++ ] = BitmapColor( (BYTE) ( (double) pNode->nRed \/ pNode->nCount ),\n (BYTE) ( (double) pNode->nGreen \/ pNode->nCount ),\n (BYTE) ( (double) pNode->nBlue \/ pNode->nCount ) );\n }\n else for( ULONG i = 0UL; i < 8UL; i++ )\n if( pNode->pChild[ i ] )\n CreatePalette( pNode->pChild[ i ] );\n\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::GetPalIndex( PNODE pNode )\n{\n if ( pNode->bLeaf )\n nPalIndex = pNode->nPalIndex;\n else\n {\n const ULONG nShift = 7 - nLevel;\n const BYTE cMask = pImplMask[ nLevel++ ];\n const ULONG nIndex = ( ( ( pColor->GetRed() & cMask ) >> nShift ) << 2 ) |\n ( ( ( pColor->GetGreen() & cMask ) >> nShift ) << 1 ) |\n ( ( pColor->GetBlue() & cMask ) >> nShift );\n\n GetPalIndex( pNode->pChild[ nIndex ] );\n }\n}\n\n\/\/ -------------------\n\/\/ - InverseColorMap -\n\/\/ -------------------\n\nInverseColorMap::InverseColorMap( const BitmapPalette& rPal ) :\n nBits( 8 - OCTREE_BITS )\n{\n ULONG* cdp;\n BYTE* crgbp;\n const ULONG nColorMax = 1 << OCTREE_BITS;\n const ULONG xsqr = 1 << ( nBits << 1 );\n const ULONG xsqr2 = xsqr << 1;\n const ULONG nColors = rPal.GetEntryCount();\n const long x = 1L << nBits;\n const long x2 = x >> 1L;\n ULONG r, g, b;\n long rxx, gxx, bxx;\n long rdist, gdist, bdist;\n long crinc, cginc, cbinc;\n\n ImplCreateBuffers( nColorMax );\n\n for( ULONG nIndex = 0; nIndex < nColors; nIndex++ )\n {\n const BitmapColor& rColor = rPal[ (USHORT) nIndex ];\n const BYTE cRed = rColor.GetRed();\n const BYTE cGreen = rColor.GetGreen();\n const BYTE cBlue = rColor.GetBlue();\n\n rdist = cRed - x2;\n gdist = cGreen - x2;\n bdist = cBlue - x2;\n rdist = rdist*rdist + gdist*gdist + bdist*bdist;\n\n crinc = ( xsqr - ( cRed << nBits ) ) << 1L;\n cginc = ( xsqr - ( cGreen << nBits ) ) << 1L;\n cbinc = ( xsqr - ( cBlue << nBits ) ) << 1L;\n\n cdp = (ULONG*) pBuffer;\n crgbp = pMap;\n\n for( r = 0, rxx = crinc; r < nColorMax; rdist += rxx, r++, rxx += xsqr2 )\n {\n for( g = 0, gdist = rdist, gxx = cginc; g < nColorMax; gdist += gxx, g++, gxx += xsqr2 )\n {\n for( b = 0, bdist = gdist, bxx = cbinc; b < nColorMax; bdist += bxx, b++, cdp++, crgbp++, bxx += xsqr2 )\n if ( !nIndex || ( (long) *cdp ) > bdist )\n {\n *cdp = bdist;\n *crgbp = (BYTE) nIndex;\n }\n }\n }\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nInverseColorMap::~InverseColorMap()\n{\n rtl_freeMemory( pBuffer );\n rtl_freeMemory( pMap );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid InverseColorMap::ImplCreateBuffers( const ULONG nMax )\n{\n const ULONG nCount = nMax * nMax * nMax;\n const ULONG nSize = nCount * sizeof( ULONG );\n\n pMap = (BYTE*) rtl_allocateMemory( nCount );\n memset( pMap, 0x00, nCount );\n\n pBuffer = (BYTE*) rtl_allocateMemory( nSize );\n memset( pBuffer, 0xff, nSize );\n}\nINTEGRATION: CWS pchfix02 (1.4.110); FILE MERGED 2006\/09\/01 17:57:45 kaib 1.4.110.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: octree.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 12:05:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_vcl.hxx\"\n#include \n#ifndef _SV_BMPACC_HXX\n#include \n#endif\n#ifndef _SV_IMPOCT_HXX\n#include \n#endif\n#include \n\n\/\/ ---------\n\/\/ - pMask -\n\/\/ ---------\n\nstatic BYTE pImplMask[8] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };\n\n\/\/ -------------\n\/\/ - NodeCache -\n\/\/ -------------\n\nImpNodeCache::ImpNodeCache( const ULONG nInitSize ) :\n pActNode( NULL )\n{\n const ULONG nSize = nInitSize + 4;\n\n for( ULONG i = 0; i < nSize; i++ )\n {\n OctreeNode* pNewNode = new NODE;\n\n pNewNode->pNextInCache = pActNode;\n pActNode = pNewNode;\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nImpNodeCache::~ImpNodeCache()\n{\n while( pActNode )\n {\n OctreeNode* pNode = pActNode;\n\n pActNode = pNode->pNextInCache;\n delete pNode;\n }\n}\n\n\/\/ ----------\n\/\/ - Octree -\n\/\/ ----------\n\nOctree::Octree( ULONG nColors ) :\n nMax ( nColors ),\n nLeafCount ( 0L ),\n pTree ( NULL ),\n pAcc ( NULL )\n{\n pNodeCache = new ImpNodeCache( nColors );\n memset( pReduce, 0, ( OCTREE_BITS + 1 ) * sizeof( PNODE ) );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nOctree::Octree( const BitmapReadAccess& rReadAcc, ULONG nColors ) :\n nMax ( nColors ),\n nLeafCount ( 0L ),\n pTree ( NULL ),\n pAcc ( &rReadAcc )\n{\n pNodeCache = new ImpNodeCache( nColors );\n memset( pReduce, 0, ( OCTREE_BITS + 1 ) * sizeof( PNODE ) );\n ImplCreateOctree();\n}\n\n\/\/ ------------------------------------------------------------------------\n\nOctree::~Octree()\n{\n ImplDeleteOctree( &pTree );\n delete pNodeCache;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::AddColor( const BitmapColor& rColor )\n{\n pColor = &(BitmapColor&) rColor;\n nLevel = 0L;\n ImplAdd( &pTree );\n\n while( nLeafCount > nMax )\n ImplReduce();\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::ImplCreateOctree()\n{\n if( !!*pAcc )\n {\n const long nWidth = pAcc->Width();\n const long nHeight = pAcc->Height();\n\n if( pAcc->HasPalette() )\n {\n for( long nY = 0; nY < nHeight; nY++ )\n {\n for( long nX = 0; nX < nWidth; nX++ )\n {\n pColor = &(BitmapColor&) pAcc->GetPaletteColor( pAcc->GetPixel( nY, nX ) );\n nLevel = 0L;\n ImplAdd( &pTree );\n\n while( nLeafCount > nMax )\n ImplReduce();\n }\n }\n }\n else\n {\n BitmapColor aColor;\n\n pColor = &aColor;\n\n for( long nY = 0; nY < nHeight; nY++ )\n {\n for( long nX = 0; nX < nWidth; nX++ )\n {\n aColor = pAcc->GetPixel( nY, nX );\n nLevel = 0L;\n ImplAdd( &pTree );\n\n while( nLeafCount > nMax )\n ImplReduce();\n }\n }\n }\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::ImplDeleteOctree( PPNODE ppNode )\n{\n for ( ULONG i = 0UL; i < 8UL; i++ )\n {\n if ( (*ppNode)->pChild[ i ] )\n ImplDeleteOctree( &(*ppNode)->pChild[ i ] );\n }\n\n pNodeCache->ImplReleaseNode( *ppNode );\n *ppNode = NULL;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::ImplAdd( PPNODE ppNode )\n{\n \/\/ ggf. neuen Knoten erzeugen\n if( !*ppNode )\n {\n *ppNode = pNodeCache->ImplGetFreeNode();\n (*ppNode)->bLeaf = ( OCTREE_BITS == nLevel );\n\n if( (*ppNode)->bLeaf )\n nLeafCount++;\n else\n {\n (*ppNode)->pNext = pReduce[ nLevel ];\n pReduce[ nLevel ] = *ppNode;\n }\n }\n\n if( (*ppNode)->bLeaf )\n {\n (*ppNode)->nCount++;\n (*ppNode)->nRed += pColor->GetRed();\n (*ppNode)->nGreen += pColor->GetGreen();\n (*ppNode)->nBlue += pColor->GetBlue();\n }\n else\n {\n const ULONG nShift = 7 - nLevel;\n const BYTE cMask = pImplMask[ nLevel ];\n const ULONG nIndex = ( ( ( pColor->GetRed() & cMask ) >> nShift ) << 2 ) |\n ( ( ( pColor->GetGreen() & cMask ) >> nShift ) << 1 ) |\n ( ( pColor->GetBlue() & cMask ) >> nShift );\n\n nLevel++;\n ImplAdd( &(*ppNode)->pChild[ nIndex ] );\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::ImplReduce()\n{\n ULONG i;\n PNODE pNode;\n ULONG nRedSum = 0L;\n ULONG nGreenSum = 0L;\n ULONG nBlueSum = 0L;\n ULONG nChilds = 0L;\n\n for ( i = OCTREE_BITS - 1; i && !pReduce[i]; i-- ) {}\n\n pNode = pReduce[ i ];\n pReduce[ i ] = pNode->pNext;\n\n for ( i = 0; i < 8; i++ )\n {\n if ( pNode->pChild[ i ] )\n {\n PNODE pChild = pNode->pChild[ i ];\n\n nRedSum += pChild->nRed;\n nGreenSum += pChild->nGreen;\n nBlueSum += pChild->nBlue;\n pNode->nCount += pChild->nCount;\n\n pNodeCache->ImplReleaseNode( pNode->pChild[ i ] );\n pNode->pChild[ i ] = NULL;\n nChilds++;\n }\n }\n\n pNode->bLeaf = TRUE;\n pNode->nRed = nRedSum;\n pNode->nGreen = nGreenSum;\n pNode->nBlue = nBlueSum;\n nLeafCount -= --nChilds;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::CreatePalette( PNODE pNode )\n{\n if( pNode->bLeaf )\n {\n pNode->nPalIndex = nPalIndex;\n aPal[ nPalIndex++ ] = BitmapColor( (BYTE) ( (double) pNode->nRed \/ pNode->nCount ),\n (BYTE) ( (double) pNode->nGreen \/ pNode->nCount ),\n (BYTE) ( (double) pNode->nBlue \/ pNode->nCount ) );\n }\n else for( ULONG i = 0UL; i < 8UL; i++ )\n if( pNode->pChild[ i ] )\n CreatePalette( pNode->pChild[ i ] );\n\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid Octree::GetPalIndex( PNODE pNode )\n{\n if ( pNode->bLeaf )\n nPalIndex = pNode->nPalIndex;\n else\n {\n const ULONG nShift = 7 - nLevel;\n const BYTE cMask = pImplMask[ nLevel++ ];\n const ULONG nIndex = ( ( ( pColor->GetRed() & cMask ) >> nShift ) << 2 ) |\n ( ( ( pColor->GetGreen() & cMask ) >> nShift ) << 1 ) |\n ( ( pColor->GetBlue() & cMask ) >> nShift );\n\n GetPalIndex( pNode->pChild[ nIndex ] );\n }\n}\n\n\/\/ -------------------\n\/\/ - InverseColorMap -\n\/\/ -------------------\n\nInverseColorMap::InverseColorMap( const BitmapPalette& rPal ) :\n nBits( 8 - OCTREE_BITS )\n{\n ULONG* cdp;\n BYTE* crgbp;\n const ULONG nColorMax = 1 << OCTREE_BITS;\n const ULONG xsqr = 1 << ( nBits << 1 );\n const ULONG xsqr2 = xsqr << 1;\n const ULONG nColors = rPal.GetEntryCount();\n const long x = 1L << nBits;\n const long x2 = x >> 1L;\n ULONG r, g, b;\n long rxx, gxx, bxx;\n long rdist, gdist, bdist;\n long crinc, cginc, cbinc;\n\n ImplCreateBuffers( nColorMax );\n\n for( ULONG nIndex = 0; nIndex < nColors; nIndex++ )\n {\n const BitmapColor& rColor = rPal[ (USHORT) nIndex ];\n const BYTE cRed = rColor.GetRed();\n const BYTE cGreen = rColor.GetGreen();\n const BYTE cBlue = rColor.GetBlue();\n\n rdist = cRed - x2;\n gdist = cGreen - x2;\n bdist = cBlue - x2;\n rdist = rdist*rdist + gdist*gdist + bdist*bdist;\n\n crinc = ( xsqr - ( cRed << nBits ) ) << 1L;\n cginc = ( xsqr - ( cGreen << nBits ) ) << 1L;\n cbinc = ( xsqr - ( cBlue << nBits ) ) << 1L;\n\n cdp = (ULONG*) pBuffer;\n crgbp = pMap;\n\n for( r = 0, rxx = crinc; r < nColorMax; rdist += rxx, r++, rxx += xsqr2 )\n {\n for( g = 0, gdist = rdist, gxx = cginc; g < nColorMax; gdist += gxx, g++, gxx += xsqr2 )\n {\n for( b = 0, bdist = gdist, bxx = cbinc; b < nColorMax; bdist += bxx, b++, cdp++, crgbp++, bxx += xsqr2 )\n if ( !nIndex || ( (long) *cdp ) > bdist )\n {\n *cdp = bdist;\n *crgbp = (BYTE) nIndex;\n }\n }\n }\n }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nInverseColorMap::~InverseColorMap()\n{\n rtl_freeMemory( pBuffer );\n rtl_freeMemory( pMap );\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid InverseColorMap::ImplCreateBuffers( const ULONG nMax )\n{\n const ULONG nCount = nMax * nMax * nMax;\n const ULONG nSize = nCount * sizeof( ULONG );\n\n pMap = (BYTE*) rtl_allocateMemory( nCount );\n memset( pMap, 0x00, nCount );\n\n pBuffer = (BYTE*) rtl_allocateMemory( nSize );\n memset( pBuffer, 0xff, nSize );\n}\n<|endoftext|>"} {"text":"\n#include \"otbWrapperInputProcessXMLParameter.h\"\n\n#include \"otbWrapperChoiceParameter.h\"\n#include \"otbWrapperListViewParameter.h\"\n#include \"otbWrapperDirectoryParameter.h\"\n#include \"otbWrapperEmptyParameter.h\"\n#include \"otbWrapperInputFilenameParameter.h\"\n#include \"otbWrapperInputFilenameListParameter.h\"\n#include \"otbWrapperOutputFilenameParameter.h\"\n#include \"otbWrapperInputVectorDataParameter.h\"\n#include \"otbWrapperInputVectorDataListParameter.h\"\n#include \"otbWrapperNumericalParameter.h\"\n#include \"otbWrapperOutputVectorDataParameter.h\"\n#include \"otbWrapperRadiusParameter.h\"\n#include \"otbWrapperStringParameter.h\"\n#include \"otbWrapperStringListParameter.h\"\n#include \"otbWrapperInputImageParameter.h\"\n#include \"otbWrapperInputImageListParameter.h\"\n#include \"otbWrapperComplexInputImageParameter.h\"\n#include \"otbWrapperOutputImageParameter.h\"\n#include \"otbWrapperComplexOutputImageParameter.h\"\n#include \"otbWrapperRAMParameter.h\"\n#include \"itksys\/SystemTools.hxx\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\nInputProcessXMLParameter::InputProcessXMLParameter()\n{\n this->SetKey(\"inxml\");\n this->SetName(\"Load otb application from xml file\");\n this->SetDescription(\"Load otb application from xml file\");\n this->SetMandatory(false);\n this->SetActive(false);\n this->SetRole(Role_Input);\n}\n\nInputProcessXMLParameter::~InputProcessXMLParameter()\n{\n\n}\n\nImagePixelType\nInputProcessXMLParameter::GetPixelTypeFromString(std::string strType)\n{\n if(strType == \"uint8\")\n {\n return ImagePixelType_uint8;\n }\n else if (strType == \"uint16\")\n {\n return ImagePixelType_uint16;\n }\n else if(strType == \"uint32\")\n {\n return ImagePixelType_int32;\n }\n else if(strType == \"float\")\n {\n return ImagePixelType_float;\n }\n else if(strType == \"double\")\n {\n return ImagePixelType_double;\n }\n else\n {\n \/*by default return float. Eg: if strType is emtpy because of no pixtype\n node in xml which was the case earlier\n *\/\n return ImagePixelType_float;\n }\n}\n\nvoid\nInputProcessXMLParameter::otbAppLogInfo(Application::Pointer app, std::string info)\n{\n app->GetLogger()->Write(itk::LoggerBase::INFO, info );\n}\n\n\/* copied from Utilities\/tinyXMLlib\/tinyxml.cpp. Must have a FIX inside tinyxml.cpp *\/\nFILE*\nInputProcessXMLParameter::TiXmlFOpen( const char* filename, const char* mode )\n{\n#if defined(_MSC_VER) && (_MSC_VER >= 1400 )\n FILE* fp = 0;\n errno_t err = fopen_s( &fp, filename, mode );\n if ( !err && fp )\n return fp;\n return 0;\n #else\n return fopen( filename, mode );\n #endif\n}\n\nconst std::string\nInputProcessXMLParameter::GetChildNodeTextOf(TiXmlElement *parentElement, std::string key)\n{\n std::string value=\"\";\n\n if(parentElement)\n {\n TiXmlElement* childElement = 0;\n childElement = parentElement->FirstChildElement(key.c_str());\n\n \/\/same as childElement->GetText() does but that call is failing if there is\n \/\/no such node.\n \/\/but the below code works and is a replacement for GetText()\n if(childElement)\n {\n const TiXmlNode* child = childElement->FirstChild();\n if ( child )\n {\n const TiXmlText* childText = child->ToText();\n if ( childText )\n {\n value = childText->Value();\n }\n }\n }\n }\n return value;\n}\n\nint\nInputProcessXMLParameter::Read(Application::Pointer this_)\n{\n\n \/\/ Check if the filename is not empty\n if(m_FileName.empty())\n itkExceptionMacro(<<\"The XML input FileName is empty, please set the filename via the method SetFileName\");\n\n \/\/ Check that the right extension is given : expected .xml\n if (itksys::SystemTools::GetFilenameLastExtension(m_FileName) != \".xml\")\n {\n itkExceptionMacro(<GetFileName()) + \" is invalid.\";\n \/\/this->otbAppLogInfo(app,info);\n }\n\n \/*\n std::string otb_Version, otb_Build, otb_Platform;\n otb_Version = this_->GetChildNodeTextOf(n_OTB,\"version\");\n otb_Build = GetChildNodeTextOf(n_OTB, \"build\");\n otb_Platform = this_->GetChildNodeTextOf(n_OTB, \"platform\");\n *\/\n\n int ret = 0;\n\n TiXmlElement *n_AppNode = n_OTB->FirstChildElement(\"application\");\n\n std::string app_Name;\n app_Name = GetChildNodeTextOf(n_AppNode, \"name\");\n \/*\n AddMetaData(\"appname\", app_Name);\n\n app_Descr = this_->GetChildNodeTextOf(n_AppNode, \"descr\");\n AddMetaData(\"appdescr\", app_Descr);\n\n TiXmlElement* n_Doc = n_AppNode->FirstChildElement(\"doc\");\n\n std::string doc_Name, doc_Descr, doc_Author, doc_Limitation, doc_SeeAlso;\n\n doc_Name = this_->GetChildNodeTextOf(n_Doc, \"name\");\n AddMetaData(\"docname\", doc_Name);\n\n doc_Descr = this_->GetChildNodeTextOf(n_Doc, \"longdescr\");\n AddMetaData(\"doclongdescr\", doc_Descr);\n\n doc_Author = this_->GetChildNodeTextOf(n_Doc, \"authors\");\n AddMetaData(\"docauthors\", doc_Author);\n\n doc_Limitation = this_->GetChildNodeTextOf(n_Doc, \"limitations\");\n AddMetaData(\"doclimitations\", doc_Limitation);\n\n doc_SeeAlso = this_->GetChildNodeTextOf(n_Doc, \"seealso\");\n AddMetaData(\"docseealso\", doc_SeeAlso);\n *\/\n\n\n if(this_->GetName() != app_Name)\n {\n \/\/hopefully shouldn't reach here ...\n \/*\n std::string message = \"Input XML was generated for a different application( \"\n + app_Name + \") while application loaded is:\" + this_->GetName();\n\n std::cerr << message << \"\\n\\n\";\n *\/\n itkWarningMacro( << \"Input XML was generated for a different application( \" <<\n app_Name << \") while application loaded is:\" <GetName());\n\n return -1;\n }\n\n ParameterGroup::Pointer paramGroup = this_->GetParameterList();\n\n \/\/ Iterate through the parameter list\n for( TiXmlElement* n_Parameter = n_AppNode->FirstChildElement(\"parameter\"); n_Parameter != NULL;\n n_Parameter = n_Parameter->NextSiblingElement() )\n {\n std::string key,typeAsString, value, paramName;\n std::vector values;\n key = GetChildNodeTextOf(n_Parameter, \"key\");\n typeAsString = GetChildNodeTextOf(n_Parameter, \"type\");\n value = GetChildNodeTextOf(n_Parameter, \"value\");\n paramName = GetChildNodeTextOf(n_Parameter, \"name\");\n ParameterType type = paramGroup->GetParameterTypeFromString(typeAsString);\n\n Parameter* param = this_->GetParameterByKey(key);\n param->SetUserValue(true);\n TiXmlElement* n_Values = NULL;\n n_Values = n_Parameter->FirstChildElement(\"values\");\n if(n_Values)\n {\n for(TiXmlElement* n_Value = n_Values->FirstChildElement(\"value\"); n_Value != NULL;\n n_Value = n_Value->NextSiblingElement())\n {\n values.push_back(n_Value->GetText());\n }\n }\n\n if ( type == ParameterType_OutputFilename || type == ParameterType_OutputVectorData ||\n type == ParameterType_String || type == ParameterType_Choice)\n {\n this_->SetParameterString(key, value);\n }\n else if (type == ParameterType_OutputImage)\n {\n OutputImageParameter *paramDown = dynamic_cast(param);\n paramDown->SetFileName(value);\n std::string pixTypeAsString = GetChildNodeTextOf(n_Parameter, \"pixtype\");\n ImagePixelType outPixType = GetPixelTypeFromString(pixTypeAsString);\n paramDown->SetPixelType(outPixType);\n }\n else if (dynamic_cast(param))\n {\n ComplexOutputImageParameter* paramDown = dynamic_cast(param);\n paramDown->SetFileName(value);\n }\n else if (dynamic_cast(param))\n {\n DirectoryParameter* paramDown = dynamic_cast(param);\n paramDown->SetValue(value);\n }\n else if (dynamic_cast(param))\n {\n InputFilenameParameter* paramDown = dynamic_cast(param);\n paramDown->SetValue(value);\n }\n else if (dynamic_cast(param))\n {\n if(itksys::SystemTools::FileExists(value.c_str()))\n {\n InputImageParameter* paramDown = dynamic_cast(param);\n paramDown->SetFromFileName(value);\n if (!paramDown->SetFromFileName(value))\n {\n ret= -1;\n }\n }\n }\n else if (dynamic_cast(param))\n {\n if(itksys::SystemTools::FileExists(value.c_str()))\n {\n ComplexInputImageParameter* paramDown = dynamic_cast(param);\n paramDown->SetFromFileName(value);\n }\n }\n else if (dynamic_cast(param))\n {\n if(itksys::SystemTools::FileExists(value.c_str()))\n {\n InputVectorDataParameter* paramDown = dynamic_cast(param);\n paramDown->SetFromFileName(value);\n if ( !paramDown->SetFromFileName(value) )\n {\n ret = -1;\n }\n }\n }\n else if (dynamic_cast(param))\n {\n InputImageListParameter* paramDown = dynamic_cast(param);\n paramDown->SetListFromFileName(values);\n\n if ( !paramDown->SetListFromFileName(values) )\n {\n ret = -1;\n }\n\n }\n else if (dynamic_cast(param))\n {\n InputVectorDataListParameter* paramDown = dynamic_cast(param);\n paramDown->SetListFromFileName(values);\n if ( !paramDown->SetListFromFileName(values) )\n {\n ret = -1;\n }\n }\n else if (dynamic_cast(param))\n {\n InputFilenameListParameter* paramDown = dynamic_cast(param);\n paramDown->SetListFromFileName(values);\n if ( !paramDown->SetListFromFileName(values) )\n {\n ret= -1;\n }\n }\n else if (type == ParameterType_Radius || type == ParameterType_Int ||\n type == ParameterType_RAM || typeAsString == \"rand\" )\n {\n int intValue;\n std::stringstream(value) >> intValue;\n this_->SetParameterInt(key, intValue);\n }\n else if (type == ParameterType_Float)\n {\n float floatValue;\n std::stringstream(value) >> floatValue;\n this_->SetParameterFloat(key, floatValue);\n }\n else if (type == ParameterType_Empty)\n {\n bool emptyValue = false;\n if( value == \"true\")\n {\n emptyValue = true;\n }\n this_->SetParameterEmpty(key, emptyValue);\n }\n else if (type == ParameterType_StringList || type == ParameterType_ListView)\n {\n if(values.empty())\n itkWarningMacro(<< key << \" has null values\");\n\n this_->SetParameterStringList(key, values);\n }\n\n \/\/choice also comes as setint and setstring why??\n }\n ret = 0; \/\/resetting return to zero, we dont use it anyway for now.\n return ret;\n}\n\n\n} \/\/end namespace wrapper\n\n} \/\/end namespace otb\nENH: Issue a warning if image file in xml does not exist\n#include \"otbWrapperInputProcessXMLParameter.h\"\n\n#include \"otbWrapperChoiceParameter.h\"\n#include \"otbWrapperListViewParameter.h\"\n#include \"otbWrapperDirectoryParameter.h\"\n#include \"otbWrapperEmptyParameter.h\"\n#include \"otbWrapperInputFilenameParameter.h\"\n#include \"otbWrapperInputFilenameListParameter.h\"\n#include \"otbWrapperOutputFilenameParameter.h\"\n#include \"otbWrapperInputVectorDataParameter.h\"\n#include \"otbWrapperInputVectorDataListParameter.h\"\n#include \"otbWrapperNumericalParameter.h\"\n#include \"otbWrapperOutputVectorDataParameter.h\"\n#include \"otbWrapperRadiusParameter.h\"\n#include \"otbWrapperStringParameter.h\"\n#include \"otbWrapperStringListParameter.h\"\n#include \"otbWrapperInputImageParameter.h\"\n#include \"otbWrapperInputImageListParameter.h\"\n#include \"otbWrapperComplexInputImageParameter.h\"\n#include \"otbWrapperOutputImageParameter.h\"\n#include \"otbWrapperComplexOutputImageParameter.h\"\n#include \"otbWrapperRAMParameter.h\"\n#include \"itksys\/SystemTools.hxx\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\nInputProcessXMLParameter::InputProcessXMLParameter()\n{\n this->SetKey(\"inxml\");\n this->SetName(\"Load otb application from xml file\");\n this->SetDescription(\"Load otb application from xml file\");\n this->SetMandatory(false);\n this->SetActive(false);\n this->SetRole(Role_Input);\n}\n\nInputProcessXMLParameter::~InputProcessXMLParameter()\n{\n\n}\n\nImagePixelType\nInputProcessXMLParameter::GetPixelTypeFromString(std::string strType)\n{\n if(strType == \"uint8\")\n {\n return ImagePixelType_uint8;\n }\n else if (strType == \"uint16\")\n {\n return ImagePixelType_uint16;\n }\n else if(strType == \"uint32\")\n {\n return ImagePixelType_int32;\n }\n else if(strType == \"float\")\n {\n return ImagePixelType_float;\n }\n else if(strType == \"double\")\n {\n return ImagePixelType_double;\n }\n else\n {\n \/*by default return float. Eg: if strType is emtpy because of no pixtype\n node in xml which was the case earlier\n *\/\n return ImagePixelType_float;\n }\n}\n\nvoid\nInputProcessXMLParameter::otbAppLogInfo(Application::Pointer app, std::string info)\n{\n app->GetLogger()->Write(itk::LoggerBase::INFO, info );\n}\n\n\/* copied from Utilities\/tinyXMLlib\/tinyxml.cpp. Must have a FIX inside tinyxml.cpp *\/\nFILE*\nInputProcessXMLParameter::TiXmlFOpen( const char* filename, const char* mode )\n{\n#if defined(_MSC_VER) && (_MSC_VER >= 1400 )\n FILE* fp = 0;\n errno_t err = fopen_s( &fp, filename, mode );\n if ( !err && fp )\n return fp;\n return 0;\n #else\n return fopen( filename, mode );\n #endif\n}\n\nconst std::string\nInputProcessXMLParameter::GetChildNodeTextOf(TiXmlElement *parentElement, std::string key)\n{\n std::string value=\"\";\n\n if(parentElement)\n {\n TiXmlElement* childElement = 0;\n childElement = parentElement->FirstChildElement(key.c_str());\n\n \/\/same as childElement->GetText() does but that call is failing if there is\n \/\/no such node.\n \/\/but the below code works and is a replacement for GetText()\n if(childElement)\n {\n const TiXmlNode* child = childElement->FirstChild();\n if ( child )\n {\n const TiXmlText* childText = child->ToText();\n if ( childText )\n {\n value = childText->Value();\n }\n }\n }\n }\n return value;\n}\n\nint\nInputProcessXMLParameter::Read(Application::Pointer this_)\n{\n\n \/\/ Check if the filename is not empty\n if(m_FileName.empty())\n itkExceptionMacro(<<\"The XML input FileName is empty, please set the filename via the method SetFileName\");\n\n \/\/ Check that the right extension is given : expected .xml\n if (itksys::SystemTools::GetFilenameLastExtension(m_FileName) != \".xml\")\n {\n itkExceptionMacro(<GetFileName()) + \" is invalid.\";\n \/\/this->otbAppLogInfo(app,info);\n }\n\n \/*\n std::string otb_Version, otb_Build, otb_Platform;\n otb_Version = this_->GetChildNodeTextOf(n_OTB,\"version\");\n otb_Build = GetChildNodeTextOf(n_OTB, \"build\");\n otb_Platform = this_->GetChildNodeTextOf(n_OTB, \"platform\");\n *\/\n\n int ret = 0;\n\n TiXmlElement *n_AppNode = n_OTB->FirstChildElement(\"application\");\n\n std::string app_Name;\n app_Name = GetChildNodeTextOf(n_AppNode, \"name\");\n \/*\n AddMetaData(\"appname\", app_Name);\n\n app_Descr = this_->GetChildNodeTextOf(n_AppNode, \"descr\");\n AddMetaData(\"appdescr\", app_Descr);\n\n TiXmlElement* n_Doc = n_AppNode->FirstChildElement(\"doc\");\n\n std::string doc_Name, doc_Descr, doc_Author, doc_Limitation, doc_SeeAlso;\n\n doc_Name = this_->GetChildNodeTextOf(n_Doc, \"name\");\n AddMetaData(\"docname\", doc_Name);\n\n doc_Descr = this_->GetChildNodeTextOf(n_Doc, \"longdescr\");\n AddMetaData(\"doclongdescr\", doc_Descr);\n\n doc_Author = this_->GetChildNodeTextOf(n_Doc, \"authors\");\n AddMetaData(\"docauthors\", doc_Author);\n\n doc_Limitation = this_->GetChildNodeTextOf(n_Doc, \"limitations\");\n AddMetaData(\"doclimitations\", doc_Limitation);\n\n doc_SeeAlso = this_->GetChildNodeTextOf(n_Doc, \"seealso\");\n AddMetaData(\"docseealso\", doc_SeeAlso);\n *\/\n\n\n if(this_->GetName() != app_Name)\n {\n \/\/hopefully shouldn't reach here ...\n \/*\n std::string message = \"Input XML was generated for a different application( \"\n + app_Name + \") while application loaded is:\" + this_->GetName();\n\n std::cerr << message << \"\\n\\n\";\n *\/\n itkWarningMacro( << \"Input XML was generated for a different application( \" <<\n app_Name << \") while application loaded is:\" <GetName());\n\n return -1;\n }\n\n ParameterGroup::Pointer paramGroup = this_->GetParameterList();\n\n \/\/ Iterate through the parameter list\n for( TiXmlElement* n_Parameter = n_AppNode->FirstChildElement(\"parameter\"); n_Parameter != NULL;\n n_Parameter = n_Parameter->NextSiblingElement() )\n {\n std::string key,typeAsString, value, paramName;\n std::vector values;\n key = GetChildNodeTextOf(n_Parameter, \"key\");\n typeAsString = GetChildNodeTextOf(n_Parameter, \"type\");\n value = GetChildNodeTextOf(n_Parameter, \"value\");\n paramName = GetChildNodeTextOf(n_Parameter, \"name\");\n ParameterType type = paramGroup->GetParameterTypeFromString(typeAsString);\n\n Parameter* param = this_->GetParameterByKey(key);\n param->SetUserValue(true);\n TiXmlElement* n_Values = NULL;\n n_Values = n_Parameter->FirstChildElement(\"values\");\n if(n_Values)\n {\n for(TiXmlElement* n_Value = n_Values->FirstChildElement(\"value\"); n_Value != NULL;\n n_Value = n_Value->NextSiblingElement())\n {\n values.push_back(n_Value->GetText());\n }\n }\n\n if ( type == ParameterType_OutputFilename || type == ParameterType_OutputVectorData ||\n type == ParameterType_String || type == ParameterType_Choice)\n {\n this_->SetParameterString(key, value);\n }\n else if (type == ParameterType_OutputImage)\n {\n OutputImageParameter *paramDown = dynamic_cast(param);\n paramDown->SetFileName(value);\n std::string pixTypeAsString = GetChildNodeTextOf(n_Parameter, \"pixtype\");\n ImagePixelType outPixType = GetPixelTypeFromString(pixTypeAsString);\n paramDown->SetPixelType(outPixType);\n }\n else if (dynamic_cast(param))\n {\n ComplexOutputImageParameter* paramDown = dynamic_cast(param);\n paramDown->SetFileName(value);\n }\n else if (dynamic_cast(param))\n {\n DirectoryParameter* paramDown = dynamic_cast(param);\n paramDown->SetValue(value);\n }\n else if (dynamic_cast(param))\n {\n InputFilenameParameter* paramDown = dynamic_cast(param);\n paramDown->SetValue(value);\n }\n else if (dynamic_cast(param))\n {\n if(itksys::SystemTools::FileExists(value.c_str()))\n {\n InputImageParameter* paramDown = dynamic_cast(param);\n paramDown->SetFromFileName(value);\n if (!paramDown->SetFromFileName(value))\n {\n ret= -1;\n }\n }\n else\n {\n otbMsgDevMacro( << \"InputImageFile saved in InputXML does not exists\" );\n }\n }\n else if (dynamic_cast(param))\n {\n if(itksys::SystemTools::FileExists(value.c_str()))\n {\n ComplexInputImageParameter* paramDown = dynamic_cast(param);\n paramDown->SetFromFileName(value);\n }\n }\n else if (dynamic_cast(param))\n {\n if(itksys::SystemTools::FileExists(value.c_str()))\n {\n InputVectorDataParameter* paramDown = dynamic_cast(param);\n paramDown->SetFromFileName(value);\n if ( !paramDown->SetFromFileName(value) )\n {\n ret = -1;\n }\n }\n }\n else if (dynamic_cast(param))\n {\n InputImageListParameter* paramDown = dynamic_cast(param);\n paramDown->SetListFromFileName(values);\n\n if ( !paramDown->SetListFromFileName(values) )\n {\n ret = -1;\n }\n\n }\n else if (dynamic_cast(param))\n {\n InputVectorDataListParameter* paramDown = dynamic_cast(param);\n paramDown->SetListFromFileName(values);\n if ( !paramDown->SetListFromFileName(values) )\n {\n ret = -1;\n }\n }\n else if (dynamic_cast(param))\n {\n InputFilenameListParameter* paramDown = dynamic_cast(param);\n paramDown->SetListFromFileName(values);\n if ( !paramDown->SetListFromFileName(values) )\n {\n ret= -1;\n }\n }\n else if (type == ParameterType_Radius || type == ParameterType_Int ||\n type == ParameterType_RAM || typeAsString == \"rand\" )\n {\n int intValue;\n std::stringstream(value) >> intValue;\n this_->SetParameterInt(key, intValue);\n }\n else if (type == ParameterType_Float)\n {\n float floatValue;\n std::stringstream(value) >> floatValue;\n this_->SetParameterFloat(key, floatValue);\n }\n else if (type == ParameterType_Empty)\n {\n bool emptyValue = false;\n if( value == \"true\")\n {\n emptyValue = true;\n }\n this_->SetParameterEmpty(key, emptyValue);\n }\n else if (type == ParameterType_StringList || type == ParameterType_ListView)\n {\n if(values.empty())\n itkWarningMacro(<< key << \" has null values\");\n\n this_->SetParameterStringList(key, values);\n }\n\n \/\/choice also comes as setint and setstring why??\n }\n ret = 0; \/\/resetting return to zero, we dont use it anyway for now.\n return ret;\n}\n\n\n} \/\/end namespace wrapper\n\n} \/\/end namespace otb\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2013-2014 Chun-Ying Huang\n *\n * This file is part of GamingAnywhere (GA).\n *\n * GA is free software; you can redistribute it and\/or modify it\n * under the terms of the 3-clause BSD License as published by the\n * Free Software Foundation: http:\/\/directory.fsf.org\/wiki\/License:BSD_3Clause\n *\n * GA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * You should have received a copy of the 3-clause BSD License along with GA;\n * if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n#include \n\n#include \"ga-common.h\"\n#include \"vsource.h\"\n#include \"rtspclient.h\"\n#include \"qosreport.h\"\n\n#define\tQ_MAX\t\t(VIDEO_SOURCE_CHANNEL_MAX+1)\n\nstatic UsageEnvironment *env = NULL;\nstatic TaskToken qos_task = NULL;\n\/\/\nstatic int n_qrec = 0;\nstatic qos_record_t qrec[Q_MAX];\nstatic struct timeval qos_tv;\n\nstatic void qos_schedule();\n\nstatic void\nqos_report(void *clientData) {\n\tint i;\n\tstruct timeval now;\n\tlong long elapsed;\n\t\/\/\n\tgettimeofday(&now, NULL);\n\telapsed = tvdiff_us(&now, &qos_tv);\n\tfor(i = 0; i < n_qrec; i++) {\n\t\tRTPReceptionStatsDB::Iterator statsIter(qrec[i].rtpsrc->receptionStatsDB());\n\t\t\/\/ Assume that there's only one SSRC source (usually the case):\n\t\tRTPReceptionStats* stats = statsIter.next(True);\n\t\tunsigned pkts_expected, dExp;\n\t\tunsigned pkts_received, dRcvd;\n\t\tdouble KB_received, dKB;\n\t\t\/\/\n\t\tpkts_expected = stats->totNumPacketsExpected();\n\t\tpkts_received = stats->totNumPacketsReceived();\n\t\tKB_received = stats->totNumKBytesReceived();\n\t\t\/\/ delta ...\n\t\tdExp = pkts_expected - qrec[i].pkts_expected;\n\t\tdRcvd = pkts_received - qrec[i].pkts_received;\n\t\tdKB = KB_received - qrec[i].KB_received;\n\t\t\/\/ show info\n\t\trtsperror(\"# %u.%06u %s-report: %.0fKB rcvd; pkt-loss=%d\/%d,%.2f%%; bitrate=%.0fKbps; jitter=%u\\n\",\n\t\t\tnow.tv_sec, now.tv_usec,\n\t\t\tqrec[i].prefix, dKB, dExp-dRcvd, dExp, 100.0*(dExp-dRcvd)\/dExp,\n\t\t\t8000000.0*dKB\/elapsed, stats->jitter());\n\t\t\/\/\n\t\tqrec[i].pkts_expected = pkts_expected;\n\t\tqrec[i].pkts_received = pkts_received;\n\t\tqrec[i].KB_received = KB_received;\n\t}\n\t\/\/ schedule next qos\n\tqos_tv = now;\n\tqos_schedule();\n\treturn;\n}\n\nstatic void\nqos_schedule() {\n\tstruct timeval now, timeout;\n\ttimeout.tv_sec = qos_tv.tv_sec;\n\ttimeout.tv_usec = qos_tv.tv_usec + QOS_INTERVAL_MS * 1000;\n\ttimeout.tv_sec += (timeout.tv_usec \/ 1000000);\n\ttimeout.tv_usec %= 1000000;\n\tgettimeofday(&now, NULL);\n\tqos_task = env->taskScheduler().scheduleDelayedTask(\n\t\t\ttvdiff_us(&timeout, &now), (TaskFunc*) qos_report, NULL);\n\treturn;\n}\n\nint\nqos_start() {\n\tif(env == NULL)\n\t\treturn -1;\n\tif(n_qrec <= 0)\n\t\treturn 0;\n\tgettimeofday(&qos_tv, NULL);\n\tqos_schedule();\n\treturn 0;\n}\n\nint\nqos_add_source(const char *prefix, RTPSource *rtpsrc) {\n\tif(n_qrec >= Q_MAX) {\n\t\tga_error(\"qos-measurement: too many channels (limit=%d).\\n\", Q_MAX);\n\t\treturn -1;\n\t}\n\tif(rtpsrc == NULL) {\n\t\tga_error(\"qos-measurement: invalid RTPSource object.\\n\");\n\t\treturn -1;\n\t}\n\tsnprintf(qrec[n_qrec].prefix, QOS_PREFIX_LEN, \"%s\", prefix);\n\tqrec[n_qrec].rtpsrc = rtpsrc;\n\tga_error(\"qos-measurement: source #%d added, prefix=%d\\n\", n_qrec, prefix);\n\tn_qrec++;\n\treturn 0;\n}\n\nint\nqos_deinit() {\n\tif(env != NULL) {\n\t\tenv->taskScheduler().unscheduleDelayedTask(qos_task);\n\t}\n\tqos_task = NULL;\n\tenv = NULL;\n\tn_qrec = 0;\n\tbzero(qrec, sizeof(qrec));\n\tga_error(\"qos-measurement: deinitialized.\\n\");\n\treturn 0;\n}\n\nint\nqos_init(UsageEnvironment *ue) {\n\tenv = ue;\n\tn_qrec = 0;\n\tbzero(qrec, sizeof(qrec));\n\tga_error(\"qos-measurement: initialized.\\n\");\n\treturn 0;\n}\n\ndo not report qos stats when stat pointer is NULL\/*\n * Copyright (c) 2013-2014 Chun-Ying Huang\n *\n * This file is part of GamingAnywhere (GA).\n *\n * GA is free software; you can redistribute it and\/or modify it\n * under the terms of the 3-clause BSD License as published by the\n * Free Software Foundation: http:\/\/directory.fsf.org\/wiki\/License:BSD_3Clause\n *\n * GA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * You should have received a copy of the 3-clause BSD License along with GA;\n * if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n#include \n\n#include \"ga-common.h\"\n#include \"vsource.h\"\n#include \"rtspclient.h\"\n#include \"qosreport.h\"\n\n#define\tQ_MAX\t\t(VIDEO_SOURCE_CHANNEL_MAX+1)\n\nstatic UsageEnvironment *env = NULL;\nstatic TaskToken qos_task = NULL;\n\/\/\nstatic int n_qrec = 0;\nstatic qos_record_t qrec[Q_MAX];\nstatic struct timeval qos_tv;\n\nstatic void qos_schedule();\n\nstatic void\nqos_report(void *clientData) {\n\tint i;\n\tstruct timeval now;\n\tlong long elapsed;\n\t\/\/\n\tgettimeofday(&now, NULL);\n\telapsed = tvdiff_us(&now, &qos_tv);\n\tfor(i = 0; i < n_qrec; i++) {\n\t\tRTPReceptionStatsDB::Iterator statsIter(qrec[i].rtpsrc->receptionStatsDB());\n\t\t\/\/ Assume that there's only one SSRC source (usually the case):\n\t\tRTPReceptionStats* stats = statsIter.next(True);\n\t\tunsigned pkts_expected, dExp;\n\t\tunsigned pkts_received, dRcvd;\n\t\tdouble KB_received, dKB;\n\t\t\/\/\n\t\tif(stats == NULL)\n\t\t\tcontinue;\n\t\tpkts_expected = stats->totNumPacketsExpected();\n\t\tpkts_received = stats->totNumPacketsReceived();\n\t\tKB_received = stats->totNumKBytesReceived();\n\t\t\/\/ delta ...\n\t\tdExp = pkts_expected - qrec[i].pkts_expected;\n\t\tdRcvd = pkts_received - qrec[i].pkts_received;\n\t\tdKB = KB_received - qrec[i].KB_received;\n\t\t\/\/ show info\n\t\trtsperror(\"# %u.%06u %s-report: %.0fKB rcvd; pkt-loss=%d\/%d,%.2f%%; bitrate=%.0fKbps; jitter=%u\\n\",\n\t\t\tnow.tv_sec, now.tv_usec,\n\t\t\tqrec[i].prefix, dKB, dExp-dRcvd, dExp, 100.0*(dExp-dRcvd)\/dExp,\n\t\t\t8000000.0*dKB\/elapsed, stats->jitter());\n\t\t\/\/\n\t\tqrec[i].pkts_expected = pkts_expected;\n\t\tqrec[i].pkts_received = pkts_received;\n\t\tqrec[i].KB_received = KB_received;\n\t}\n\t\/\/ schedule next qos\n\tqos_tv = now;\n\tqos_schedule();\n\treturn;\n}\n\nstatic void\nqos_schedule() {\n\tstruct timeval now, timeout;\n\ttimeout.tv_sec = qos_tv.tv_sec;\n\ttimeout.tv_usec = qos_tv.tv_usec + QOS_INTERVAL_MS * 1000;\n\ttimeout.tv_sec += (timeout.tv_usec \/ 1000000);\n\ttimeout.tv_usec %= 1000000;\n\tgettimeofday(&now, NULL);\n\tqos_task = env->taskScheduler().scheduleDelayedTask(\n\t\t\ttvdiff_us(&timeout, &now), (TaskFunc*) qos_report, NULL);\n\treturn;\n}\n\nint\nqos_start() {\n\tif(env == NULL)\n\t\treturn -1;\n\tif(n_qrec <= 0)\n\t\treturn 0;\n\tgettimeofday(&qos_tv, NULL);\n\tqos_schedule();\n\treturn 0;\n}\n\nint\nqos_add_source(const char *prefix, RTPSource *rtpsrc) {\n\tif(n_qrec >= Q_MAX) {\n\t\tga_error(\"qos-measurement: too many channels (limit=%d).\\n\", Q_MAX);\n\t\treturn -1;\n\t}\n\tif(rtpsrc == NULL) {\n\t\tga_error(\"qos-measurement: invalid RTPSource object.\\n\");\n\t\treturn -1;\n\t}\n\tsnprintf(qrec[n_qrec].prefix, QOS_PREFIX_LEN, \"%s\", prefix);\n\tqrec[n_qrec].rtpsrc = rtpsrc;\n\tga_error(\"qos-measurement: source #%d added, prefix=%d\\n\", n_qrec, prefix);\n\tn_qrec++;\n\treturn 0;\n}\n\nint\nqos_deinit() {\n\tif(env != NULL) {\n\t\tenv->taskScheduler().unscheduleDelayedTask(qos_task);\n\t}\n\tqos_task = NULL;\n\tenv = NULL;\n\tn_qrec = 0;\n\tbzero(qrec, sizeof(qrec));\n\tga_error(\"qos-measurement: deinitialized.\\n\");\n\treturn 0;\n}\n\nint\nqos_init(UsageEnvironment *ue) {\n\tenv = ue;\n\tn_qrec = 0;\n\tbzero(qrec, sizeof(qrec));\n\tga_error(\"qos-measurement: initialized.\\n\");\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2014-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"osquery\/core\/conversions.h\"\n\nnamespace osquery {\nnamespace tables {\n\ninline std::string getProcAttr(const std::string& attr,\n const std::string& pid) {\n return \"\/proc\/\" + pid + \"\/\" + attr;\n}\n\ninline std::string readProcCMDLine(const std::string& pid) {\n auto attr = getProcAttr(\"cmdline\", pid);\n\n std::string content;\n readFile(attr, content);\n \/\/ Remove \\0 delimiters.\n std::replace_if(content.begin(),\n content.end(),\n [](const char& c) { return c == 0; },\n ' ');\n \/\/ Remove trailing delimiter.\n boost::algorithm::trim(content);\n return content;\n}\n\ninline std::string readProcLink(const std::string& attr,\n const std::string& pid) {\n \/\/ The exe is a symlink to the binary on-disk.\n auto attr_path = getProcAttr(attr, pid);\n\n std::string result;\n char link_path[PATH_MAX] = {0};\n auto bytes = readlink(attr_path.c_str(), link_path, sizeof(link_path) - 1);\n if (bytes >= 0) {\n result = std::string(link_path);\n }\n\n return result;\n}\n\n\/\/ In the case where the linked binary path ends in \" (deleted)\", and a file\n\/\/ actually exists at that path, check whether the inode of that file matches\n\/\/ the inode of the mapped file in \/proc\/%pid\/maps\nStatus deletedMatchesInode(const std::string& path, const std::string& pid) {\n const std::string maps_path = getProcAttr(\"maps\", pid);\n std::string maps_contents;\n auto s = osquery::readFile(maps_path, maps_contents);\n if (!s.ok()) {\n return Status(-1, \"Cannot read maps file: \" + maps_path);\n }\n\n \/\/ Extract the expected inode of the binary file from \/proc\/%pid\/maps\n boost::smatch what;\n boost::regex expression(\"([0-9]+)\\\\h+\\\\Q\" + path + \"\\\\E\");\n if (!boost::regex_search(maps_contents, what, expression)) {\n return Status(-1, \"Could not find binary inode in maps file: \" + maps_path);\n }\n std::string inode = what[1];\n\n \/\/ stat the file at the expected binary path\n struct stat st;\n if (stat(path.c_str(), &st) != 0) {\n return Status(-1, \"Error in stat of binary: \" + path);\n }\n\n \/\/ If the inodes match, the binary name actually ends with \" (deleted)\"\n if (std::to_string(st.st_ino) == inode) {\n return Status(0, \"Inodes match\");\n } else {\n return Status(1, \"Inodes do not match\");\n }\n}\n\nstd::set getProcList(const QueryContext& context) {\n std::set pidlist;\n if (context.constraints.count(\"pid\") > 0 &&\n context.constraints.at(\"pid\").exists(EQUALS)) {\n for (const auto& pid : context.constraints.at(\"pid\").getAll(EQUALS)) {\n if (isDirectory(\"\/proc\/\" + pid)) {\n pidlist.insert(pid);\n }\n }\n } else {\n osquery::procProcesses(pidlist);\n }\n\n return pidlist;\n}\n\nvoid genProcessEnvironment(const std::string& pid, QueryData& results) {\n auto attr = getProcAttr(\"environ\", pid);\n\n std::string content;\n readFile(attr, content);\n const char* variable = content.c_str();\n\n \/\/ Stop at the end of nul-delimited string content.\n while (*variable > 0) {\n auto buf = std::string(variable);\n size_t idx = buf.find_first_of(\"=\");\n\n Row r;\n r[\"pid\"] = pid;\n r[\"key\"] = buf.substr(0, idx);\n r[\"value\"] = buf.substr(idx + 1);\n results.push_back(r);\n variable += buf.size() + 1;\n }\n}\n\nvoid genProcessMap(const std::string& pid, QueryData& results) {\n auto map = getProcAttr(\"maps\", pid);\n\n std::string content;\n readFile(map, content);\n for (auto& line : osquery::split(content, \"\\n\")) {\n auto fields = osquery::split(line, \" \");\n \/\/ If can't read address, not sure.\n if (fields.size() < 5) {\n continue;\n }\n\n Row r;\n r[\"pid\"] = pid;\n if (!fields[0].empty()) {\n auto addresses = osquery::split(fields[0], \"-\");\n if (addresses.size() >= 2) {\n r[\"start\"] = \"0x\" + addresses[0];\n r[\"end\"] = \"0x\" + addresses[1];\n } else {\n \/\/ Problem with the address format.\n continue;\n }\n }\n\n r[\"permissions\"] = fields[1];\n try {\n auto offset = std::stoll(fields[2], nullptr, 16);\n r[\"offset\"] = (offset != 0) ? BIGINT(offset) : r[\"start\"];\n\n } catch (const std::exception& e) {\n \/\/ Value was out of range or could not be interpreted as a hex long long.\n r[\"offset\"] = \"-1\";\n }\n r[\"device\"] = fields[3];\n r[\"inode\"] = fields[4];\n\n \/\/ Path name must be trimmed.\n if (fields.size() > 5) {\n boost::trim(fields[5]);\n r[\"path\"] = fields[5];\n }\n\n \/\/ BSS with name in pathname.\n r[\"pseudo\"] = (fields[4] == \"0\" && !r[\"path\"].empty()) ? \"1\" : \"0\";\n results.push_back(std::move(r));\n }\n}\n\nstruct SimpleProcStat : private boost::noncopyable {\n \/\/ Output from string parsing \/proc\/\/status.\n std::string name; \/\/ Name:\n std::string real_uid; \/\/ Uid: * - - -\n std::string real_gid; \/\/ Gid: * - - -\n std::string effective_uid; \/\/ Uid: - * - -\n std::string effective_gid; \/\/ Gid: - * - -\n std::string saved_uid; \/\/ Uid: - - * -\n std::string saved_gid; \/\/ Gid: - - * -\n\n std::string resident_size; \/\/ VmRSS:\n std::string total_size; \/\/ VmSize:\n\n \/\/ Output from sring parsing \/proc\/\/stat.\n std::string state;\n std::string parent;\n std::string group;\n std::string nice;\n std::string threads;\n\n std::string user_time;\n std::string system_time;\n std::string start_time;\n\n explicit SimpleProcStat(const std::string& pid);\n};\n\nSimpleProcStat::SimpleProcStat(const std::string& pid) {\n std::string content;\n if (readFile(getProcAttr(\"stat\", pid), content).ok()) {\n auto start = content.find_last_of(\")\");\n \/\/ Start parsing stats from \") ...\"\n if (start == std::string::npos || content.size() <= start + 2) {\n return;\n }\n\n auto details = osquery::split(content.substr(start + 2), \" \");\n if (details.size() <= 19) {\n return;\n }\n\n this->state = details.at(0);\n this->parent = details.at(1);\n this->group = details.at(2);\n this->user_time = details.at(11);\n this->system_time = details.at(12);\n this->nice = details.at(16);\n this->threads = details.at(17);\n try {\n this->start_time = TEXT(AS_LITERAL(BIGINT_LITERAL, details.at(19)) \/ 100);\n } catch (const boost::bad_lexical_cast& e) {\n this->start_time = \"-1\";\n }\n }\n\n \/\/ \/proc\/N\/status may be not available, or readable by this user.\n if (!readFile(getProcAttr(\"status\", pid), content).ok()) {\n return;\n }\n\n for (const auto& line : osquery::split(content, \"\\n\")) {\n \/\/ Status lines are formatted: Key: Value....\\n.\n auto detail = osquery::split(line, \":\", 1);\n if (detail.size() != 2) {\n continue;\n }\n\n \/\/ There are specific fields from each detail.\n if (detail.at(0) == \"Name\") {\n this->name = detail.at(1);\n } else if (detail.at(0) == \"VmRSS\") {\n detail[1].erase(detail.at(1).end() - 3, detail.at(1).end());\n \/\/ Memory is reported in kB.\n this->resident_size = detail.at(1) + \"000\";\n } else if (detail.at(0) == \"VmSize\") {\n detail[1].erase(detail.at(1).end() - 3, detail.at(1).end());\n \/\/ Memory is reported in kB.\n this->total_size = detail.at(1) + \"000\";\n } else if (detail.at(0) == \"Gid\") {\n \/\/ Format is: R E - -\n auto gid_detail = osquery::split(detail.at(1), \"\\t\");\n if (gid_detail.size() == 4) {\n this->real_gid = gid_detail.at(0);\n this->effective_gid = gid_detail.at(1);\n this->saved_gid = gid_detail.at(2);\n }\n } else if (detail.at(0) == \"Uid\") {\n auto uid_detail = osquery::split(detail.at(1), \"\\t\");\n if (uid_detail.size() == 4) {\n this->real_uid = uid_detail.at(0);\n this->effective_uid = uid_detail.at(1);\n this->saved_uid = uid_detail.at(2);\n }\n }\n }\n}\n\n\/**\n * @brief Determine if the process path (binary) exists on the filesystem.\n *\n * If the path of the executable that started the process is available and\n * the path exists on disk, set on_disk to 1. If the path is not\n * available, set on_disk to -1. If, and only if, the path of the\n * executable is available and the file does NOT exist on disk, set on_disk\n * to 0.\n *\n * @param pid The string (because we're referencing file path) pid.\n * @param path A mutable string found from \/proc\/N\/exe. If this is found\n * to contain the (deleted) suffix, it will be removed.\n * @return A tristate -1 error, 1 yes, 0 nope.\n *\/\nint getOnDisk(const std::string& pid, std::string& path) {\n if (path.empty()) {\n return -1;\n }\n\n \/\/ The string appended to the exe path when the binary is deleted\n const std::string kDeletedString = \" (deleted)\";\n if (!boost::algorithm::ends_with(path, kDeletedString)) {\n return (osquery::pathExists(path)) ? 1 : 0;\n }\n\n if (!osquery::pathExists(path)) {\n \/\/ No file exists with the path including \" (deleted)\", so we can strip\n \/\/ this from the path and set on_disk = 0\n path.erase(path.size() - kDeletedString.size());\n return 0;\n }\n\n \/\/ Special case in which we have to check the inode to see whether the\n \/\/ process is actually running from a binary file ending with\n \/\/ \" (deleted)\". See #1607\n std::string maps_contents;\n Status deleted = deletedMatchesInode(path, pid);\n if (deleted.getCode() == -1) {\n LOG(ERROR) << deleted.getMessage();\n return -1;\n } else if (deleted.getCode() == 0) {\n \/\/ The process is actually running from a binary ending with\n \/\/ \" (deleted)\"\n return 1;\n } else {\n \/\/ There is a collision with a file name ending in \" (deleted)\", but\n \/\/ that file is not the binary for this process\n path.erase(path.size() - kDeletedString.size());\n return 0;\n }\n}\n\nvoid genProcess(const std::string& pid, QueryData& results) {\n \/\/ Parse the process stat and status.\n SimpleProcStat proc_stat(pid);\n\n Row r;\n r[\"pid\"] = pid;\n r[\"parent\"] = proc_stat.parent;\n r[\"path\"] = readProcLink(\"exe\", pid);\n r[\"name\"] = proc_stat.name;\n r[\"pgroup\"] = proc_stat.group;\n r[\"state\"] = proc_stat.state;\n r[\"nice\"] = proc_stat.nice;\n r[\"threads\"] = proc_stat.threads;\n \/\/ Read\/parse cmdline arguments.\n r[\"cmdline\"] = readProcCMDLine(pid);\n r[\"cwd\"] = readProcLink(\"cwd\", pid);\n r[\"root\"] = readProcLink(\"root\", pid);\n r[\"uid\"] = proc_stat.real_uid;\n r[\"euid\"] = proc_stat.effective_uid;\n r[\"suid\"] = proc_stat.saved_uid;\n r[\"gid\"] = proc_stat.real_gid;\n r[\"egid\"] = proc_stat.effective_gid;\n r[\"sgid\"] = proc_stat.saved_gid;\n\n r[\"on_disk\"] = INTEGER(getOnDisk(pid, r[\"path\"]));\n\n \/\/ size\/memory information\n r[\"wired_size\"] = \"0\"; \/\/ No support for unpagable counters in linux.\n r[\"resident_size\"] = proc_stat.resident_size;\n r[\"total_size\"] = proc_stat.total_size;\n\n \/\/ time information\n r[\"user_time\"] = proc_stat.user_time;\n r[\"system_time\"] = proc_stat.system_time;\n r[\"start_time\"] = proc_stat.start_time;\n\n results.push_back(r);\n}\n\nQueryData genProcesses(QueryContext& context) {\n QueryData results;\n\n auto pidlist = getProcList(context);\n for (const auto& pid : pidlist) {\n genProcess(pid, results);\n }\n\n return results;\n}\n\nQueryData genProcessEnvs(QueryContext& context) {\n QueryData results;\n\n auto pidlist = getProcList(context);\n for (const auto& pid : pidlist) {\n genProcessEnvironment(pid, results);\n }\n\n return results;\n}\n\nQueryData genProcessMemoryMap(QueryContext& context) {\n QueryData results;\n\n auto pidlist = getProcList(context);\n for (const auto& pid : pidlist) {\n genProcessMap(pid, results);\n }\n\n return results;\n}\n}\n}\nAddress the invalid uid for Linux processes (#2946)\/*\n * Copyright (c) 2014-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"osquery\/core\/conversions.h\"\n\nnamespace osquery {\nnamespace tables {\n\ninline std::string getProcAttr(const std::string& attr,\n const std::string& pid) {\n return \"\/proc\/\" + pid + \"\/\" + attr;\n}\n\ninline std::string readProcCMDLine(const std::string& pid) {\n auto attr = getProcAttr(\"cmdline\", pid);\n\n std::string content;\n readFile(attr, content);\n \/\/ Remove \\0 delimiters.\n std::replace_if(content.begin(),\n content.end(),\n [](const char& c) { return c == 0; },\n ' ');\n \/\/ Remove trailing delimiter.\n boost::algorithm::trim(content);\n return content;\n}\n\ninline std::string readProcLink(const std::string& attr,\n const std::string& pid) {\n \/\/ The exe is a symlink to the binary on-disk.\n auto attr_path = getProcAttr(attr, pid);\n\n std::string result;\n char link_path[PATH_MAX] = {0};\n auto bytes = readlink(attr_path.c_str(), link_path, sizeof(link_path) - 1);\n if (bytes >= 0) {\n result = std::string(link_path);\n }\n\n return result;\n}\n\n\/\/ In the case where the linked binary path ends in \" (deleted)\", and a file\n\/\/ actually exists at that path, check whether the inode of that file matches\n\/\/ the inode of the mapped file in \/proc\/%pid\/maps\nStatus deletedMatchesInode(const std::string& path, const std::string& pid) {\n const std::string maps_path = getProcAttr(\"maps\", pid);\n std::string maps_contents;\n auto s = osquery::readFile(maps_path, maps_contents);\n if (!s.ok()) {\n return Status(-1, \"Cannot read maps file: \" + maps_path);\n }\n\n \/\/ Extract the expected inode of the binary file from \/proc\/%pid\/maps\n boost::smatch what;\n boost::regex expression(\"([0-9]+)\\\\h+\\\\Q\" + path + \"\\\\E\");\n if (!boost::regex_search(maps_contents, what, expression)) {\n return Status(-1, \"Could not find binary inode in maps file: \" + maps_path);\n }\n std::string inode = what[1];\n\n \/\/ stat the file at the expected binary path\n struct stat st;\n if (stat(path.c_str(), &st) != 0) {\n return Status(-1, \"Error in stat of binary: \" + path);\n }\n\n \/\/ If the inodes match, the binary name actually ends with \" (deleted)\"\n if (std::to_string(st.st_ino) == inode) {\n return Status(0, \"Inodes match\");\n } else {\n return Status(1, \"Inodes do not match\");\n }\n}\n\nstd::set getProcList(const QueryContext& context) {\n std::set pidlist;\n if (context.constraints.count(\"pid\") > 0 &&\n context.constraints.at(\"pid\").exists(EQUALS)) {\n for (const auto& pid : context.constraints.at(\"pid\").getAll(EQUALS)) {\n if (isDirectory(\"\/proc\/\" + pid)) {\n pidlist.insert(pid);\n }\n }\n } else {\n osquery::procProcesses(pidlist);\n }\n\n return pidlist;\n}\n\nvoid genProcessEnvironment(const std::string& pid, QueryData& results) {\n auto attr = getProcAttr(\"environ\", pid);\n\n std::string content;\n readFile(attr, content);\n const char* variable = content.c_str();\n\n \/\/ Stop at the end of nul-delimited string content.\n while (*variable > 0) {\n auto buf = std::string(variable);\n size_t idx = buf.find_first_of(\"=\");\n\n Row r;\n r[\"pid\"] = pid;\n r[\"key\"] = buf.substr(0, idx);\n r[\"value\"] = buf.substr(idx + 1);\n results.push_back(r);\n variable += buf.size() + 1;\n }\n}\n\nvoid genProcessMap(const std::string& pid, QueryData& results) {\n auto map = getProcAttr(\"maps\", pid);\n\n std::string content;\n readFile(map, content);\n for (auto& line : osquery::split(content, \"\\n\")) {\n auto fields = osquery::split(line, \" \");\n \/\/ If can't read address, not sure.\n if (fields.size() < 5) {\n continue;\n }\n\n Row r;\n r[\"pid\"] = pid;\n if (!fields[0].empty()) {\n auto addresses = osquery::split(fields[0], \"-\");\n if (addresses.size() >= 2) {\n r[\"start\"] = \"0x\" + addresses[0];\n r[\"end\"] = \"0x\" + addresses[1];\n } else {\n \/\/ Problem with the address format.\n continue;\n }\n }\n\n r[\"permissions\"] = fields[1];\n try {\n auto offset = std::stoll(fields[2], nullptr, 16);\n r[\"offset\"] = (offset != 0) ? BIGINT(offset) : r[\"start\"];\n\n } catch (const std::exception& e) {\n \/\/ Value was out of range or could not be interpreted as a hex long long.\n r[\"offset\"] = \"-1\";\n }\n r[\"device\"] = fields[3];\n r[\"inode\"] = fields[4];\n\n \/\/ Path name must be trimmed.\n if (fields.size() > 5) {\n boost::trim(fields[5]);\n r[\"path\"] = fields[5];\n }\n\n \/\/ BSS with name in pathname.\n r[\"pseudo\"] = (fields[4] == \"0\" && !r[\"path\"].empty()) ? \"1\" : \"0\";\n results.push_back(std::move(r));\n }\n}\n\n\/**\n * Output from string parsing \/proc\/\/status.\n *\/\nstruct SimpleProcStat : private boost::noncopyable {\n public:\n std::string name;\n std::string real_uid;\n std::string real_gid;\n std::string effective_uid;\n std::string effective_gid;\n std::string saved_uid;\n std::string saved_gid;\n std::string resident_size;\n std::string total_size;\n std::string state;\n std::string parent;\n std::string group;\n std::string nice;\n std::string threads;\n std::string user_time;\n std::string system_time;\n std::string start_time;\n\n \/\/\/ For errors processing proc data.\n Status status;\n\n explicit SimpleProcStat(const std::string& pid);\n};\n\nSimpleProcStat::SimpleProcStat(const std::string& pid) {\n std::string content;\n if (readFile(getProcAttr(\"stat\", pid), content).ok()) {\n auto start = content.find_last_of(\")\");\n \/\/ Start parsing stats from \") ...\"\n if (start == std::string::npos || content.size() <= start + 2) {\n status = Status(1, \"Invalid \/proc\/stat header\");\n return;\n }\n\n auto details = osquery::split(content.substr(start + 2), \" \");\n if (details.size() <= 19) {\n status = Status(1, \"Invalid \/proc\/stat content\");\n return;\n }\n\n this->state = details.at(0);\n this->parent = details.at(1);\n this->group = details.at(2);\n this->user_time = details.at(11);\n this->system_time = details.at(12);\n this->nice = details.at(16);\n this->threads = details.at(17);\n try {\n this->start_time = TEXT(AS_LITERAL(BIGINT_LITERAL, details.at(19)) \/ 100);\n } catch (const boost::bad_lexical_cast& e) {\n this->start_time = \"-1\";\n }\n }\n\n \/\/ \/proc\/N\/status may be not available, or readable by this user.\n if (!readFile(getProcAttr(\"status\", pid), content).ok()) {\n status = Status(1, \"Cannot read \/proc\/status\");\n return;\n }\n\n for (const auto& line : osquery::split(content, \"\\n\")) {\n \/\/ Status lines are formatted: Key: Value....\\n.\n auto detail = osquery::split(line, \":\", 1);\n if (detail.size() != 2) {\n continue;\n }\n\n \/\/ There are specific fields from each detail.\n if (detail.at(0) == \"Name\") {\n this->name = detail.at(1);\n } else if (detail.at(0) == \"VmRSS\") {\n detail[1].erase(detail.at(1).end() - 3, detail.at(1).end());\n \/\/ Memory is reported in kB.\n this->resident_size = detail.at(1) + \"000\";\n } else if (detail.at(0) == \"VmSize\") {\n detail[1].erase(detail.at(1).end() - 3, detail.at(1).end());\n \/\/ Memory is reported in kB.\n this->total_size = detail.at(1) + \"000\";\n } else if (detail.at(0) == \"Gid\") {\n \/\/ Format is: R E - -\n auto gid_detail = osquery::split(detail.at(1), \"\\t\");\n if (gid_detail.size() == 4) {\n this->real_gid = gid_detail.at(0);\n this->effective_gid = gid_detail.at(1);\n this->saved_gid = gid_detail.at(2);\n }\n } else if (detail.at(0) == \"Uid\") {\n auto uid_detail = osquery::split(detail.at(1), \"\\t\");\n if (uid_detail.size() == 4) {\n this->real_uid = uid_detail.at(0);\n this->effective_uid = uid_detail.at(1);\n this->saved_uid = uid_detail.at(2);\n }\n }\n }\n}\n\n\/**\n * @brief Determine if the process path (binary) exists on the filesystem.\n *\n * If the path of the executable that started the process is available and\n * the path exists on disk, set on_disk to 1. If the path is not\n * available, set on_disk to -1. If, and only if, the path of the\n * executable is available and the file does NOT exist on disk, set on_disk\n * to 0.\n *\n * @param pid The string (because we're referencing file path) pid.\n * @param path A mutable string found from \/proc\/N\/exe. If this is found\n * to contain the (deleted) suffix, it will be removed.\n * @return A tristate -1 error, 1 yes, 0 nope.\n *\/\nint getOnDisk(const std::string& pid, std::string& path) {\n if (path.empty()) {\n return -1;\n }\n\n \/\/ The string appended to the exe path when the binary is deleted\n const std::string kDeletedString = \" (deleted)\";\n if (!boost::algorithm::ends_with(path, kDeletedString)) {\n return (osquery::pathExists(path)) ? 1 : 0;\n }\n\n if (!osquery::pathExists(path)) {\n \/\/ No file exists with the path including \" (deleted)\", so we can strip\n \/\/ this from the path and set on_disk = 0\n path.erase(path.size() - kDeletedString.size());\n return 0;\n }\n\n \/\/ Special case in which we have to check the inode to see whether the\n \/\/ process is actually running from a binary file ending with\n \/\/ \" (deleted)\". See #1607\n std::string maps_contents;\n Status deleted = deletedMatchesInode(path, pid);\n if (deleted.getCode() == -1) {\n LOG(ERROR) << deleted.getMessage();\n return -1;\n } else if (deleted.getCode() == 0) {\n \/\/ The process is actually running from a binary ending with\n \/\/ \" (deleted)\"\n return 1;\n } else {\n \/\/ There is a collision with a file name ending in \" (deleted)\", but\n \/\/ that file is not the binary for this process\n path.erase(path.size() - kDeletedString.size());\n return 0;\n }\n}\n\nvoid genProcess(const std::string& pid, QueryData& results) {\n \/\/ Parse the process stat and status.\n SimpleProcStat proc_stat(pid);\n\n if (!proc_stat.status.ok()) {\n VLOG(1) << proc_stat.status.getMessage() << \" for pid \" << pid;\n return;\n }\n\n Row r;\n r[\"pid\"] = pid;\n r[\"parent\"] = proc_stat.parent;\n r[\"path\"] = readProcLink(\"exe\", pid);\n r[\"name\"] = proc_stat.name;\n r[\"pgroup\"] = proc_stat.group;\n r[\"state\"] = proc_stat.state;\n r[\"nice\"] = proc_stat.nice;\n r[\"threads\"] = proc_stat.threads;\n \/\/ Read\/parse cmdline arguments.\n r[\"cmdline\"] = readProcCMDLine(pid);\n r[\"cwd\"] = readProcLink(\"cwd\", pid);\n r[\"root\"] = readProcLink(\"root\", pid);\n r[\"uid\"] = proc_stat.real_uid;\n r[\"euid\"] = proc_stat.effective_uid;\n r[\"suid\"] = proc_stat.saved_uid;\n r[\"gid\"] = proc_stat.real_gid;\n r[\"egid\"] = proc_stat.effective_gid;\n r[\"sgid\"] = proc_stat.saved_gid;\n\n r[\"on_disk\"] = INTEGER(getOnDisk(pid, r[\"path\"]));\n\n \/\/ size\/memory information\n r[\"wired_size\"] = \"0\"; \/\/ No support for unpagable counters in linux.\n r[\"resident_size\"] = proc_stat.resident_size;\n r[\"total_size\"] = proc_stat.total_size;\n\n \/\/ time information\n r[\"user_time\"] = proc_stat.user_time;\n r[\"system_time\"] = proc_stat.system_time;\n r[\"start_time\"] = proc_stat.start_time;\n\n results.push_back(r);\n}\n\nQueryData genProcesses(QueryContext& context) {\n QueryData results;\n\n auto pidlist = getProcList(context);\n for (const auto& pid : pidlist) {\n genProcess(pid, results);\n }\n\n return results;\n}\n\nQueryData genProcessEnvs(QueryContext& context) {\n QueryData results;\n\n auto pidlist = getProcList(context);\n for (const auto& pid : pidlist) {\n genProcessEnvironment(pid, results);\n }\n\n return results;\n}\n\nQueryData genProcessMemoryMap(QueryContext& context) {\n QueryData results;\n\n auto pidlist = getProcList(context);\n for (const auto& pid : pidlist) {\n genProcessMap(pid, results);\n }\n\n return results;\n}\n}\n}\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,\n * University of Southern California\n * Jan Issac (jan.issac@gmail.com)\n * Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n *\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n\/**\n * @date 2015\n * @author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n * Max-Planck-Institute for Intelligent Systems\n *\/\n\n\n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\ntemplate\nbool moments_are_similar(Vector mean_a, Matrix cov_a,\n Vector mean_b, Matrix cov_b, double epsilon = 0.1)\n{\n Matrix cov_delta = cov_a.inverse() * cov_b;\n bool are_similar = cov_delta.isApprox(Matrix::Identity(), epsilon);\n\n Matrix square_root = fl::matrix_sqrt(cov_a);\n double max_mean_delta =\n (square_root.inverse() * (mean_a-mean_b)).cwiseAbs().maxCoeff();\n\n are_similar = are_similar && max_mean_delta < epsilon;\n\n return are_similar;\n}\n\n\nEigen::Matrix some_rotation()\n{\n double angle = 2 * M_PI * double(rand()) \/ double(RAND_MAX);\n\n Eigen::Matrix R = Eigen::Matrix::Identity();\n\n R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitX());\n R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitZ());\n R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitY());\n return R;\n}\n\n\nTEST(particle_filter, predict)\n{\n typedef Eigen::Matrix State;\n typedef Eigen::Matrix Observation;\n typedef Eigen::Matrix Input;\n\n typedef Eigen::Matrix Matrix;\n\n typedef fl::LinearGaussianProcessModel ProcessModel;\n typedef fl::LinearObservationModel ObservationModel;\n\n \/\/ particle filter\n typedef fl::ParticleFilter ParticleFilter;\n typedef ParticleFilter::Belief ParticleBelief;\n\n \/\/ gaussian filter\n typedef fl::GaussianFilter GaussianFilter;\n typedef GaussianFilter::Belief GaussianBelief;\n\n\n srand(0);\n size_t N_particles = 10000;\n size_t N_steps = 10;\n size_t delta_time = 1;\n\n\n \/\/ create process model\n ProcessModel process_model;\n {\n process_model.A(some_rotation());\n Matrix R = some_rotation();\n Matrix D = Eigen::DiagonalMatrix(1, 3.5, 1.2);\n process_model.covariance(R*D*R.transpose());\n }\n\n \/\/ create observation model\n \/\/\/ \\todo this is a hack because the GF does not currently work with the new\n \/\/\/ observation model interface\n ObservationModel observation_model;\n {\n observation_model.sensor_matrix(some_rotation());\n Matrix R = some_rotation();\n Matrix D = Eigen::DiagonalMatrix(3.1, 1.0, 1.3);\n D = D.cwiseSqrt();\n observation_model.noise_matrix(R*D);\n }\n\n \/\/ create filters\n ParticleFilter particle_filter(process_model, observation_model);\n GaussianFilter gaussian_filter(process_model, observation_model);\n\n \/\/ create intial beliefs\n GaussianBelief gaussian_belief;\n {\n gaussian_belief.mean(State::Zero());\n gaussian_belief.covariance(Matrix::Identity());\n }\n ParticleBelief particle_belief;\n particle_belief.from_distribution(gaussian_belief, N_particles);\n\n \/\/ run prediction\n for(size_t i = 0; i < N_steps; i++)\n {\n particle_filter.predict(delta_time, State::Zero(),\n particle_belief, particle_belief);\n\n gaussian_filter.predict(delta_time, State::Zero(),\n gaussian_belief, gaussian_belief);\n\n EXPECT_TRUE(moments_are_similar(\n particle_belief.mean(), particle_belief.covariance(),\n gaussian_belief.mean(), gaussian_belief.covariance()));\n }\n}\n\n\n\n\n\n\n\n\n\nTEST(particle_filter, update)\n{\n typedef Eigen::Matrix State;\n typedef Eigen::Matrix Observation;\n typedef Eigen::Matrix Input;\n\n typedef Eigen::Matrix Matrix;\n\n typedef fl::LinearGaussianProcessModel ProcessModel;\n typedef fl::LinearObservationModel ObservationModel;\n \/\/ particle filter\n typedef fl::ParticleFilter ParticleFilter;\n typedef ParticleFilter::Belief ParticleBelief;\n\n \/\/ gaussian filter\n typedef fl::GaussianFilter GaussianFilter;\n typedef GaussianFilter::Belief GaussianBelief;\n\n\n srand(0);\n size_t N_particles = 10000;\n size_t N_steps = 10;\n\n\n \/\/ create process model\n ProcessModel process_model;\n {\n process_model.A(some_rotation());\n Matrix R = some_rotation();\n Matrix D = Eigen::DiagonalMatrix(1, 3.5, 1.2);\n process_model.covariance(R*D*R.transpose());\n }\n\n \/\/ create observation model\n \/\/\/ \\todo this is a hack because the GF does not currently work with the new\n \/\/\/ observation model interface\n ObservationModel observation_model;\n {\n observation_model.sensor_matrix(some_rotation());\n Matrix R = some_rotation();\n Matrix D = Eigen::DiagonalMatrix(3.1, 1.0, 1.3);\n D = D.cwiseSqrt();\n observation_model.noise_matrix(R*D);\n }\n\n \/\/ create filters\n ParticleFilter particle_filter(process_model, observation_model);\n GaussianFilter gaussian_filter(process_model, observation_model);\n\n \/\/ create intial beliefs\n GaussianBelief gaussian_belief;\n {\n gaussian_belief.mean(State::Zero());\n gaussian_belief.covariance(Matrix::Identity());\n }\n ParticleBelief particle_belief;\n particle_belief.from_distribution(gaussian_belief, N_particles);\n\n\n \/\/ run prediction\n for(size_t i = 0; i < N_steps; i++)\n {\n Observation observation(0.5, 0.5, 0.5);\n\n particle_filter.update(observation, particle_belief, particle_belief);\n gaussian_filter.update(observation, gaussian_belief, gaussian_belief);\n\n EXPECT_TRUE(moments_are_similar(\n particle_belief.mean(), particle_belief.covariance(),\n gaussian_belief.mean(), gaussian_belief.covariance()));\n }\n\n}\n\n\n\n\n\n\n\n\n\nTEST(particle_filter, predict_and_update)\n{\n typedef Eigen::Matrix State;\n typedef Eigen::Matrix Observation;\n typedef Eigen::Matrix Input;\n\n typedef Eigen::Matrix Matrix;\n\n typedef fl::LinearGaussianProcessModel ProcessModel;\n typedef fl::LinearObservationModel ObservationModel;\n\n \/\/ particle filter\n typedef fl::ParticleFilter ParticleFilter;\n typedef ParticleFilter::Belief ParticleBelief;\n\n \/\/ gaussian filter\n typedef fl::GaussianFilter GaussianFilter;\n typedef GaussianFilter::Belief GaussianBelief;\n\n\n srand(0);\n size_t N_particles = 10000;\n size_t N_steps = 10;\n size_t delta_time = 1;\n\n\n \/\/ create process model\n ProcessModel process_model;\n {\n process_model.A(some_rotation());\n Matrix R = some_rotation();\n Matrix D = Eigen::DiagonalMatrix(1, 3.5, 1.2);\n process_model.covariance(R*D*R.transpose());\n }\n\n \/\/ create observation model\n \/\/\/ \\todo this is a hack because the GF does not currently work with the new\n \/\/\/ observation model interface\n ObservationModel observation_model;\n {\n observation_model.sensor_matrix(some_rotation());\n Matrix R = some_rotation();\n Matrix D = Eigen::DiagonalMatrix(3.1, 1.0, 1.3);\n D = D.cwiseSqrt();\n observation_model.noise_matrix(R*D);\n }\n\n \/\/ create filters\n ParticleFilter particle_filter(process_model, observation_model);\n GaussianFilter gaussian_filter(process_model, observation_model);\n\n \/\/ create intial beliefs\n GaussianBelief gaussian_belief;\n {\n gaussian_belief.mean(State::Zero());\n gaussian_belief.covariance(Matrix::Identity());\n }\n ParticleBelief particle_belief;\n particle_belief.from_distribution(gaussian_belief, N_particles);\n\n\n fl::StandardGaussian standard_gaussian;\n State state = gaussian_belief.sample();\n \/\/ run prediction\n for(size_t i = 0; i < N_steps; i++)\n {\n \/\/ simulate system\n state = process_model.predict_state(delta_time,\n state,\n standard_gaussian.sample(),\n State::Zero());\n Observation observation =\n observation_model.observation(state, standard_gaussian.sample());\n\n \/\/ predict\n particle_filter.predict(delta_time, State::Zero(),\n particle_belief, particle_belief);\n gaussian_filter.predict(delta_time, State::Zero(),\n gaussian_belief, gaussian_belief);\n\n \/\/ update\n particle_filter.update(observation, particle_belief, particle_belief);\n gaussian_filter.update(observation, gaussian_belief, gaussian_belief);\n }\n\n State delta = particle_belief.mean() - gaussian_belief.mean();\n double mh_distance = delta.transpose() * gaussian_belief.precision() * delta;\n\n \/\/ make sure that the estimate of the pf is within one std dev\n EXPECT_TRUE(std::sqrt(mh_distance) <= 1.0);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nUpdated license\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * @date 2015\n * @author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n * Max-Planck-Institute for Intelligent Systems\n *\/\n\n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\ntemplate\nbool moments_are_similar(Vector mean_a, Matrix cov_a,\n Vector mean_b, Matrix cov_b, double epsilon = 0.1)\n{\n Matrix cov_delta = cov_a.inverse() * cov_b;\n bool are_similar = cov_delta.isApprox(Matrix::Identity(), epsilon);\n\n Matrix square_root = fl::matrix_sqrt(cov_a);\n double max_mean_delta =\n (square_root.inverse() * (mean_a-mean_b)).cwiseAbs().maxCoeff();\n\n are_similar = are_similar && max_mean_delta < epsilon;\n\n return are_similar;\n}\n\nEigen::Matrix some_rotation()\n{\n double angle = 2 * M_PI * double(rand()) \/ double(RAND_MAX);\n\n Eigen::Matrix R = Eigen::Matrix::Identity();\n\n R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitX());\n R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitZ());\n R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitY());\n return R;\n}\n\nTEST(particle_filter, predict)\n{\n typedef Eigen::Matrix State;\n typedef Eigen::Matrix Observation;\n typedef Eigen::Matrix Input;\n\n typedef Eigen::Matrix Matrix;\n\n typedef fl::LinearGaussianProcessModel ProcessModel;\n typedef fl::LinearObservationModel ObservationModel;\n\n \/\/ particle filter\n typedef fl::ParticleFilter ParticleFilter;\n typedef ParticleFilter::Belief ParticleBelief;\n\n \/\/ gaussian filter\n typedef fl::GaussianFilter GaussianFilter;\n typedef GaussianFilter::Belief GaussianBelief;\n\n\n srand(0);\n size_t N_particles = 10000;\n size_t N_steps = 10;\n size_t delta_time = 1;\n\n\n \/\/ create process model\n ProcessModel process_model;\n {\n process_model.A(some_rotation());\n Matrix R = some_rotation();\n Matrix D = Eigen::DiagonalMatrix(1, 3.5, 1.2);\n process_model.covariance(R*D*R.transpose());\n }\n\n \/\/ create observation model\n \/\/\/ \\todo this is a hack because the GF does not currently work with the new\n \/\/\/ observation model interface\n ObservationModel observation_model;\n {\n observation_model.sensor_matrix(some_rotation());\n Matrix R = some_rotation();\n Matrix D = Eigen::DiagonalMatrix(3.1, 1.0, 1.3);\n D = D.cwiseSqrt();\n observation_model.noise_matrix(R*D);\n }\n\n \/\/ create filters\n ParticleFilter particle_filter(process_model, observation_model);\n GaussianFilter gaussian_filter(process_model, observation_model);\n\n \/\/ create intial beliefs\n GaussianBelief gaussian_belief;\n {\n gaussian_belief.mean(State::Zero());\n gaussian_belief.covariance(Matrix::Identity());\n }\n ParticleBelief particle_belief;\n particle_belief.from_distribution(gaussian_belief, N_particles);\n\n \/\/ run prediction\n for(size_t i = 0; i < N_steps; i++)\n {\n particle_filter.predict(delta_time, State::Zero(),\n particle_belief, particle_belief);\n\n gaussian_filter.predict(delta_time, State::Zero(),\n gaussian_belief, gaussian_belief);\n\n EXPECT_TRUE(moments_are_similar(\n particle_belief.mean(), particle_belief.covariance(),\n gaussian_belief.mean(), gaussian_belief.covariance()));\n }\n}\n\nTEST(particle_filter, update)\n{\n typedef Eigen::Matrix State;\n typedef Eigen::Matrix Observation;\n typedef Eigen::Matrix Input;\n\n typedef Eigen::Matrix Matrix;\n\n typedef fl::LinearGaussianProcessModel ProcessModel;\n typedef fl::LinearObservationModel ObservationModel;\n \/\/ particle filter\n typedef fl::ParticleFilter ParticleFilter;\n typedef ParticleFilter::Belief ParticleBelief;\n\n \/\/ gaussian filter\n typedef fl::GaussianFilter GaussianFilter;\n typedef GaussianFilter::Belief GaussianBelief;\n\n\n srand(0);\n size_t N_particles = 10000;\n size_t N_steps = 10;\n\n\n \/\/ create process model\n ProcessModel process_model;\n {\n process_model.A(some_rotation());\n Matrix R = some_rotation();\n Matrix D = Eigen::DiagonalMatrix(1, 3.5, 1.2);\n process_model.covariance(R*D*R.transpose());\n }\n\n \/\/ create observation model\n \/\/\/ \\todo this is a hack because the GF does not currently work with the new\n \/\/\/ observation model interface\n ObservationModel observation_model;\n {\n observation_model.sensor_matrix(some_rotation());\n Matrix R = some_rotation();\n Matrix D = Eigen::DiagonalMatrix(3.1, 1.0, 1.3);\n D = D.cwiseSqrt();\n observation_model.noise_matrix(R*D);\n }\n\n \/\/ create filters\n ParticleFilter particle_filter(process_model, observation_model);\n GaussianFilter gaussian_filter(process_model, observation_model);\n\n \/\/ create intial beliefs\n GaussianBelief gaussian_belief;\n {\n gaussian_belief.mean(State::Zero());\n gaussian_belief.covariance(Matrix::Identity());\n }\n ParticleBelief particle_belief;\n particle_belief.from_distribution(gaussian_belief, N_particles);\n\n\n \/\/ run prediction\n for(size_t i = 0; i < N_steps; i++)\n {\n Observation observation(0.5, 0.5, 0.5);\n\n particle_filter.update(observation, particle_belief, particle_belief);\n gaussian_filter.update(observation, gaussian_belief, gaussian_belief);\n\n EXPECT_TRUE(moments_are_similar(\n particle_belief.mean(), particle_belief.covariance(),\n gaussian_belief.mean(), gaussian_belief.covariance()));\n }\n\n}\n\nTEST(particle_filter, predict_and_update)\n{\n typedef Eigen::Matrix State;\n typedef Eigen::Matrix Observation;\n typedef Eigen::Matrix Input;\n\n typedef Eigen::Matrix Matrix;\n\n typedef fl::LinearGaussianProcessModel ProcessModel;\n typedef fl::LinearObservationModel ObservationModel;\n\n \/\/ particle filter\n typedef fl::ParticleFilter ParticleFilter;\n typedef ParticleFilter::Belief ParticleBelief;\n\n \/\/ gaussian filter\n typedef fl::GaussianFilter GaussianFilter;\n typedef GaussianFilter::Belief GaussianBelief;\n\n\n srand(0);\n size_t N_particles = 10000;\n size_t N_steps = 10;\n size_t delta_time = 1;\n\n\n \/\/ create process model\n ProcessModel process_model;\n {\n process_model.A(some_rotation());\n Matrix R = some_rotation();\n Matrix D = Eigen::DiagonalMatrix(1, 3.5, 1.2);\n process_model.covariance(R*D*R.transpose());\n }\n\n \/\/ create observation model\n \/\/\/ \\todo this is a hack because the GF does not currently work with the new\n \/\/\/ observation model interface\n ObservationModel observation_model;\n {\n observation_model.sensor_matrix(some_rotation());\n Matrix R = some_rotation();\n Matrix D = Eigen::DiagonalMatrix(3.1, 1.0, 1.3);\n D = D.cwiseSqrt();\n observation_model.noise_matrix(R*D);\n }\n\n \/\/ create filters\n ParticleFilter particle_filter(process_model, observation_model);\n GaussianFilter gaussian_filter(process_model, observation_model);\n\n \/\/ create intial beliefs\n GaussianBelief gaussian_belief;\n {\n gaussian_belief.mean(State::Zero());\n gaussian_belief.covariance(Matrix::Identity());\n }\n ParticleBelief particle_belief;\n particle_belief.from_distribution(gaussian_belief, N_particles);\n\n\n fl::StandardGaussian standard_gaussian;\n State state = gaussian_belief.sample();\n \/\/ run prediction\n for(size_t i = 0; i < N_steps; i++)\n {\n \/\/ simulate system\n state = process_model.predict_state(delta_time,\n state,\n standard_gaussian.sample(),\n State::Zero());\n Observation observation =\n observation_model.observation(state, standard_gaussian.sample());\n\n \/\/ predict\n particle_filter.predict(delta_time, State::Zero(),\n particle_belief, particle_belief);\n gaussian_filter.predict(delta_time, State::Zero(),\n gaussian_belief, gaussian_belief);\n\n \/\/ update\n particle_filter.update(observation, particle_belief, particle_belief);\n gaussian_filter.update(observation, gaussian_belief, gaussian_belief);\n }\n\n State delta = particle_belief.mean() - gaussian_belief.mean();\n double mh_distance = delta.transpose() * gaussian_belief.precision() * delta;\n\n \/\/ make sure that the estimate of the pf is within one std dev\n EXPECT_TRUE(std::sqrt(mh_distance) <= 1.0);\n}\n<|endoftext|>"} {"text":"\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing af::dim4;\nusing namespace detail;\n\ntemplate\nstatic inline af_array where(const af_array in)\n{\n return getHandle(where(getArray(in)));\n}\n\naf_err af_where(af_array *idx, const af_array in)\n{\n try {\n af_dtype type = getInfo(in).getType();\n af_array res;\n switch(type) {\n case f32: res = where(in); break;\n case f64: res = where(in); break;\n case c32: res = where(in); break;\n case c64: res = where(in); break;\n case s32: res = where(in); break;\n case u32: res = where(in); break;\n case u8 : res = where(in); break;\n case b8 : res = where(in); break;\n default:\n TYPE_ERROR(1, type);\n }\n std::swap(*idx, res);\n }\n CATCHALL\n\n return AF_SUCCESS;\n}\nSTYLE: Making the function \"where\" more explicit in C API\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing af::dim4;\nusing namespace detail;\n\ntemplate\nstatic inline af_array where(const af_array in)\n{\n \/\/ Making it more explicit that the output is uint\n return getHandle(where(getArray(in)));\n}\n\naf_err af_where(af_array *idx, const af_array in)\n{\n try {\n af_dtype type = getInfo(in).getType();\n af_array res;\n switch(type) {\n case f32: res = where(in); break;\n case f64: res = where(in); break;\n case c32: res = where(in); break;\n case c64: res = where(in); break;\n case s32: res = where(in); break;\n case u32: res = where(in); break;\n case u8 : res = where(in); break;\n case b8 : res = where(in); break;\n default:\n TYPE_ERROR(1, type);\n }\n std::swap(*idx, res);\n }\n CATCHALL\n\n return AF_SUCCESS;\n}\n<|endoftext|>"} {"text":"#define BOOST_TEST_MODULE SerializationTest\n#include \n\n#include \n#include \n\n\/** Based local map **\/\n#include \n\nusing namespace ::maps::grid;\n\nBOOST_AUTO_TEST_CASE(test_mls_surfacepatchbase_serialization)\n{\n SurfacePatchBase sp_o(0.5, 1.3);\n\n std::stringstream stream;\n boost::archive::binary_oarchive oa(stream);\n oa << sp_o;\n\n \/\/ deserialize from string stream\n boost::archive::binary_iarchive *ia = new boost::archive::binary_iarchive(stream);\n SurfacePatchBase sp_i;\n (*ia) >> sp_i;\n\n BOOST_CHECK(sp_i.getMin() == sp_o.getMin()); \n BOOST_CHECK(sp_i.getMax() == sp_o.getMax());\n BOOST_CHECK(sp_i.getTop() == sp_o.getTop());\n BOOST_CHECK(sp_i.getBottom() == sp_o.getBottom());\n}\n\n\nBOOST_AUTO_TEST_CASE(test_mls_surfacepatchslope_serialization)\n{\n SurfacePatch sp_o(Eigen::Vector3f(-3.2, 2.5, -4.5), 4.6);\n\n std::stringstream stream;\n boost::archive::binary_oarchive oa(stream);\n oa << sp_o;\n\n \/\/ deserialize from string stream\n boost::archive::binary_iarchive *ia = new boost::archive::binary_iarchive(stream);\n SurfacePatch sp_i;\n (*ia) >> sp_i;\n\n BOOST_CHECK(sp_i.getMin() == sp_o.getMin()); \n BOOST_CHECK(sp_i.getMax() == sp_o.getMax());\n BOOST_CHECK(sp_i.getTop() == sp_o.getTop());\n BOOST_CHECK(sp_i.getBottom() == sp_o.getBottom());\n\n BOOST_CHECK(sp_i. getCenter() == sp_o. getCenter()); \n BOOST_CHECK(sp_i.getNormal() == sp_o.getNormal());\n}\n\nBOOST_AUTO_TEST_CASE(test_mls_surfacepatchkalman_serialization)\n{\n SurfacePatch sp_o(Eigen::Vector3f(-3.2, 2.5, -4.5), 4.6);\n\n std::stringstream stream;\n boost::archive::binary_oarchive oa(stream);\n oa << sp_o;\n\n \/\/ deserialize from string stream\n boost::archive::binary_iarchive *ia = new boost::archive::binary_iarchive(stream);\n SurfacePatch sp_i;\n (*ia) >> sp_i;\n\n BOOST_CHECK(sp_i.getMin() == sp_o.getMin()); \n BOOST_CHECK(sp_i.getMax() == sp_o.getMax());\n BOOST_CHECK(sp_i.getTop() == sp_o.getTop());\n BOOST_CHECK(sp_i.getBottom() == sp_o.getBottom());\n\n BOOST_CHECK(sp_i. getCenter() == sp_o. getCenter()); \n BOOST_CHECK(sp_i.getNormal() == sp_o.getNormal());\n}\n\nBOOST_AUTO_TEST_CASE(test_mls_serialization)\n{\n \/\/ GridConfig conf(300, 300, 0.05, 0.05, -7.5, -7.5);\n Vector2d res(0.05, 0.05);\n Vector2ui numCells(300, 300);\n\n MLSConfig mls_config;\n mls_config.updateModel = MLSConfig::SLOPE;\n \/\/mls_config.updateModel = MLSConfig::KALMAN;\n MLSMapSloped mls_o = MLSMapSloped(numCells, res, mls_config);\n\n \/** Translate the local frame (offset) **\/\n mls_o.getLocalFrame().translation() << 0.5*mls_o.getSize(), 0;\n\n\n for (unsigned int x = 0; x < numCells.x(); ++x) for(float dx = -.5f; dx <0.49f; dx+=0.125)\n {\n float xx = x+dx-numCells.x()\/2;\n float cs = std::cos(xx * M_PI\/50);\n for (unsigned int y = 0; y < numCells.y(); ++y) for (float dy = -0.5f; dy<0.49; dy+=0.125)\n {\n float yy = y+dy-numCells.y()\/2;\n float sn = std::sin(yy* M_PI\/50);\n\n mls_o.mergePoint(Eigen::Vector3d(xx*res.x(), yy*res.y(), cs*sn));\n }\n }\n\n std::stringstream stream;\n boost::archive::binary_oarchive oa(stream);\n oa << mls_o; \n\n boost::archive::binary_iarchive *ia = new boost::archive::binary_iarchive(stream);\n MLSMapSloped mls_i;\n (*ia) >> mls_i;\n\n \/\/ Grid configuration\n \/\/BOOST_CHECK(mls_o.getDefaultValue() == mls_i.getDefaultValue()); \n BOOST_CHECK(mls_o.getResolution() == mls_i.getResolution()); \n BOOST_CHECK(mls_o.getNumCells() == mls_i.getNumCells());\n\n \/\/ MLSGrid configuration\n BOOST_CHECK(mls_o.getConfig().gapSize == mls_i.getConfig().gapSize);\n BOOST_CHECK(mls_o.getConfig().thickness == mls_i.getConfig().thickness);\n BOOST_CHECK(mls_o.getConfig().useColor == mls_i.getConfig().useColor);\n BOOST_CHECK(mls_o.getConfig().updateModel == mls_i.getConfig().updateModel);\n BOOST_CHECK(mls_o.getConfig().useNegativeInformation == mls_i.getConfig().useNegativeInformation);\n\n for(size_t x = 0; x < numCells.x(); ++x)\n {\n for(size_t y = 0; y < numCells.y(); ++y)\n {\n Index idx(x,y);\n typedef MLSMapSloped::CellType Cell;\n const Cell &cell_o = mls_o.at(idx);\n const Cell &cell_i = mls_i.at(idx);\n\n \/\/ check the number of patches in the cells\n BOOST_CHECK_EQUAL(cell_o.size(), cell_i.size());\n\n \/\/ check the patches\n Cell::const_iterator it_o = cell_o.begin();\n Cell::const_iterator it_i = cell_i.begin();\n Cell::const_iterator end_o = cell_o.end();\n Cell::const_iterator end_i = cell_i.end();\n for(; it_o != end_o; ++it_o, ++it_i)\n {\n BOOST_CHECK(it_i != end_i);\n BOOST_CHECK_EQUAL(it_o->getMin(), it_i->getMin());\n BOOST_CHECK_EQUAL(it_o->getMax(), it_i->getMax());\n BOOST_CHECK_EQUAL(it_o->getTop(), it_i->getTop());\n BOOST_CHECK_EQUAL(it_o->getBottom(), it_i->getBottom());\n }\n BOOST_CHECK(it_i == end_i);\n }\n }\n\n}Fixed (and simplified) unit test#define BOOST_TEST_MODULE SerializationTest\n#include \n\n#include \n#include \n\n\/** Based local map **\/\n#include \n\nusing namespace ::maps::grid;\n\nBOOST_AUTO_TEST_CASE(test_mls_surfacepatchbase_serialization)\n{\n SurfacePatchBase sp_o(0.5, 1.3);\n\n std::stringstream stream;\n boost::archive::binary_oarchive oa(stream);\n oa << sp_o;\n\n \/\/ deserialize from string stream\n boost::archive::binary_iarchive *ia = new boost::archive::binary_iarchive(stream);\n SurfacePatchBase sp_i;\n (*ia) >> sp_i;\n\n BOOST_CHECK(sp_i.getMin() == sp_o.getMin()); \n BOOST_CHECK(sp_i.getMax() == sp_o.getMax());\n BOOST_CHECK(sp_i.getTop() == sp_o.getTop());\n BOOST_CHECK(sp_i.getBottom() == sp_o.getBottom());\n}\n\n\nBOOST_AUTO_TEST_CASE(test_mls_surfacepatchslope_serialization)\n{\n SurfacePatch sp_o(Eigen::Vector3f(-3.2, 2.5, -4.5), 4.6);\n\n std::stringstream stream;\n boost::archive::binary_oarchive oa(stream);\n oa << sp_o;\n\n \/\/ deserialize from string stream\n boost::archive::binary_iarchive *ia = new boost::archive::binary_iarchive(stream);\n SurfacePatch sp_i;\n (*ia) >> sp_i;\n\n BOOST_CHECK(sp_i.getMin() == sp_o.getMin()); \n BOOST_CHECK(sp_i.getMax() == sp_o.getMax());\n BOOST_CHECK(sp_i.getTop() == sp_o.getTop());\n BOOST_CHECK(sp_i.getBottom() == sp_o.getBottom());\n\n BOOST_CHECK(sp_i. getCenter() == sp_o. getCenter()); \n BOOST_CHECK(sp_i.getNormal() == sp_o.getNormal());\n}\n\nBOOST_AUTO_TEST_CASE(test_mls_surfacepatchkalman_serialization)\n{\n SurfacePatch sp_o(Eigen::Vector3f(-3.2, 2.5, -4.5), 4.6);\n\n std::stringstream stream;\n boost::archive::binary_oarchive oa(stream);\n oa << sp_o;\n\n \/\/ deserialize from string stream\n boost::archive::binary_iarchive *ia = new boost::archive::binary_iarchive(stream);\n SurfacePatch sp_i;\n (*ia) >> sp_i;\n\n BOOST_CHECK(sp_i.getMin() == sp_o.getMin()); \n BOOST_CHECK(sp_i.getMax() == sp_o.getMax());\n BOOST_CHECK(sp_i.getTop() == sp_o.getTop());\n BOOST_CHECK(sp_i.getBottom() == sp_o.getBottom());\n\n BOOST_CHECK(sp_i. getCenter() == sp_o. getCenter()); \n BOOST_CHECK(sp_i.getNormal() == sp_o.getNormal());\n}\n\nBOOST_AUTO_TEST_CASE(test_mls_serialization)\n{\n \/\/ GridConfig conf(300, 300, 0.05, 0.05, -7.5, -7.5);\n Vector2d res(0.05, 0.05);\n Vector2ui numCells(300, 300);\n\n MLSConfig mls_config;\n mls_config.updateModel = MLSConfig::SLOPE;\n \/\/mls_config.updateModel = MLSConfig::KALMAN;\n MLSMapSloped mls_o = MLSMapSloped(numCells, res, mls_config);\n\n \/** Translate the local frame (offset) **\/\n mls_o.getLocalFrame().translation() << 0.5*mls_o.getSize(), 0;\n\n\n Eigen::Vector2d max = 0.5 * mls_o.getSize();\n Eigen::Vector2d min = -0.5 * mls_o.getSize();\n for (double x = min.x(); x < max.x(); x += 0.00625)\n {\n double cs = std::cos(x * M_PI\/2.5);\n for (double y = min.y(); y < max.y(); y += 0.00625)\n {\n double sn = std::sin(y * M_PI\/2.5);\n mls_o.mergePoint(Eigen::Vector3d(x, y, cs*sn));\n }\n }\n\n std::stringstream stream;\n boost::archive::binary_oarchive oa(stream);\n oa << mls_o; \n\n boost::archive::binary_iarchive *ia = new boost::archive::binary_iarchive(stream);\n MLSMapSloped mls_i;\n (*ia) >> mls_i;\n\n \/\/ Grid configuration\n \/\/BOOST_CHECK(mls_o.getDefaultValue() == mls_i.getDefaultValue()); \n BOOST_CHECK(mls_o.getResolution() == mls_i.getResolution()); \n BOOST_CHECK(mls_o.getNumCells() == mls_i.getNumCells());\n\n \/\/ MLSGrid configuration\n BOOST_CHECK(mls_o.getConfig().gapSize == mls_i.getConfig().gapSize);\n BOOST_CHECK(mls_o.getConfig().thickness == mls_i.getConfig().thickness);\n BOOST_CHECK(mls_o.getConfig().useColor == mls_i.getConfig().useColor);\n BOOST_CHECK(mls_o.getConfig().updateModel == mls_i.getConfig().updateModel);\n BOOST_CHECK(mls_o.getConfig().useNegativeInformation == mls_i.getConfig().useNegativeInformation);\n\n for(size_t x = 0; x < numCells.x(); ++x)\n {\n for(size_t y = 0; y < numCells.y(); ++y)\n {\n Index idx(x,y);\n typedef MLSMapSloped::CellType Cell;\n const Cell &cell_o = mls_o.at(idx);\n const Cell &cell_i = mls_i.at(idx);\n\n \/\/ check the number of patches in the cells\n BOOST_CHECK_EQUAL(cell_o.size(), cell_i.size());\n\n \/\/ check the patches\n Cell::const_iterator it_o = cell_o.begin();\n Cell::const_iterator it_i = cell_i.begin();\n Cell::const_iterator end_o = cell_o.end();\n Cell::const_iterator end_i = cell_i.end();\n for(; it_o != end_o; ++it_o, ++it_i)\n {\n BOOST_CHECK(it_i != end_i);\n BOOST_CHECK_EQUAL(it_o->getMin(), it_i->getMin());\n BOOST_CHECK_EQUAL(it_o->getMax(), it_i->getMax());\n BOOST_CHECK_EQUAL(it_o->getTop(), it_i->getTop());\n BOOST_CHECK_EQUAL(it_o->getBottom(), it_i->getBottom());\n }\n BOOST_CHECK(it_i == end_i);\n }\n }\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2016 Steinwurf ApS\n\/\/ All Rights Reserved\n\/\/\n\/\/ Distributed under the \"BSD License\". See the accompanying LICENSE.rst\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"..\/helper_function.syhpp\"\n#include \n#include \n\n#include \n\nTEST(TestLittleEndianStream, create_stream)\n{\n const uint32_t size = 1024;\n std::vector buffer;\n buffer.resize(size);\n\n endian::endian_stream stream(buffer.data(), size);\n\n EXPECT_EQ(size, stream.size());\n EXPECT_EQ(0U, stream.position());\n}\n\nTEST(TestLittleEndianStream, create_stream_from_storage)\n{\n const uint32_t elements = 10; \/\/\/no. of elements\n const uint32_t size = elements * sizeof(uint32_t);\n\n std::vector buffer;\n buffer.resize(size);\n \/\/ Create endian stream directly from storage::storage\n endian::endian_stream\n stream(storage::storage(buffer));\n\n EXPECT_EQ(size, stream.size());\n EXPECT_EQ(0U, stream.position());\n\n for (uint32_t i = 0; i < elements; i++)\n {\n stream.write(i);\n }\n\n EXPECT_EQ(size, stream.size());\n EXPECT_EQ(size, stream.position());\n\n \/\/ Go back to the beginning of the stream\n stream.seek(0);\n uint32_t last_value = 0;\n for (uint32_t i = 0; i < elements; i++)\n {\n stream.read(last_value);\n EXPECT_EQ(i, last_value);\n }\n}\n\n\n\/\/\/ Write-read tests\n\nTEST(TestLittleEndianStream, read_write_u8)\n{\n write_read_test();\n}\n\nTEST(TestLittleEndianStream, read_write_u16)\n{\n write_read_test();\n}\n\nTEST(TestLittleEndianStream, read_write_u32)\n{\n write_read_test();\n}\n\nTEST(TestLittleEndianStream, read_write_u64)\n{\n write_read_test();\n}\n\n\/\/\/ Pseudorandom write-read tests\n\nTEST(TestLittleEndianStream, pseudorandom_read_write_u8)\n{\n random_write_read_test(true);\n}\n\nTEST(TestLittleEndianStream, pseudorandom_read_write_u16)\n{\n random_write_read_test(true);\n}\n\nTEST(TestLittleEndianStream, pseudorandom_read_write_u32)\n{\n random_write_read_test(true);\n}\n\nTEST(TestLittleEndianStream, pseudorandom_read_write_u64)\n{\n random_write_read_test(true);\n}\n\n\/\/\/ Random write read tests\n\nTEST(TestLittleEndianStream, random_read_write_u8)\n{\n random_write_read_test(false);\n}\n\nTEST(TestLittleEndianStream, random_read_write_u16)\n{\n random_write_read_test(false);\n}\n\nTEST(TestLittleEndianStream, random_read_write_u32)\n{\n random_write_read_test(false);\n}\n\nTEST(TestLittleEndianStream, random_read_write_u64)\n{\n random_write_read_test(false);\n}\n\n\/\/\/ Various read writes\n\nTEST(TestLittleEndianStream, pseudorandom_various_read_write)\n{\n various_write_read_test(true);\n}\n\nTEST(TestLittleEndianStream, random_various_read_write)\n{\n various_write_read_test(false);\n}\n\n\/\/\/ Test composite data types\n\nTEST(TestLittleEndianStream, read_write_string)\n{\n const uint32_t size = 1024;\n std::vector buffer;\n buffer.resize(size);\n\n endian::endian_stream stream(buffer.data(), size);\n\n std::string first(\"first first first\");\n std::string second(\"second second\");\n std::string third(\"third\");\n\n \/\/ Write the strings together with their lengths\n \/\/ The length is written as 16-bit integers\n stream.write((uint16_t)first.size());\n stream.write(storage::storage(first));\n stream.write((uint16_t)second.size());\n stream.write(storage::storage(second));\n stream.write((uint16_t)third.size());\n stream.write(storage::storage(third));\n\n \/\/ Temp variables\n std::string current;\n uint16_t len = 0;\n\n \/\/ Go back to the beginning of the stream\n stream.seek(0);\n\n \/\/ Read the strings together with their lengths\n stream.read(len);\n EXPECT_EQ(first.size(), len);\n \/\/ Resize the current string to accommodate 'len' bytes\n current.resize(len);\n stream.read(storage::storage(current));\n EXPECT_EQ(first, current);\n\n stream.read(len);\n EXPECT_EQ(second.size(), len);\n current.resize(len);\n stream.read(storage::storage(current));\n EXPECT_EQ(second, current);\n\n stream.read(len);\n EXPECT_EQ(third.size(), len);\n current.resize(len);\n stream.read(storage::storage(current));\n EXPECT_EQ(third, current);\n}\n\nTEST(TestLittleEndianStream, read_write_vector)\n{\n const uint32_t size = 1024;\n std::vector buffer;\n buffer.resize(size);\n endian::endian_stream stream(buffer.data(), size);\n\n std::vector first(100, 'a');\n std::vector second(200, 1234);\n\n \/\/ Write the vectors together with their lengths\n \/\/ The length is written as 16-bit integers\n stream.write((uint16_t)first.size());\n stream.write(storage::storage(first));\n \/\/ The size here refers to the number of integers\n \/\/ stored in the second vector\n stream.write((uint16_t)second.size());\n stream.write(storage::storage(second));\n\n \/\/ Temp variables\n std::vector first_out;\n std::vector second_out;\n uint16_t len = 0;\n\n \/\/ Go back to the beginning of the stream\n stream.seek(0);\n\n \/\/ Read the vector length\n stream.read(len);\n EXPECT_EQ(first.size(), len);\n \/\/ Resize the output vector to accommodate 'len' bytes\n first_out.resize(len);\n stream.read(storage::storage(first_out));\n EXPECT_TRUE(\n std::equal(first.begin(), first.end(), first_out.begin()));\n\n \/\/ Read the vector length\n stream.read(len);\n EXPECT_EQ(second.size(), len);\n \/\/ Resize the output vector to accommodate 'len' bytes\n second_out.resize(len);\n stream.read(storage::storage(second_out));\n EXPECT_TRUE(\n std::equal(second.begin(), second.end(), second_out.begin()));\n}\ncorrect spelling\/\/ Copyright (c) 2016 Steinwurf ApS\n\/\/ All Rights Reserved\n\/\/\n\/\/ Distributed under the \"BSD License\". See the accompanying LICENSE.rst\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"..\/helper_function.hpp\"\n#include \n#include \n\n#include \n\nTEST(TestLittleEndianStream, create_stream)\n{\n const uint32_t size = 1024;\n std::vector buffer;\n buffer.resize(size);\n\n endian::endian_stream stream(buffer.data(), size);\n\n EXPECT_EQ(size, stream.size());\n EXPECT_EQ(0U, stream.position());\n}\n\nTEST(TestLittleEndianStream, create_stream_from_storage)\n{\n const uint32_t elements = 10; \/\/\/no. of elements\n const uint32_t size = elements * sizeof(uint32_t);\n\n std::vector buffer;\n buffer.resize(size);\n \/\/ Create endian stream directly from storage::storage\n endian::endian_stream\n stream(storage::storage(buffer));\n\n EXPECT_EQ(size, stream.size());\n EXPECT_EQ(0U, stream.position());\n\n for (uint32_t i = 0; i < elements; i++)\n {\n stream.write(i);\n }\n\n EXPECT_EQ(size, stream.size());\n EXPECT_EQ(size, stream.position());\n\n \/\/ Go back to the beginning of the stream\n stream.seek(0);\n uint32_t last_value = 0;\n for (uint32_t i = 0; i < elements; i++)\n {\n stream.read(last_value);\n EXPECT_EQ(i, last_value);\n }\n}\n\n\n\/\/\/ Write-read tests\n\nTEST(TestLittleEndianStream, read_write_u8)\n{\n write_read_test();\n}\n\nTEST(TestLittleEndianStream, read_write_u16)\n{\n write_read_test();\n}\n\nTEST(TestLittleEndianStream, read_write_u32)\n{\n write_read_test();\n}\n\nTEST(TestLittleEndianStream, read_write_u64)\n{\n write_read_test();\n}\n\n\/\/\/ Pseudorandom write-read tests\n\nTEST(TestLittleEndianStream, pseudorandom_read_write_u8)\n{\n random_write_read_test(true);\n}\n\nTEST(TestLittleEndianStream, pseudorandom_read_write_u16)\n{\n random_write_read_test(true);\n}\n\nTEST(TestLittleEndianStream, pseudorandom_read_write_u32)\n{\n random_write_read_test(true);\n}\n\nTEST(TestLittleEndianStream, pseudorandom_read_write_u64)\n{\n random_write_read_test(true);\n}\n\n\/\/\/ Random write read tests\n\nTEST(TestLittleEndianStream, random_read_write_u8)\n{\n random_write_read_test(false);\n}\n\nTEST(TestLittleEndianStream, random_read_write_u16)\n{\n random_write_read_test(false);\n}\n\nTEST(TestLittleEndianStream, random_read_write_u32)\n{\n random_write_read_test(false);\n}\n\nTEST(TestLittleEndianStream, random_read_write_u64)\n{\n random_write_read_test(false);\n}\n\n\/\/\/ Various read writes\n\nTEST(TestLittleEndianStream, pseudorandom_various_read_write)\n{\n various_write_read_test(true);\n}\n\nTEST(TestLittleEndianStream, random_various_read_write)\n{\n various_write_read_test(false);\n}\n\n\/\/\/ Test composite data types\n\nTEST(TestLittleEndianStream, read_write_string)\n{\n const uint32_t size = 1024;\n std::vector buffer;\n buffer.resize(size);\n\n endian::endian_stream stream(buffer.data(), size);\n\n std::string first(\"first first first\");\n std::string second(\"second second\");\n std::string third(\"third\");\n\n \/\/ Write the strings together with their lengths\n \/\/ The length is written as 16-bit integers\n stream.write((uint16_t)first.size());\n stream.write(storage::storage(first));\n stream.write((uint16_t)second.size());\n stream.write(storage::storage(second));\n stream.write((uint16_t)third.size());\n stream.write(storage::storage(third));\n\n \/\/ Temp variables\n std::string current;\n uint16_t len = 0;\n\n \/\/ Go back to the beginning of the stream\n stream.seek(0);\n\n \/\/ Read the strings together with their lengths\n stream.read(len);\n EXPECT_EQ(first.size(), len);\n \/\/ Resize the current string to accommodate 'len' bytes\n current.resize(len);\n stream.read(storage::storage(current));\n EXPECT_EQ(first, current);\n\n stream.read(len);\n EXPECT_EQ(second.size(), len);\n current.resize(len);\n stream.read(storage::storage(current));\n EXPECT_EQ(second, current);\n\n stream.read(len);\n EXPECT_EQ(third.size(), len);\n current.resize(len);\n stream.read(storage::storage(current));\n EXPECT_EQ(third, current);\n}\n\nTEST(TestLittleEndianStream, read_write_vector)\n{\n const uint32_t size = 1024;\n std::vector buffer;\n buffer.resize(size);\n endian::endian_stream stream(buffer.data(), size);\n\n std::vector first(100, 'a');\n std::vector second(200, 1234);\n\n \/\/ Write the vectors together with their lengths\n \/\/ The length is written as 16-bit integers\n stream.write((uint16_t)first.size());\n stream.write(storage::storage(first));\n \/\/ The size here refers to the number of integers\n \/\/ stored in the second vector\n stream.write((uint16_t)second.size());\n stream.write(storage::storage(second));\n\n \/\/ Temp variables\n std::vector first_out;\n std::vector second_out;\n uint16_t len = 0;\n\n \/\/ Go back to the beginning of the stream\n stream.seek(0);\n\n \/\/ Read the vector length\n stream.read(len);\n EXPECT_EQ(first.size(), len);\n \/\/ Resize the output vector to accommodate 'len' bytes\n first_out.resize(len);\n stream.read(storage::storage(first_out));\n EXPECT_TRUE(\n std::equal(first.begin(), first.end(), first_out.begin()));\n\n \/\/ Read the vector length\n stream.read(len);\n EXPECT_EQ(second.size(), len);\n \/\/ Resize the output vector to accommodate 'len' bytes\n second_out.resize(len);\n stream.read(storage::storage(second_out));\n EXPECT_TRUE(\n std::equal(second.begin(), second.end(), second_out.begin()));\n}\n<|endoftext|>"} {"text":"\/**\n * Class for rpc call LogonUser (freerds to session manager)\n *\n * Copyright 2013 Thinstuff Technologies GmbH\n * Copyright 2013 DI (FH) Martin Haimberger \n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"CallInLogonUser.h\"\n#include \n#include \n\nusing freerds::icp::LogonUserRequest;\nusing freerds::icp::LogonUserResponse;\n\nnamespace freerds\n{\n\tnamespace sessionmanager\n\t{\n\t\tnamespace call\n\t\t{\n\n\t\tstatic wLog* logger_CallInLogonUser = WLog_Get(\"freerds.SessionManager.call.callinlogonuser\");\n\n\n\t\tCallInLogonUser::CallInLogonUser()\n\t\t\t: mConnectionId(0), mAuthStatus(0)\n\t\t{\n\n\t\t};\n\n\t\tCallInLogonUser::~CallInLogonUser()\n\t\t{\n\n\t\t};\n\n\t\tunsigned long CallInLogonUser::getCallType()\n\t\t{\n\t\t\treturn freerds::icp::LogonUser;\n\t\t};\n\n\t\tint CallInLogonUser::decodeRequest()\n\t\t{\n\t\t\t\/\/ decode protocol buffers\n\t\t\tLogonUserRequest req;\n\n\t\t\tif (!req.ParseFromString(mEncodedRequest))\n\t\t\t{\n\t\t\t\t\/\/ failed to parse\n\t\t\t\tmResult = 1;\/\/ will report error with answer\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tmUserName = req.username();\n\n\t\t\tmConnectionId = req.connectionid();\n\n\t\t\tmDomainName = req.domain();\n\n\t\t\tmPassword = req.password();\n\n\t\t\treturn 0;\n\t\t};\n\n\t\tint CallInLogonUser::encodeResponse()\n\t\t{\n\t\t\t\/\/ encode protocol buffers\n\t\t\tLogonUserResponse resp;\n\t\t\t\/\/ stup do stuff here\n\n\t\t\tresp.set_authstatus(mAuthStatus);\n\t\t\tresp.set_serviceendpoint(mPipeName);\n\n\t\t\tif (!resp.SerializeToString(&mEncodedResponse))\n\t\t\t{\n\t\t\t\t\/\/ failed to serialize\n\t\t\t\tmResult = 1;\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\treturn 0;\n\t\t};\n\n\t\tint CallInLogonUser::authenticateUser() {\n\n\t\t\tstd::string authModule;\n\t\t\tif (!APP_CONTEXT.getPropertyManager()->getPropertyString(0,\"auth.module\",authModule,mUserName)) {\n\t\t\t\tauthModule = \"PAM\";\n\t\t\t}\n\n\t\t\tmoduleNS::AuthModule* auth = moduleNS::AuthModule::loadFromName(authModule);\n\n\t\t\tif (!auth) {\n\t\t\t\tmResult = 1;\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tmAuthStatus = auth->logonUser(mUserName, mDomainName, mPassword);\n\n\t\t\tdelete auth;\n\t\t\treturn 0;\n\n\t\t}\n\n\t\tint CallInLogonUser::getUserSession() {\n\n\t\t\tsessionNS::Session* currentSession;\n\t\t\tsessionNS::Connection * currentConnection = APP_CONTEXT.getConnectionStore()->getOrCreateConnection(mConnectionId);\n\n\t\t\tif (currentConnection->getSessionId() != 0) {\n\t\t\t\tcurrentSession = APP_CONTEXT.getSessionStore()->getSession(currentConnection->getSessionId());\n\t\t\t\tif (currentSession == NULL) {\n\t\t\t\t\tmResult = 1;\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\t\/\/ we had an auth session before ...\n\t\t\t\tif (currentSession->isAuthSession()) {\n\t\t\t\t\tcurrentSession->stopModule();\n\t\t\t\t\tAPP_CONTEXT.getSessionStore()->removeSession(currentSession->getSessionID());\n\t\t\t\t\tcurrentConnection->setSessionId(0);\n\t\t\t\t} else {\n\t\t\t\t\tWLog_Print(logger_CallInLogonUser, WLOG_ERROR, \"Expected session to be an authsession with sessionId = %d\",currentSession->getSessionID());\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ check if there is an running session, which is disconnected\n\t\t\t\tcurrentSession = APP_CONTEXT.getSessionStore()->getFirstSessionUserName(mUserName, mDomainName);\n\t\t\t}\n\n\n\t\t\tif ((!currentSession) || (currentSession->getConnectState() != WTSDisconnected))\n\t\t\t{\n\t\t\t\t\/\/ create new Session for this request\n\t\t\t\tcurrentSession = APP_CONTEXT.getSessionStore()->createSession();\n\t\t\t\tcurrentSession->setUserName(mUserName);\n\t\t\t\tcurrentSession->setDomain(mDomainName);\n\n\t\t\t\tif (!currentSession->generateUserToken())\n\t\t\t\t{\n\t\t\t\t\tWLog_Print(logger_CallInLogonUser, WLOG_ERROR, \"generateUserToken failed for user %s with domain %s\",mUserName.c_str(),mDomainName.c_str());\n\t\t\t\t\tmResult = 1;\/\/ will report error with answer\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\n\t\t\t\tif (!currentSession->generateEnvBlockAndModify())\n\t\t\t\t{\n\t\t\t\t\tWLog_Print(logger_CallInLogonUser, WLOG_ERROR, \"generateEnvBlockAndModify failed for user %s with domain %s\",mUserName.c_str(),mDomainName.c_str());\n\t\t\t\t\tmResult = 1;\/\/ will report error with answer\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tstd::string moduleName;\n\n\t\t\t\tif (!APP_CONTEXT.getPropertyManager()->getPropertyString(currentSession->getSessionID(),\"module\",moduleName)) {\n\t\t\t\t\tmoduleName = \"X11\";\n\t\t\t\t}\n\t\t\t\tcurrentSession->setModuleName(moduleName);\n\t\t\t}\n\n\t\t\tif (currentSession->getConnectState() == WTSDown)\n\t\t\t{\n\t\t\t\tstd::string pipeName;\n\t\t\t\tif (!currentSession->startModule(pipeName))\n\t\t\t\t{\n\t\t\t\t\tWLog_Print(logger_CallInLogonUser, WLOG_ERROR, \"Module %s does not start properly for user %s in domain %s\",currentSession->getModuleName().c_str(),mUserName.c_str(),mDomainName.c_str());\n\t\t\t\t\tmResult = 1;\/\/ will report error with answer\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurrentConnection->setSessionId(currentSession->getSessionID());\n\t\t\tmPipeName = currentSession->getPipeName();\n\t\t\treturn 0;\n\t\t}\n\n\t\tint CallInLogonUser::getAuthSession() {\n\t\t\t\/\/ authentication failed, start up greater module\n\t\t\tsessionNS::Session* currentSession;\n\t\t\tsessionNS::Connection * currentConnection = APP_CONTEXT.getConnectionStore()->getOrCreateConnection(mConnectionId);\n\n\t\t\tif (currentConnection->getSessionId() != 0 ){\n\t\t\t\t\/\/ we had a session for authentication before ... use this session\n\t\t\t\tcurrentSession = APP_CONTEXT.getSessionStore()->getSession(currentConnection->getSessionId());\n\t\t\t\tif (currentSession == NULL) {\n\t\t\t\t\tmResult = 1;\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcurrentSession = APP_CONTEXT.getSessionStore()->createSession();\n\t\t\t\tstd::string greater;\n\n\t\t\t\tif (!APP_CONTEXT.getPropertyManager()->getPropertyString(0,\"auth.greater\",greater,mUserName)) {\n\t\t\t\t\tgreater = \"Qt\";\n\t\t\t\t}\n\t\t\t\tcurrentSession->setModuleName(greater);\n\t\t\t\tif (!currentSession->startModule(greater))\n\t\t\t\t{\n\t\t\t\t\tmResult = 1;\/\/ will report error with answer\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tcurrentConnection->setSessionId(currentSession->getSessionID());\n\t\t\t}\n\t\t\tcurrentSession->setAuthSession(true);\n\t\t\tmPipeName = currentSession->getPipeName();\n\t\t\treturn 0;\n\t\t}\n\n\t\tint CallInLogonUser::doStuff()\n\t\t{\n\n\t\t\tif (authenticateUser() != 0) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif (mAuthStatus != 0) {\n\t\t\t\tif (getAuthSession() != 0 ) {\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ user is authenticated\n\t\t\t\tif (getUserSession() != 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\n\t\t}\n\t}\n}\nLogonUser: Fixed problem with reconnects\/**\n * Class for rpc call LogonUser (freerds to session manager)\n *\n * Copyright 2013 Thinstuff Technologies GmbH\n * Copyright 2013 DI (FH) Martin Haimberger \n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"CallInLogonUser.h\"\n#include \n#include \n\nusing freerds::icp::LogonUserRequest;\nusing freerds::icp::LogonUserResponse;\n\nnamespace freerds\n{\n\tnamespace sessionmanager\n\t{\n\t\tnamespace call\n\t\t{\n\n\t\tstatic wLog* logger_CallInLogonUser = WLog_Get(\"freerds.SessionManager.call.callinlogonuser\");\n\n\n\t\tCallInLogonUser::CallInLogonUser()\n\t\t\t: mConnectionId(0), mAuthStatus(0)\n\t\t{\n\n\t\t};\n\n\t\tCallInLogonUser::~CallInLogonUser()\n\t\t{\n\n\t\t};\n\n\t\tunsigned long CallInLogonUser::getCallType()\n\t\t{\n\t\t\treturn freerds::icp::LogonUser;\n\t\t};\n\n\t\tint CallInLogonUser::decodeRequest()\n\t\t{\n\t\t\t\/\/ decode protocol buffers\n\t\t\tLogonUserRequest req;\n\n\t\t\tif (!req.ParseFromString(mEncodedRequest))\n\t\t\t{\n\t\t\t\t\/\/ failed to parse\n\t\t\t\tmResult = 1;\/\/ will report error with answer\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tmUserName = req.username();\n\n\t\t\tmConnectionId = req.connectionid();\n\n\t\t\tmDomainName = req.domain();\n\n\t\t\tmPassword = req.password();\n\n\t\t\treturn 0;\n\t\t};\n\n\t\tint CallInLogonUser::encodeResponse()\n\t\t{\n\t\t\t\/\/ encode protocol buffers\n\t\t\tLogonUserResponse resp;\n\t\t\t\/\/ stup do stuff here\n\n\t\t\tresp.set_authstatus(mAuthStatus);\n\t\t\tresp.set_serviceendpoint(mPipeName);\n\n\t\t\tif (!resp.SerializeToString(&mEncodedResponse))\n\t\t\t{\n\t\t\t\t\/\/ failed to serialize\n\t\t\t\tmResult = 1;\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\treturn 0;\n\t\t};\n\n\t\tint CallInLogonUser::authenticateUser() {\n\n\t\t\tstd::string authModule;\n\t\t\tif (!APP_CONTEXT.getPropertyManager()->getPropertyString(0,\"auth.module\",authModule,mUserName)) {\n\t\t\t\tauthModule = \"PAM\";\n\t\t\t}\n\n\t\t\tmoduleNS::AuthModule* auth = moduleNS::AuthModule::loadFromName(authModule);\n\n\t\t\tif (!auth) {\n\t\t\t\tmResult = 1;\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tmAuthStatus = auth->logonUser(mUserName, mDomainName, mPassword);\n\n\t\t\tdelete auth;\n\t\t\treturn 0;\n\n\t\t}\n\n\t\tint CallInLogonUser::getUserSession() {\n\n\t\t\tsessionNS::Session* currentSession;\n\t\t\tsessionNS::Connection * currentConnection = APP_CONTEXT.getConnectionStore()->getOrCreateConnection(mConnectionId);\n\n\t\t\tif (currentConnection->getSessionId() != 0) {\n\t\t\t\tcurrentSession = APP_CONTEXT.getSessionStore()->getSession(currentConnection->getSessionId());\n\t\t\t\tif (currentSession == NULL) {\n\t\t\t\t\tmResult = 1;\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\t\/\/ we had an auth session before ...\n\t\t\t\tif (currentSession->isAuthSession()) {\n\t\t\t\t\tcurrentSession->stopModule();\n\t\t\t\t\tAPP_CONTEXT.getSessionStore()->removeSession(currentSession->getSessionID());\n\t\t\t\t\tcurrentConnection->setSessionId(0);\n\t\t\t\t} else {\n\t\t\t\t\tWLog_Print(logger_CallInLogonUser, WLOG_ERROR, \"Expected session to be an authsession with sessionId = %d\",currentSession->getSessionID());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurrentSession = APP_CONTEXT.getSessionStore()->getFirstSessionUserName(mUserName, mDomainName);\n\n\t\t\tif ((!currentSession) || (currentSession->getConnectState() != WTSDisconnected))\n\t\t\t{\n\t\t\t\t\/\/ create new Session for this request\n\t\t\t\tcurrentSession = APP_CONTEXT.getSessionStore()->createSession();\n\t\t\t\tcurrentSession->setUserName(mUserName);\n\t\t\t\tcurrentSession->setDomain(mDomainName);\n\n\t\t\t\tif (!currentSession->generateUserToken())\n\t\t\t\t{\n\t\t\t\t\tWLog_Print(logger_CallInLogonUser, WLOG_ERROR, \"generateUserToken failed for user %s with domain %s\",mUserName.c_str(),mDomainName.c_str());\n\t\t\t\t\tmResult = 1;\/\/ will report error with answer\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\n\t\t\t\tif (!currentSession->generateEnvBlockAndModify())\n\t\t\t\t{\n\t\t\t\t\tWLog_Print(logger_CallInLogonUser, WLOG_ERROR, \"generateEnvBlockAndModify failed for user %s with domain %s\",mUserName.c_str(),mDomainName.c_str());\n\t\t\t\t\tmResult = 1;\/\/ will report error with answer\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tstd::string moduleName;\n\n\t\t\t\tif (!APP_CONTEXT.getPropertyManager()->getPropertyString(currentSession->getSessionID(),\"module\",moduleName)) {\n\t\t\t\t\tmoduleName = \"X11\";\n\t\t\t\t}\n\t\t\t\tcurrentSession->setModuleName(moduleName);\n\t\t\t}\n\n\t\t\tif (currentSession->getConnectState() == WTSDown)\n\t\t\t{\n\t\t\t\tstd::string pipeName;\n\t\t\t\tif (!currentSession->startModule(pipeName))\n\t\t\t\t{\n\t\t\t\t\tWLog_Print(logger_CallInLogonUser, WLOG_ERROR, \"Module %s does not start properly for user %s in domain %s\",currentSession->getModuleName().c_str(),mUserName.c_str(),mDomainName.c_str());\n\t\t\t\t\tmResult = 1;\/\/ will report error with answer\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurrentConnection->setSessionId(currentSession->getSessionID());\n\t\t\tmPipeName = currentSession->getPipeName();\n\t\t\treturn 0;\n\t\t}\n\n\t\tint CallInLogonUser::getAuthSession() {\n\t\t\t\/\/ authentication failed, start up greater module\n\t\t\tsessionNS::Session* currentSession;\n\t\t\tsessionNS::Connection * currentConnection = APP_CONTEXT.getConnectionStore()->getOrCreateConnection(mConnectionId);\n\n\t\t\tif (currentConnection->getSessionId() != 0 ){\n\t\t\t\t\/\/ we had a session for authentication before ... use this session\n\t\t\t\tcurrentSession = APP_CONTEXT.getSessionStore()->getSession(currentConnection->getSessionId());\n\t\t\t\tif (currentSession == NULL) {\n\t\t\t\t\tmResult = 1;\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcurrentSession = APP_CONTEXT.getSessionStore()->createSession();\n\t\t\t\tstd::string greater;\n\n\t\t\t\tif (!APP_CONTEXT.getPropertyManager()->getPropertyString(0,\"auth.greater\",greater,mUserName)) {\n\t\t\t\t\tgreater = \"Qt\";\n\t\t\t\t}\n\t\t\t\tcurrentSession->setModuleName(greater);\n\t\t\t\tif (!currentSession->startModule(greater))\n\t\t\t\t{\n\t\t\t\t\tmResult = 1;\/\/ will report error with answer\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tcurrentConnection->setSessionId(currentSession->getSessionID());\n\t\t\t}\n\t\t\tcurrentSession->setAuthSession(true);\n\t\t\tmPipeName = currentSession->getPipeName();\n\t\t\treturn 0;\n\t\t}\n\n\t\tint CallInLogonUser::doStuff()\n\t\t{\n\n\t\t\tif (authenticateUser() != 0) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif (mAuthStatus != 0) {\n\t\t\t\tif (getAuthSession() != 0 ) {\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ user is authenticated\n\t\t\t\tif (getUserSession() != 0) {\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nTEST(AgradRev, arena_matrix_matrix_test) {\n using Eigen::MatrixXd;\n using stan::math::arena_matrix;\n\n \/\/ construction\n arena_matrix a;\n arena_matrix a2;\n arena_matrix a3;\n arena_matrix b(3, 2);\n arena_matrix b2(4, 5);\n arena_matrix c(MatrixXd::Ones(3, 2));\n arena_matrix d(c);\n arena_matrix e(2 * d);\n\n \/\/ assignment\n a = c;\n a2 = std::move(d);\n a3 = 2 * a;\n b = d;\n b2 = std::move(c);\n e = e + a;\n a = MatrixXd::Ones(3, 2);\n\n EXPECT_MATRIX_EQ(a + a2 + a3 + b + b2 + e, MatrixXd::Ones(3, 2) * 9);\n stan::math::recover_memory();\n}\n\nTEST(AgradRev, arena_matrix_vector_test) {\n using Eigen::VectorXd;\n using stan::math::arena_matrix;\n\n \/\/ construction\n arena_matrix a;\n arena_matrix a2;\n arena_matrix a3;\n arena_matrix b(3);\n arena_matrix b2(4);\n arena_matrix c(VectorXd::Ones(3));\n arena_matrix d(c);\n arena_matrix e(2 * d);\n\n \/\/ assignment\n a = c;\n a2 = std::move(d);\n a3 = 2 * a;\n b = d;\n b2 = std::move(c);\n e = e + a;\n a = VectorXd::Ones(3);\n\n EXPECT_MATRIX_EQ(a + a2 + a3 + b + b2 + e, VectorXd::Ones(3) * 9);\n stan::math::recover_memory();\n}\n\nTEST(AgradRev, arena_matrix_row_vector_test) {\n using Eigen::RowVectorXd;\n using stan::math::arena_matrix;\n\n \/\/ construction\n arena_matrix a;\n arena_matrix a2;\n arena_matrix a3;\n arena_matrix b(3);\n arena_matrix b2(4);\n arena_matrix c(RowVectorXd::Ones(3));\n arena_matrix d(c);\n arena_matrix e(2 * d);\n\n \/\/ assignment\n a = c;\n a2 = std::move(d);\n a3 = 2 * a;\n b = d;\n b2 = std::move(c);\n e = e + a;\n a = RowVectorXd::Ones(3);\n\n EXPECT_MATRIX_EQ(a + a2 + a3 + b + b2 + e, RowVectorXd::Ones(3) * 9);\n stan::math::recover_memory();\n}\n\nTEST(AgradRev, arena_matrix_transpose_test) {\n using stan::math::arena_matrix;\n\n Eigen::VectorXd c = Eigen::VectorXd::Random(3);\n Eigen::RowVectorXd d = Eigen::RowVectorXd::Random(3);\n \n \/\/ The VectorXd\/RowVectorXd mixup here is on purpose to test a vector can initialize a row vector and visa versa\n arena_matrix a = d;\n arena_matrix b = c;\n EXPECT_MATRIX_EQ(a, d.transpose());\n EXPECT_MATRIX_EQ(b, c.transpose());\n\n EXPECT_NO_THROW(a = b);\n EXPECT_MATRIX_EQ(a, b.transpose());\n a = Eigen::VectorXd::Random(3);\n EXPECT_NO_THROW(b = a);\n EXPECT_MATRIX_EQ(a, b.transpose());\n \n stan::math::recover_memory();\n}\n[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags\/RELEASE_600\/final)#include \n#include \n#include \n\nTEST(AgradRev, arena_matrix_matrix_test) {\n using Eigen::MatrixXd;\n using stan::math::arena_matrix;\n\n \/\/ construction\n arena_matrix a;\n arena_matrix a2;\n arena_matrix a3;\n arena_matrix b(3, 2);\n arena_matrix b2(4, 5);\n arena_matrix c(MatrixXd::Ones(3, 2));\n arena_matrix d(c);\n arena_matrix e(2 * d);\n\n \/\/ assignment\n a = c;\n a2 = std::move(d);\n a3 = 2 * a;\n b = d;\n b2 = std::move(c);\n e = e + a;\n a = MatrixXd::Ones(3, 2);\n\n EXPECT_MATRIX_EQ(a + a2 + a3 + b + b2 + e, MatrixXd::Ones(3, 2) * 9);\n stan::math::recover_memory();\n}\n\nTEST(AgradRev, arena_matrix_vector_test) {\n using Eigen::VectorXd;\n using stan::math::arena_matrix;\n\n \/\/ construction\n arena_matrix a;\n arena_matrix a2;\n arena_matrix a3;\n arena_matrix b(3);\n arena_matrix b2(4);\n arena_matrix c(VectorXd::Ones(3));\n arena_matrix d(c);\n arena_matrix e(2 * d);\n\n \/\/ assignment\n a = c;\n a2 = std::move(d);\n a3 = 2 * a;\n b = d;\n b2 = std::move(c);\n e = e + a;\n a = VectorXd::Ones(3);\n\n EXPECT_MATRIX_EQ(a + a2 + a3 + b + b2 + e, VectorXd::Ones(3) * 9);\n stan::math::recover_memory();\n}\n\nTEST(AgradRev, arena_matrix_row_vector_test) {\n using Eigen::RowVectorXd;\n using stan::math::arena_matrix;\n\n \/\/ construction\n arena_matrix a;\n arena_matrix a2;\n arena_matrix a3;\n arena_matrix b(3);\n arena_matrix b2(4);\n arena_matrix c(RowVectorXd::Ones(3));\n arena_matrix d(c);\n arena_matrix e(2 * d);\n\n \/\/ assignment\n a = c;\n a2 = std::move(d);\n a3 = 2 * a;\n b = d;\n b2 = std::move(c);\n e = e + a;\n a = RowVectorXd::Ones(3);\n\n EXPECT_MATRIX_EQ(a + a2 + a3 + b + b2 + e, RowVectorXd::Ones(3) * 9);\n stan::math::recover_memory();\n}\n\nTEST(AgradRev, arena_matrix_transpose_test) {\n using stan::math::arena_matrix;\n\n Eigen::VectorXd c = Eigen::VectorXd::Random(3);\n Eigen::RowVectorXd d = Eigen::RowVectorXd::Random(3);\n\n \/\/ The VectorXd\/RowVectorXd mixup here is on purpose to test a vector can\n \/\/ initialize a row vector and visa versa\n arena_matrix a = d;\n arena_matrix b = c;\n EXPECT_MATRIX_EQ(a, d.transpose());\n EXPECT_MATRIX_EQ(b, c.transpose());\n\n EXPECT_NO_THROW(a = b);\n EXPECT_MATRIX_EQ(a, b.transpose());\n a = Eigen::VectorXd::Random(3);\n EXPECT_NO_THROW(b = a);\n EXPECT_MATRIX_EQ(a, b.transpose());\n\n stan::math::recover_memory();\n}\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2014-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \"test.hpp\"\n#include \"etl\/stop.hpp\"\n\n#include \"mmul_test.hpp\"\n\n\/\/ Matrix Matrix multiplication tests\n\nGEMM_TEST_CASE(\"gemm\/1\", \"[gemm]\") {\n etl::fast_matrix a = {1, 2, 3, 4, 5, 6};\n etl::fast_matrix b = {7, 8, 9, 10, 11, 12};\n etl::fast_matrix c;\n\n Impl::apply(a, b, c);\n\n REQUIRE_EQUALS(c(0, 0), 58);\n REQUIRE_EQUALS(c(0, 1), 64);\n REQUIRE_EQUALS(c(1, 0), 139);\n REQUIRE_EQUALS(c(1, 1), 154);\n}\n\nGEMM_TEST_CASE(\"gemm\/2\", \"[gemm]\") {\n etl::fast_matrix a = {1, 2, 3, 4, 5, 6, 7, 8, 9};\n etl::fast_matrix b = {7, 8, 9, 9, 10, 11, 11, 12, 13};\n etl::fast_matrix c;\n\n Impl::apply(a, b, c);\n\n REQUIRE_EQUALS(c(0, 0), 58);\n REQUIRE_EQUALS(c(0, 1), 64);\n REQUIRE_EQUALS(c(0, 2), 70);\n REQUIRE_EQUALS(c(1, 0), 139);\n REQUIRE_EQUALS(c(1, 1), 154);\n REQUIRE_EQUALS(c(1, 2), 169);\n REQUIRE_EQUALS(c(2, 0), 220);\n REQUIRE_EQUALS(c(2, 1), 244);\n REQUIRE_EQUALS(c(2, 2), 268);\n}\n\nGEMM_TEST_CASE(\"gemm\/3\", \"[gemm]\") {\n etl::dyn_matrix a(4, 4, etl::values(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16));\n etl::dyn_matrix b(4, 4, etl::values(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16));\n etl::dyn_matrix c(4, 4);\n\n Impl::apply(a, b, c);\n\n REQUIRE_EQUALS(c(0, 0), 90);\n REQUIRE_EQUALS(c(0, 1), 100);\n REQUIRE_EQUALS(c(1, 0), 202);\n REQUIRE_EQUALS(c(1, 1), 228);\n REQUIRE_EQUALS(c(2, 0), 314);\n REQUIRE_EQUALS(c(2, 1), 356);\n REQUIRE_EQUALS(c(3, 0), 426);\n REQUIRE_EQUALS(c(3, 1), 484);\n}\n\nGEMM_TEST_CASE(\"gemm\/4\", \"[gemm]\") {\n etl::dyn_matrix a(2, 2, etl::values(1, 2, 3, 4));\n etl::dyn_matrix b(2, 2, etl::values(1, 2, 3, 4));\n etl::dyn_matrix c(2, 2);\n\n Impl::apply(a, b, c);\n\n REQUIRE_EQUALS(c(0, 0), 7);\n REQUIRE_EQUALS(c(0, 1), 10);\n REQUIRE_EQUALS(c(1, 0), 15);\n REQUIRE_EQUALS(c(1, 1), 22);\n}\n\nGEMM_TEST_CASE(\"gemm\/5\", \"[gemm]\") {\n etl::dyn_matrix a(3, 3, std::initializer_list({1, 2, 3, 4, 5, 6, 7, 8, 9}));\n etl::dyn_matrix b(3, 3, std::initializer_list({7, 8, 9, 9, 10, 11, 11, 12, 13}));\n etl::dyn_matrix c(3, 3);\n\n Impl::apply(a, b, c);\n\n REQUIRE_EQUALS(c(0, 0), 58);\n REQUIRE_EQUALS(c(0, 1), 64);\n REQUIRE_EQUALS(c(0, 2), 70);\n REQUIRE_EQUALS(c(1, 0), 139);\n REQUIRE_EQUALS(c(1, 1), 154);\n REQUIRE_EQUALS(c(1, 2), 169);\n REQUIRE_EQUALS(c(2, 0), 220);\n REQUIRE_EQUALS(c(2, 1), 244);\n REQUIRE_EQUALS(c(2, 2), 268);\n}\n\nGEMM_TEST_CASE(\"gemm\/6\", \"[gemm]\") {\n etl::fast_matrix a(etl::magic(19));\n etl::fast_matrix b(etl::magic(19));\n etl::fast_matrix c;\n\n Impl::apply(a, b, c);\n\n REQUIRE_EQUALS(c(0, 0), 828343);\n REQUIRE_EQUALS(c(1, 1), 825360);\n REQUIRE_EQUALS(c(2, 2), 826253);\n REQUIRE_EQUALS(c(3, 3), 824524);\n REQUIRE_EQUALS(c(18, 18), 828343);\n}\nNew tests with reshape\/\/=======================================================================\n\/\/ Copyright (c) 2014-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \"test.hpp\"\n#include \"etl\/stop.hpp\"\n\n#include \"mmul_test.hpp\"\n\n\/\/ Matrix Matrix multiplication tests\n\nGEMM_TEST_CASE(\"gemm\/1\", \"[gemm]\") {\n etl::fast_matrix a = {1, 2, 3, 4, 5, 6};\n etl::fast_matrix b = {7, 8, 9, 10, 11, 12};\n etl::fast_matrix c;\n\n Impl::apply(a, b, c);\n\n REQUIRE_EQUALS(c(0, 0), 58);\n REQUIRE_EQUALS(c(0, 1), 64);\n REQUIRE_EQUALS(c(1, 0), 139);\n REQUIRE_EQUALS(c(1, 1), 154);\n}\n\nGEMM_TEST_CASE(\"gemm\/2\", \"[gemm]\") {\n etl::fast_matrix a = {1, 2, 3, 4, 5, 6, 7, 8, 9};\n etl::fast_matrix b = {7, 8, 9, 9, 10, 11, 11, 12, 13};\n etl::fast_matrix c;\n\n Impl::apply(a, b, c);\n\n REQUIRE_EQUALS(c(0, 0), 58);\n REQUIRE_EQUALS(c(0, 1), 64);\n REQUIRE_EQUALS(c(0, 2), 70);\n REQUIRE_EQUALS(c(1, 0), 139);\n REQUIRE_EQUALS(c(1, 1), 154);\n REQUIRE_EQUALS(c(1, 2), 169);\n REQUIRE_EQUALS(c(2, 0), 220);\n REQUIRE_EQUALS(c(2, 1), 244);\n REQUIRE_EQUALS(c(2, 2), 268);\n}\n\nGEMM_TEST_CASE(\"gemm\/3\", \"[gemm]\") {\n etl::dyn_matrix a(4, 4, etl::values(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16));\n etl::dyn_matrix b(4, 4, etl::values(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16));\n etl::dyn_matrix c(4, 4);\n\n Impl::apply(a, b, c);\n\n REQUIRE_EQUALS(c(0, 0), 90);\n REQUIRE_EQUALS(c(0, 1), 100);\n REQUIRE_EQUALS(c(1, 0), 202);\n REQUIRE_EQUALS(c(1, 1), 228);\n REQUIRE_EQUALS(c(2, 0), 314);\n REQUIRE_EQUALS(c(2, 1), 356);\n REQUIRE_EQUALS(c(3, 0), 426);\n REQUIRE_EQUALS(c(3, 1), 484);\n}\n\nGEMM_TEST_CASE(\"gemm\/4\", \"[gemm]\") {\n etl::dyn_matrix a(2, 2, etl::values(1, 2, 3, 4));\n etl::dyn_matrix b(2, 2, etl::values(1, 2, 3, 4));\n etl::dyn_matrix c(2, 2);\n\n Impl::apply(a, b, c);\n\n REQUIRE_EQUALS(c(0, 0), 7);\n REQUIRE_EQUALS(c(0, 1), 10);\n REQUIRE_EQUALS(c(1, 0), 15);\n REQUIRE_EQUALS(c(1, 1), 22);\n}\n\nGEMM_TEST_CASE(\"gemm\/5\", \"[gemm]\") {\n etl::dyn_matrix a(3, 3, std::initializer_list({1, 2, 3, 4, 5, 6, 7, 8, 9}));\n etl::dyn_matrix b(3, 3, std::initializer_list({7, 8, 9, 9, 10, 11, 11, 12, 13}));\n etl::dyn_matrix c(3, 3);\n\n Impl::apply(a, b, c);\n\n REQUIRE_EQUALS(c(0, 0), 58);\n REQUIRE_EQUALS(c(0, 1), 64);\n REQUIRE_EQUALS(c(0, 2), 70);\n REQUIRE_EQUALS(c(1, 0), 139);\n REQUIRE_EQUALS(c(1, 1), 154);\n REQUIRE_EQUALS(c(1, 2), 169);\n REQUIRE_EQUALS(c(2, 0), 220);\n REQUIRE_EQUALS(c(2, 1), 244);\n REQUIRE_EQUALS(c(2, 2), 268);\n}\n\nGEMM_TEST_CASE(\"gemm\/6\", \"[gemm]\") {\n etl::fast_matrix a(etl::magic(19));\n etl::fast_matrix b(etl::magic(19));\n etl::fast_matrix c;\n\n Impl::apply(a, b, c);\n\n REQUIRE_EQUALS(c(0, 0), 828343);\n REQUIRE_EQUALS(c(1, 1), 825360);\n REQUIRE_EQUALS(c(2, 2), 826253);\n REQUIRE_EQUALS(c(3, 3), 824524);\n REQUIRE_EQUALS(c(18, 18), 828343);\n}\n\nGEMM_TEST_CASE(\"gemm\/7\", \"[gemm]\") {\n etl::fast_matrix a(etl::magic(19));\n etl::fast_matrix b(etl::magic(19));\n etl::fast_matrix c;\n\n Impl::apply(reshape(a, 19, 19), reshape(b, 19, 19), c);\n\n REQUIRE_EQUALS(c(0, 0), 828343);\n REQUIRE_EQUALS(c(1, 1), 825360);\n REQUIRE_EQUALS(c(2, 2), 826253);\n REQUIRE_EQUALS(c(3, 3), 824524);\n REQUIRE_EQUALS(c(18, 18), 828343);\n}\n\nGEMM_TEST_CASE(\"gemm\/8\", \"[gemm]\") {\n etl::fast_matrix a(etl::magic(19));\n etl::fast_matrix b(etl::magic(19));\n etl::fast_matrix c;\n\n Impl::apply(etl::reshape<19, 19>(a), etl::reshape<19, 19>(b), c);\n\n REQUIRE_EQUALS(c(0, 0), 828343);\n REQUIRE_EQUALS(c(1, 1), 825360);\n REQUIRE_EQUALS(c(2, 2), 826253);\n REQUIRE_EQUALS(c(3, 3), 824524);\n REQUIRE_EQUALS(c(18, 18), 828343);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright GHI Electronics, LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n\n#define TARGET(a) CONCAT(DEVICE_TARGET, a)\n\nconst TinyCLR_Api_Provider* globalApiProvider;\n\nvoid OnSoftReset(const TinyCLR_Api_Provider* apiProvider) {\n#ifdef INCLUDE_ADC\n apiProvider->Add(apiProvider, TARGET(_Adc_GetApi)());\n apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::AdcProvider, TARGET(_Adc_GetApi)()->Name);\n#endif\n\n#ifdef INCLUDE_DAC\n apiProvider->Add(apiProvider, TARGET(_Dac_GetApi)());\n apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::DacProvider, TARGET(_Dac_GetApi)()->Name);\n#endif\n\n#ifdef INCLUDE_DISPLAY\n apiProvider->Add(apiProvider, TARGET(_Display_GetApi)());\n apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::DisplayProvider, TARGET(_Display_GetApi)()->Name);\n#endif\n\n#ifdef INCLUDE_GPIO\n apiProvider->Add(apiProvider, TARGET(_Gpio_GetApi)());\n apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::GpioProvider, TARGET(_Gpio_GetApi)()->Name);\n#endif\n\n#ifdef INCLUDE_I2C\n apiProvider->Add(apiProvider, TARGET(_I2c_GetApi)());\n#endif\n\n#ifdef INCLUDE_PWM\n apiProvider->Add(apiProvider, TARGET(_Pwm_GetApi)());\n#endif\n\n#ifdef INCLUDE_SPI\n apiProvider->Add(apiProvider, TARGET(_Spi_GetApi)());\n#endif\n\n#ifdef INCLUDE_UART\n apiProvider->Add(apiProvider, TARGET(_Uart_GetApi)());\n#endif\n\n#ifdef INCLUDE_USBCLIENT\n apiProvider->Add(apiProvider, TARGET(_UsbClient_GetApi)());\n#endif\n\n#ifdef INCLUDE_CAN\n apiProvider->Add(apiProvider, TARGET(_Can_GetApi)());\n apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::CanProvider, TARGET(_Can_GetApi)()->Name);\n#endif\n\n globalApiProvider = apiProvider;\n}\n\nint main() {\n TARGET(_Startup_Initialize)();\n\n\n uint8_t* heapStart;\n size_t heapLength;\n\n TARGET(_Startup_GetHeap)(heapStart, heapLength);\n TinyCLR_Startup_AddHeapRegion(heapStart, heapLength);\n\n\n const TinyCLR_Api_Info* debuggerApi;\n size_t debuggerIndex;\n\n TARGET(_Startup_GetDebugger)(debuggerApi, debuggerIndex);\n TinyCLR_Startup_SetDebugger(debuggerApi, debuggerIndex);\n\n\n TinyCLR_Startup_SetDeviceInformation(DEVICE_NAME, DEVICE_MANUFACTURER, DEVICE_VERSION);\n\n TinyCLR_Startup_SetRequiredProviders(TARGET(_Deployment_GetApi)(), TARGET(_Interrupt_GetApi)(), TARGET(_Power_GetApi)(), TARGET(_Time_GetApi)());\n\n\n auto runApp = true;\n\n TARGET(_Startup_GetRunApp)(runApp);\n TinyCLR_Startup_Start(&OnSoftReset, runApp);\n\n return 0;\n}\nwe will make another PR for globalApiProvider\/\/ Copyright GHI Electronics, LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n\n#define TARGET(a) CONCAT(DEVICE_TARGET, a)\n\nvoid OnSoftReset(const TinyCLR_Api_Provider* apiProvider) {\n#ifdef INCLUDE_ADC\n apiProvider->Add(apiProvider, TARGET(_Adc_GetApi)());\n apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::AdcProvider, TARGET(_Adc_GetApi)()->Name);\n#endif\n\n#ifdef INCLUDE_DAC\n apiProvider->Add(apiProvider, TARGET(_Dac_GetApi)());\n apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::DacProvider, TARGET(_Dac_GetApi)()->Name);\n#endif\n\n#ifdef INCLUDE_DISPLAY\n apiProvider->Add(apiProvider, TARGET(_Display_GetApi)());\n apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::DisplayProvider, TARGET(_Display_GetApi)()->Name);\n#endif\n\n#ifdef INCLUDE_GPIO\n apiProvider->Add(apiProvider, TARGET(_Gpio_GetApi)());\n apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::GpioProvider, TARGET(_Gpio_GetApi)()->Name);\n#endif\n\n#ifdef INCLUDE_I2C\n apiProvider->Add(apiProvider, TARGET(_I2c_GetApi)());\n#endif\n\n#ifdef INCLUDE_PWM\n apiProvider->Add(apiProvider, TARGET(_Pwm_GetApi)());\n#endif\n\n#ifdef INCLUDE_SPI\n apiProvider->Add(apiProvider, TARGET(_Spi_GetApi)());\n#endif\n\n#ifdef INCLUDE_UART\n apiProvider->Add(apiProvider, TARGET(_Uart_GetApi)());\n#endif\n\n#ifdef INCLUDE_USBCLIENT\n apiProvider->Add(apiProvider, TARGET(_UsbClient_GetApi)());\n#endif\n\n#ifdef INCLUDE_CAN\n apiProvider->Add(apiProvider, TARGET(_Can_GetApi)());\n apiProvider->SetDefaultSelector(apiProvider, TinyCLR_Api_Type::CanProvider, TARGET(_Can_GetApi)()->Name);\n#endif\n}\n\nint main() {\n TARGET(_Startup_Initialize)();\n\n\n uint8_t* heapStart;\n size_t heapLength;\n\n TARGET(_Startup_GetHeap)(heapStart, heapLength);\n TinyCLR_Startup_AddHeapRegion(heapStart, heapLength);\n\n\n const TinyCLR_Api_Info* debuggerApi;\n size_t debuggerIndex;\n\n TARGET(_Startup_GetDebugger)(debuggerApi, debuggerIndex);\n TinyCLR_Startup_SetDebugger(debuggerApi, debuggerIndex);\n\n\n TinyCLR_Startup_SetDeviceInformation(DEVICE_NAME, DEVICE_MANUFACTURER, DEVICE_VERSION);\n\n TinyCLR_Startup_SetRequiredProviders(TARGET(_Deployment_GetApi)(), TARGET(_Interrupt_GetApi)(), TARGET(_Power_GetApi)(), TARGET(_Time_GetApi)());\n\n\n auto runApp = true;\n\n TARGET(_Startup_GetRunApp)(runApp);\n TinyCLR_Startup_Start(&OnSoftReset, runApp);\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate \nclass NPriorityQueue{\npublic:\n \/\/types\n using PriorityList = std::array;\n\n \/\/functions\n NPriorityQueue& enqueue(ValType value, PriorityList priorities){\n elements_.push_front(value, priorities);\n for(size_t N=0; N ValType&& dequeue(){\n static_assert(N;\n using pElement = typename std::list::iterator;\n using PriorityListItr = typename std::deque::iterator;\n\n \/\/functions\n std::function compare_(size_t N) const{\n return [N](const pElement& a, const pElement& b){\n return a->second[N] < b->second[N];\n };\n }\n\n void insert_sorted_(size_t N, pElement ptr){\n auto list = priorities_[N];\n auto position = std::lower_bound(list.cbegin(), list.cend(), \n compare_(N));\n priorities_.at(N).insert(position, ptr);\n }\n\n PriorityListItr find_sorted_(size_t N, Element el) const{\n auto list = priorities_[N];\n auto range = std::equal_range(list.begin(), list.end(), \n compare_(N));\n for(auto itr=range.first; itr!=range.second; ++itr){\n if(**itr==el) return itr;\n }\n return list.end(); \/\/if not found\n }\n\n \/\/members\n std::list elements_;\n std::array, NQueues> priorities_;\n};\n\nTemporarily removed Comparator from NPriorityQueue#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate \nclass NPriorityQueue{\npublic:\n \/\/types\n using PriorityList = std::array;\n\n \/\/functions\n NPriorityQueue& enqueue(ValType value, PriorityList priorities){\n elements_.push_front(value, priorities);\n for(size_t N=0; N ValType&& dequeue(){\n static_assert(N;\n using pElement = typename std::list::iterator;\n using PriorityListItr = typename std::deque::iterator;\n\n \/\/functions\n std::function compare_(size_t N) const{\n return [N](const pElement& a, const pElement& b){\n return a->second[N] < b->second[N];\n };\n }\n\n void insert_sorted_(size_t N, pElement ptr){\n auto list = priorities_[N];\n auto position = std::lower_bound(list.cbegin(), list.cend(), \n compare_(N));\n priorities_.at(N).insert(position, ptr);\n }\n\n PriorityListItr find_sorted_(size_t N, Element el) const{\n auto list = priorities_[N];\n auto range = std::equal_range(list.begin(), list.end(), \n compare_(N));\n for(auto itr=range.first; itr!=range.second; ++itr){\n if(**itr==el) return itr;\n }\n return list.end(); \/\/if not found\n }\n\n \/\/members\n std::list elements_;\n std::array, NQueues> priorities_;\n};\n\n<|endoftext|>"} {"text":"#include \"MoveDummy.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyDummy.h\"\n#include \"ShapeCapsule.h\"\n\n#include \"Utils.h\"\n#include \"Engine.h\"\n#include \"Physics.h\"\n#include \"Game.h\"\n#include \"World.h\"\n\n#define MOVE_DUMMY_IFPS\t\t\t(1.0f\/100.0f)\t\t\n#define MOVE_DUMMY_CLAMP 89.9f\n#define MOVE_DUMMY_COLLISIONS\t\t1\n\nusing namespace MathLib;\n\nCMoveDummy::CMoveDummy()\t\t\/\/캯\n{\n\tm_pObject = new CObjectDummy();\t\t\/\/һʵ\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(0.5f, 1.0f);\n\n\tSetCollisionMask(1);\n\tClear();\n}\n\nCMoveDummy::~CMoveDummy()\n{\n\tm_pDummy->SetObject(NULL);\n\tSAFE_DELETE(m_pObject);\n\tSAFE_DELETE(m_pDummy);\n}\n\nvoid CMoveDummy::SetCollision(int c)\n{\n\tm_nCollision = c;\n}Signed-off-by: mrlitong #include \"MoveDummy.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyDummy.h\"\n#include \"ShapeCapsule.h\"\n\n#include \"Utils.h\"\n#include \"Engine.h\"\n#include \"Physics.h\"\n#include \"Game.h\"\n#include \"World.h\"\n\n#define MOVE_DUMMY_IFPS\t\t\t(1.0f\/100.0f)\t\t\n#define MOVE_DUMMY_CLAMP 89.9f\n#define MOVE_DUMMY_COLLISIONS\t\t1\n\nusing namespace MathLib;\n\nCMoveDummy::CMoveDummy()\t\t\/\/캯\n{\n\tm_pObject = new CObjectDummy();\t\t\/\/һʵ\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(0.5f, 1.0f);\n\n\tSetCollisionMask(1);\n\tClear();\n}\n\nCMoveDummy::~CMoveDummy()\n{\n\tm_pDummy->SetObject(NULL);\n\tSAFE_DELETE(m_pObject);\n\tSAFE_DELETE(m_pDummy);\n}\n\nvoid CMoveDummy::SetCollision(int c)\n{\n\tm_nCollision = c;\n}\n\nint CMoveDummy::GetCollision() const\n{\n\treturn m_nCollision;\n}\n\n<|endoftext|>"} {"text":"#include \"MoveDummy.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyDummy.h\"\n#include \"ShapeCapsule.h\"\n\n#include \"Utils.h\"\n#include \"Engine.h\"\n#include \"Physics.h\"\n#include \"Game.h\"\n#include \"World.h\"\n\n#define MOVE_DUMMY_IFPS\t\t\t(1.0f\/100.0f)\t\t\n#define MOVE_DUMMY_CLAMP 89.9f\n#define MOVE_DUMMY_COLLISIONS\t\t1\n\nusing namespace MathLib;\n\nCMoveDummy::CMoveDummy()\t\t\/\/캯\n{\n\tm_pObject = new CObjectDummy();\t\t\/\/һʵ\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(0.5f, 1.0f);\n\n\tSetCollisionMask(1);\n\tClear();\n}\n\nCMoveDummy::~CMoveDummy()\n{\n\tm_pDummy->SetObject(NULL);\n\tSAFE_DELETE(m_pObject);\n\tSAFE_DELETE(m_pDummy);\n}\n\nvoid CMoveDummy::SetCollision(int c)\n{\n\tm_nCollision = c;\n}\n\nint CMoveDummy::GetCollision() const\n{\n\treturn m_nCollision;\n}\n\nvoid CMoveDummy::SetCollisionMask(int m)\n{\n\tm_pShape->SetCollisionMask(m);\n}\n\nint CMoveDummy::GetCollisionMask() const\n{\n\treturn m_nCollisionMask;\n}\n\nvoid CMoveDummy::SetGround(int g)\n{\n\tm_nGround = g;\n}\n\nint CMoveDummy::GetGround() const\n{\n\treturn m_nGround;\n}\n\nvoid CMoveDummy::SetCeiling(int c)\n{\n\tm_nCeiling = c;\n}\n\nint CMoveDummy::GetCeiling() const\n{\n\treturn m_nCeiling;\n}\n\nvoid CMoveDummy::SetPosition(const MathLib::vec3& p)\n{\n\tm_vPosition = p;\n}\n\nconst MathLib::vec3& CMoveDummy::GetPosition() const\n{\n\treturn m_vPosition;\n}\n\nvoid CMoveDummy::SetCollisionRadius(float radius)\n{\n\tif (!Compare(m_pShape->GetRadius(), radius))\n\t{\n\t\tm_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());\n\t\tm_pShape->SetRadius(radius);\n\t}\n\n\tUpdate_Bounds();\n}\n\n\nfloat CMoveDummy::GetCollisionRadius() const\n{\n\treturn m_pShape->GetRadius();\n}\n\nvoid CMoveDummy::SetCollisionHeight(float height)\n{\n\tif (!Compare(m_pShape->GetHeight(), height))\n\t{\n\t\tm_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform());\n\t\tm_pShape->SetHeight(height);\n\t}\n\n\tUpdate_Bounds();\n}\nfloat CMoveDummy::GetCollisionHeight() const\n{\n\treturn m_pShape->GetHeight();\n}\n\nvoid CMoveDummy::SetUp(const MathLib::vec3& u)\n{\n\tm_vUp = u;\n}\n\nconst MathLib::vec3& CMoveDummy::GetUp() const\n{\n\treturn m_vUp;\n}\nvoid CMoveDummy::SetEnabled(int e)\n{\n\tm_nEnabled = e;\n}\n\nfloat CMoveDummy::GetCollisionHeight() const\n{\n\treturn m_pShape->GetHeight();\n}\nvoid CMoveDummy::SetUp(const MathLib::vec3& u)\n{\n\tm_vUp = u;\n}\n\nconst MathLib::vec3& CMoveDummy::GetUp() const\n{\n\treturn m_vUp;\n}\nvoid CMoveDummy::SetEnabled(int e)\n{\n\tm_nEnabled = e;\n}\n\nint CMoveDummy::GetEnabled() const\n{\n\treturn m_nEnabled;\n}\n\nvoid CMoveDummy::SetVelocity(const MathLib::vec3& v)\n{\n\tm_vVelocity = v;\n}\n\nconst MathLib::vec3& CMoveDummy::GetVelocity() const\n{\n\treturn m_vVelocity;\n}\n\nvoid CMoveDummy::SetMaxVelocity(float v)\n{\n\tm_fMaxVelocity = v;\n}\nfloat CMoveDummy::GetMaxVelocity() const\n{\n\treturn m_fMaxVelocity;\n}\n\nvoid CMoveDummy::SetAcceleration(float a)\n{\n\tm_fAcceleration = a;\n}\nfloat CMoveDummy::GetAcceleration() const\n{\n\treturn m_fAcceleration;\n}\nfloat CMoveDummy::GetMaxThrough() const\n{\n\treturn m_fMaxThrough;\n}\nvoid CMoveDummy::Clear()\n{\n\tSetVelocity(vec3_zero);\n\tSetMaxVelocity(2.5f);\n\tSetAcceleration(15.0f);\n\tSetCollision(1);\n\tSetCollisionMask(1);\n\tSetGround(0);\n\tSetCeiling(0);\n\tSetPosition(vec3_zero);\n\tSetUp(vec3(0.0f, 0.0f, 1.0f));\n\tSetEnabled(1);\n\tm_pDummy->SetEnabled(1);\n\tm_pObject->SetBody(NULL);\n\tm_pObject->SetBody(m_pDummy);\n\n\tm_pShape->SetBody(NULL);\n\tm_pShape->SetBody(m_pDummy);\n\tm_pShape->SetExclusionMask(2);\n\n\tm_pObject->SetWorldTransform(Get_Body_Transform());\n\n\tSetCollisionRadius(0.5f);\n\tSetCollisionHeight(1.0f);\n\n\n\tSetMaxThrough(0.4f);\n\n\tm_vecContacts.Clear();\n\n}\nint CMoveDummy::Update(float fIfps, const MathLib::vec3& vDirection)\n{\n\treturn Update(fIfps, vDirection, m_vPosition);\n}\nint CMoveDummy::Update(float fIfps, const MathLib::vec3& vDirection, const MathLib::vec3& pos)\n{\n\tSetPosition(pos);\n\n\tvec3 vOldPosition = m_vPosition;\n\n\tfloat fVVelocity = Dot(m_vVelocity, m_vUp);\n\tfloat fHVelocity = CMathCore::Sqrt(CMathCore::Abs(m_vVelocity.length2() - fVVelocity*fVVelocity));\n\n\tm_vVelocity = m_vUp * fVVelocity + vDirection * fHVelocity;\n\t\/\/ time\n\tfloat time = fIfps;\/\/ * g_Engine.pPhysics->GetScale();\n\n\t\/\/ penetration tolerance\n\tfloat penetration = g_Engine.pPhysics->GetPenetrationTolerance();\n\tfloat penetration_2 = penetration * 2.0f;\n\t\/\/ clear collision flags\n\tif (GetCollision())\n\t{\n\t\tm_nGround = 0;\n\t\tm_nCeiling = 0;\n\t}\n\n\t\/\/ frozen linear velocity\n\tfloat frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();\n\n\n\t\/\/ movement\n\tdo\n\t{\n\t\t\/\/ adaptive time step\n\t\tfloat ifps = Min(time, MOVE_DUMMY_IFPS);\n\t\ttime -= ifps;\n\t\t\/\/ integrate velocity\n\t\tm_vVelocity += vDirection * (m_fAcceleration * ifps);\n\t\tm_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;\n\n\t\tfVVelocity = Dot(m_vVelocity, m_vUp);\n\t\tfHVelocity = CMathCore::Sqrt(m_vVelocity.length2() - fVVelocity*fVVelocity);\n\n\t\tm_vVelocity = m_vUp * fVVelocity + vDirection * m_fMaxVelocity;\n\n\n\n\n\n\n\t}\n\twhile (time > EPSILON);\n\tif (GetCollision())\n\t{\n\t\tint nSurface = -1;\n\t}\n\n\tVec3 vStart = m_vPosition + vDirection * GetCollisionRadius() + Vec3(m_vUp * (m_pShape->GetHHeight() + m_pShape->GetRadius()));\n\tVec3 vEnd = vOldPosition + Vec3(m_vUp * (m_pShape->GetHHeight() + m_pShape->GetRadius()));\n\n\n\n\n\n\n}Judge variable P#include \"MoveDummy.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyDummy.h\"\n#include \"ShapeCapsule.h\"\n\n#include \"Utils.h\"\n#include \"Engine.h\"\n#include \"Physics.h\"\n#include \"Game.h\"\n#include \"World.h\"\n\n#define MOVE_DUMMY_IFPS\t\t\t(1.0f\/100.0f)\t\t\n#define MOVE_DUMMY_CLAMP 89.9f\n#define MOVE_DUMMY_COLLISIONS\t\t1\n\nusing namespace MathLib;\n\nCMoveDummy::CMoveDummy()\t\t\/\/캯\n{\n\tm_pObject = new CObjectDummy();\t\t\/\/һʵ\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(0.5f, 1.0f);\n\n\tSetCollisionMask(1);\n\tClear();\n}\n\nCMoveDummy::~CMoveDummy()\n{\n\tm_pDummy->SetObject(NULL);\n\tSAFE_DELETE(m_pObject);\n\tSAFE_DELETE(m_pDummy);\n}\n\nvoid CMoveDummy::SetCollision(int c)\n{\n\tm_nCollision = c;\n}\n\nint CMoveDummy::GetCollision() const\n{\n\treturn m_nCollision;\n}\n\nvoid CMoveDummy::SetCollisionMask(int m)\n{\n\tm_pShape->SetCollisionMask(m);\n}\n\nint CMoveDummy::GetCollisionMask() const\n{\n\treturn m_nCollisionMask;\n}\n\nvoid CMoveDummy::SetGround(int g)\n{\n\tm_nGround = g;\n}\n\nint CMoveDummy::GetGround() const\n{\n\treturn m_nGround;\n}\n\nvoid CMoveDummy::SetCeiling(int c)\n{\n\tm_nCeiling = c;\n}\n\nint CMoveDummy::GetCeiling() const\n{\n\treturn m_nCeiling;\n}\n\nvoid CMoveDummy::SetPosition(const MathLib::vec3& p)\n{\n\tm_vPosition = p;\n}\n\nconst MathLib::vec3& CMoveDummy::GetPosition() const\n{\n\treturn m_vPosition;\n}\n\nvoid CMoveDummy::SetCollisionRadius(float radius)\n{\n\tif (!Compare(m_pShape->GetRadius(), radius))\n\t{\n\t\tm_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());\n\t\tm_pShape->SetRadius(radius);\n\t}\n\n\tUpdate_Bounds();\n}\n\n\nfloat CMoveDummy::GetCollisionRadius() const\n{\n\treturn m_pShape->GetRadius();\n}\n\nvoid CMoveDummy::SetCollisionHeight(float height)\n{\n\tif (!Compare(m_pShape->GetHeight(), height))\n\t{\n\t\tm_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform());\n\t\tm_pShape->SetHeight(height);\n\t}\n\n\tUpdate_Bounds();\n}\nfloat CMoveDummy::GetCollisionHeight() const\n{\n\treturn m_pShape->GetHeight();\n}\n\nvoid CMoveDummy::SetUp(const MathLib::vec3& u)\n{\n\tm_vUp = u;\n}\n\nconst MathLib::vec3& CMoveDummy::GetUp() const\n{\n\treturn m_vUp;\n}\nvoid CMoveDummy::SetEnabled(int e)\n{\n\tm_nEnabled = e;\n}\n\nfloat CMoveDummy::GetCollisionHeight() const\n{\n\treturn m_pShape->GetHeight();\n}\nvoid CMoveDummy::SetUp(const MathLib::vec3& u)\n{\n\tm_vUp = u;\n}\n\nconst MathLib::vec3& CMoveDummy::GetUp() const\n{\n\treturn m_vUp;\n}\nvoid CMoveDummy::SetEnabled(int e)\n{\n\tm_nEnabled = e;\n}\n\nint CMoveDummy::GetEnabled() const\n{\n\treturn m_nEnabled;\n}\n\nvoid CMoveDummy::SetVelocity(const MathLib::vec3& v)\n{\n\tm_vVelocity = v;\n}\n\nconst MathLib::vec3& CMoveDummy::GetVelocity() const\n{\n\treturn m_vVelocity;\n}\n\nvoid CMoveDummy::SetMaxVelocity(float v)\n{\n\tm_fMaxVelocity = v;\n}\nfloat CMoveDummy::GetMaxVelocity() const\n{\n\treturn m_fMaxVelocity;\n}\n\nvoid CMoveDummy::SetAcceleration(float a)\n{\n\tm_fAcceleration = a;\n}\nfloat CMoveDummy::GetAcceleration() const\n{\n\treturn m_fAcceleration;\n}\nfloat CMoveDummy::GetMaxThrough() const\n{\n\treturn m_fMaxThrough;\n}\nvoid CMoveDummy::Clear()\n{\n\tSetVelocity(vec3_zero);\n\tSetMaxVelocity(2.5f);\n\tSetAcceleration(15.0f);\n\tSetCollision(1);\n\tSetCollisionMask(1);\n\tSetGround(0);\n\tSetCeiling(0);\n\tSetPosition(vec3_zero);\n\tSetUp(vec3(0.0f, 0.0f, 1.0f));\n\tSetEnabled(1);\n\tm_pDummy->SetEnabled(1);\n\tm_pObject->SetBody(NULL);\n\tm_pObject->SetBody(m_pDummy);\n\n\tm_pShape->SetBody(NULL);\n\tm_pShape->SetBody(m_pDummy);\n\tm_pShape->SetExclusionMask(2);\n\n\tm_pObject->SetWorldTransform(Get_Body_Transform());\n\n\tSetCollisionRadius(0.5f);\n\tSetCollisionHeight(1.0f);\n\n\n\tSetMaxThrough(0.4f);\n\n\tm_vecContacts.Clear();\n\n}\nint CMoveDummy::Update(float fIfps, const MathLib::vec3& vDirection)\n{\n\treturn Update(fIfps, vDirection, m_vPosition);\n}\nint CMoveDummy::Update(float fIfps, const MathLib::vec3& vDirection, const MathLib::vec3& pos)\n{\n\tSetPosition(pos);\n\n\tvec3 vOldPosition = m_vPosition;\n\n\tfloat fVVelocity = Dot(m_vVelocity, m_vUp);\n\tfloat fHVelocity = CMathCore::Sqrt(CMathCore::Abs(m_vVelocity.length2() - fVVelocity*fVVelocity));\n\n\tm_vVelocity = m_vUp * fVVelocity + vDirection * fHVelocity;\n\t\/\/ time\n\tfloat time = fIfps;\/\/ * g_Engine.pPhysics->GetScale();\n\n\t\/\/ penetration tolerance\n\tfloat penetration = g_Engine.pPhysics->GetPenetrationTolerance();\n\tfloat penetration_2 = penetration * 2.0f;\n\t\/\/ clear collision flags\n\tif (GetCollision())\n\t{\n\t\tm_nGround = 0;\n\t\tm_nCeiling = 0;\n\t}\n\n\t\/\/ frozen linear velocity\n\tfloat frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();\n\n\n\t\/\/ movement\n\tdo\n\t{\n\t\t\/\/ adaptive time step\n\t\tfloat ifps = Min(time, MOVE_DUMMY_IFPS);\n\t\ttime -= ifps;\n\t\t\/\/ integrate velocity\n\t\tm_vVelocity += vDirection * (m_fAcceleration * ifps);\n\t\tm_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;\n\n\t\tfVVelocity = Dot(m_vVelocity, m_vUp);\n\t\tfHVelocity = CMathCore::Sqrt(m_vVelocity.length2() - fVVelocity*fVVelocity);\n\n\t\tm_vVelocity = m_vUp * fVVelocity + vDirection * m_fMaxVelocity;\n\n\n\n\n\n\n\t}\n\twhile (time > EPSILON);\n\tif (GetCollision())\n\t{\n\t\tint nSurface = -1;\n\t}\n\n\tVec3 vStart = m_vPosition + vDirection * GetCollisionRadius() + Vec3(m_vUp * (m_pShape->GetHHeight() + m_pShape->GetRadius()));\n\tVec3 vEnd = vOldPosition + Vec3(m_vUp * (m_pShape->GetHHeight() + m_pShape->GetRadius()));\n\n\tCBRObject *p = g_Engine.pWorld->GetIntersection(vStart, vEnd, 2, nSurface);\n\n\tif (p != NULL)\n\t{\n\t\tm_vPosition = vOldPosition;\n\t}\n}\n\n\n\n\n}<|endoftext|>"} {"text":"#pragma once\n#include \"ilayer.hpp\"\n#include \n\nnamespace Convolutional::Layer {\n\nclass FullyConnectedNeuralNetwork : public ILayer {\npublic:\t\n\tusing ILayer::ILayer;\n\n\tclass Neuron;\n\n\tclass Connection {\n\tpublic:\n\t\tNeuron& from;\n\t\tNeuron& to;\n\n\t\tdouble weight = ((double) rand() \/ RAND_MAX * 2) - 1;\n\n\t\tConnection(Neuron& from, Neuron& to) : from(from), to(to) { };\n\t};\n\n\tclass Neuron {\n\tpublic:\n\t\tMatrix::element_t lastActionPotential = 0;\n\t\tstd::vector connections;\n\n\t\tNeuron(std::size_t nConnections = 0) { connections.reserve(nConnections); };\n\n\t\tauto AddConnection(Connection& connection) -> void {\n\t\t\tconnections.push_back(connection);\n\t\t}\n\t};\n\n\tclass BiasNeuron: public Neuron {\n\tpublic:\n\t\tBiasNeuron(std::size_t nOutputs = 0) : Neuron(nOutputs) { lastActionPotential = 1.0; };\n\t};\n\n\tstd::size_t nOutputs;\n\tstd::vector inputNeurons;\n\tstd::vector outputNeurons;\n\n\tFullyConnectedNeuralNetwork(std::size_t outputCount): nOutputs(outputCount), outputNeurons(outputCount, Neuron()) { };\n\tFullyConnectedNeuralNetwork(const FullyConnectedNeuralNetwork&) = default;\n\tFullyConnectedNeuralNetwork(FullyConnectedNeuralNetwork&&) = default;\n\n\tauto ProcessMultiMatrix(const MultiMatrix& multiMatrix) -> MultiMatrix override;\n\tauto GetReceptiveField(Matrix::Size size) const noexcept -> Matrix::Size override { return {1, 1}; }\n\tauto GetZeroPadding(Matrix::Size size) const noexcept -> Matrix::Size override { return {0, 0}; }\n\tauto GetStride(Matrix::Size size) const noexcept -> Matrix::Size override { return {1, 1}; }\n\n\tauto Clone() const noexcept -> std::unique_ptr override { return std::make_unique(*this); }\n};\n\n}\nCleanup ctors#pragma once\n#include \"ilayer.hpp\"\n#include \n\nnamespace Convolutional::Layer {\n\nclass FullyConnectedNeuralNetwork : public ILayer {\npublic:\t\n\tusing ILayer::ILayer;\n\n\tclass Neuron;\n\n\tclass Connection {\n\tpublic:\n\t\tNeuron& from;\n\t\tNeuron& to;\n\n\t\tdouble weight = ((double) rand() \/ RAND_MAX * 2) - 1;\n\n\t\tConnection(Neuron& from, Neuron& to) : from(from), to(to) { };\n\t};\n\n\tclass Neuron {\n\tpublic:\n\t\tMatrix::element_t lastActionPotential = 0;\n\t\tstd::vector connections;\n\n\t\tNeuron(std::size_t nConnections = 0) { connections.reserve(nConnections); };\n\n\t\tauto AddConnection(Connection& connection) -> void {\n\t\t\tconnections.push_back(connection);\n\t\t}\n\t};\n\n\tclass BiasNeuron: public Neuron {\n\tpublic:\n\t\tBiasNeuron() { lastActionPotential = 1.0; };\n\t};\n\n\tstd::size_t nOutputs;\n\tstd::vector inputNeurons;\n\tstd::vector outputNeurons;\n\n\tFullyConnectedNeuralNetwork(std::size_t outputCount): nOutputs(outputCount), outputNeurons(outputCount, Neuron()) { };\n\tFullyConnectedNeuralNetwork(const FullyConnectedNeuralNetwork&) = default;\n\tFullyConnectedNeuralNetwork(FullyConnectedNeuralNetwork&&) = default;\n\n\tauto ProcessMultiMatrix(const MultiMatrix& multiMatrix) -> MultiMatrix override;\n\tauto GetReceptiveField(Matrix::Size size) const noexcept -> Matrix::Size override { return {1, 1}; }\n\tauto GetZeroPadding(Matrix::Size size) const noexcept -> Matrix::Size override { return {0, 0}; }\n\tauto GetStride(Matrix::Size size) const noexcept -> Matrix::Size override { return {1, 1}; }\n\n\tauto Clone() const noexcept -> std::unique_ptr override { return std::make_unique(*this); }\n};\n\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"fixfmt\/base.hh\"\n#include \"fixfmt\/math.hh\"\n#include \"fixfmt\/text.hh\"\n\n\/\/------------------------------------------------------------------------------\n\nnamespace fixfmt {\n\nusing std::string;\n\nclass Number\n{\npublic:\n\n constexpr static char PAD_SPACE = ' ';\n constexpr static char PAD_ZERO = '0';\n\n constexpr static char SIGN_NONE = ' ';\n constexpr static char SIGN_NEGATIVE = '-';\n constexpr static char SIGN_ALWAYS = '+';\n\n constexpr static int PRECISION_NONE = -1;\n\n \/*\n * Fixed scaling for rendering numbers.\n *\n * @factor\n * The positive scale factor in which values are represented. A value is\n * divided by this value when formatted. Use 0 for no scaling.\n * @suffix\n * A suffix to append to formatted numbers to indicate scale.\n *\/\n struct Scale\n {\n double factor = 0;\n string suffix = \"\";\n\n bool enabled() const noexcept { return factor > 0; }\n };\n\n static Scale const SCALE_NONE;\n\n static Scale const SCALE_PERCENT;\n static Scale const SCALE_PER_MILLE;\n static Scale const SCALE_BASIS_POINTS;\n\n static Scale const SCALE_TERA;\n static Scale const SCALE_GIGA;\n static Scale const SCALE_MEGA;\n static Scale const SCALE_KILO;\n static Scale const SCALE_DECI;\n static Scale const SCALE_CENTI;\n static Scale const SCALE_MILLI;\n static Scale const SCALE_MICRO;\n static Scale const SCALE_NANO;\n static Scale const SCALE_PICO;\n static Scale const SCALE_FEMTO;\n\n static Scale const SCALE_GIBI;\n static Scale const SCALE_MEBI;\n static Scale const SCALE_KIBI;\n\n \/*\n * Arguments to a number formatter.\n *\/\n struct Args\n {\n int size = 8;\n int precision = PRECISION_NONE;\n char sign = SIGN_NEGATIVE;\n char pad = ' ';\n char point = '.';\n char bad = '#';\n string nan = \"NaN\";\n string inf = \"inf\";\n Scale scale = {};\n };\n \n Number() = default;\n Number(Number const&) = default;\n Number(Number&&) noexcept = default;\n Number& operator=(Number const&) = default;\n Number& operator=(Number&&) noexcept = default;\n ~Number() noexcept = default;\n\n Number(Args const& args) \n : args_(args) { check(args_); set_up(); }\n Number(Args&& args) \n : args_(std::move(args)) { check(args_); set_up(); }\n\n \/*\n * Convenience ctor for the most common options.\n *\/\n explicit \n Number(\n int const size,\n int const precision =PRECISION_NONE,\n char const sign =SIGN_NEGATIVE)\n : Number(Args{size, .precision=precision, .sign=sign})\n {\n }\n\n Args const& get_args() const noexcept\n { return args_; }\n void set_args(Args const& args) \n { check(args); args_ = args; set_up(); }\n void set_args(Args&& args) \n { check(args); args_ = std::move(args); set_up(); }\n\n size_t get_width() const noexcept { return width_; }\n string operator()(long val) const;\n string operator()(double val) const;\n\n \/\/ Make sure we use the integer implementation for integral types.\n string operator()(int val) const { return operator()((long) val); }\n string operator()(short val) const { return operator()((long) val); }\n string operator()(char val) const { return operator()((long) val); }\n string operator()(unsigned long val) const { return operator()((long) val); }\n string operator()(unsigned int val) const { return operator()((long) val); }\n string operator()(unsigned short val) const { return operator()((long) val); }\n string operator()(unsigned char val) const { return operator()((long) val); }\n\nprivate:\n\n static void check(Args const&);\n char get_sign_char(bool nonneg) const;\n string format_inf_nan(string const& str, int sign) const;\n void set_up();\n\n Args args_ = {};\n\n \/\/ Display width.\n size_t width_;\n \/\/ Maximum allocation size.\n size_t alloc_size_;\n\n string nan_;\n string pos_inf_;\n string neg_inf_;\n string bad_;\n\n};\n\n\n\/\/------------------------------------------------------------------------------\n\ninline void\nNumber::check(\n Args const& args)\n{\n \/\/ FIXME: Use Expect() or similar.\n assert(args.size >= 0);\n assert(args.precision == PRECISION_NONE || args.precision >= 0);\n assert(args.size > 0 || args.precision > 0);\n assert(args.pad == PAD_SPACE || args.pad == PAD_ZERO);\n assert(\n args.sign == SIGN_NONE \n || args.sign == SIGN_NEGATIVE \n || args.sign == SIGN_ALWAYS);\n assert(args.scale.factor >= 0);\n}\n\n\ninline char \nNumber::get_sign_char(\n bool const nonneg) \n const\n{\n assert(args_.sign != SIGN_NONE);\n return nonneg ? (args_.sign == SIGN_ALWAYS ? '+' : ' ') : '-';\n}\n\n\ninline string \nNumber::format_inf_nan(\n string const& str, \n int const sign) \n const\n{\n \/\/ Tack on the sign.\n bool const has_sign = args_.sign != SIGN_NONE;\n string result = \n ! has_sign || sign == 0 ? str\n : get_sign_char(sign > 0) + str;\n int const len = string_length(result);\n int const size = args_.size + has_sign;\n\n \/\/ Try to put it in the integer part.\n if (len <= (int) width_)\n result = pad(\n pad(result, size, \" \", PAD_POSITION_RIGHT_JUSTIFY), \n width_, \" \", PAD_POSITION_LEFT_JUSTIFY);\n else \n \/\/ Doesn't fit at all.\n string_truncate(result, width_);\n\n return result;\n}\n\n\ninline void\nNumber::set_up()\n{\n auto sz =\n args_.size\n + (args_.precision == PRECISION_NONE ? 0 : 1 + args_.precision)\n + (args_.sign == SIGN_NEGATIVE || args_.sign == SIGN_ALWAYS ? 1 : 0);\n width_ = sz + (args_.scale.enabled() ? string_length(args_.scale.suffix) : 0);\n alloc_size_ = sz + (args_.scale.enabled() ? args_.scale.suffix.size() : 0);\n\n nan_ = format_inf_nan(args_.nan, 0);\n pos_inf_ = format_inf_nan(args_.inf, 1);\n neg_inf_ = format_inf_nan(args_.inf, -1);\n bad_ = std::string(width_, args_.bad);\n}\n\n\n} \/\/ namespace fixfmt\n\nRemove noexcet from some defaulted methods.#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"fixfmt\/base.hh\"\n#include \"fixfmt\/math.hh\"\n#include \"fixfmt\/text.hh\"\n\n\/\/------------------------------------------------------------------------------\n\nnamespace fixfmt {\n\nusing std::string;\n\nclass Number\n{\npublic:\n\n constexpr static char PAD_SPACE = ' ';\n constexpr static char PAD_ZERO = '0';\n\n constexpr static char SIGN_NONE = ' ';\n constexpr static char SIGN_NEGATIVE = '-';\n constexpr static char SIGN_ALWAYS = '+';\n\n constexpr static int PRECISION_NONE = -1;\n\n \/*\n * Fixed scaling for rendering numbers.\n *\n * @factor\n * The positive scale factor in which values are represented. A value is\n * divided by this value when formatted. Use 0 for no scaling.\n * @suffix\n * A suffix to append to formatted numbers to indicate scale.\n *\/\n struct Scale\n {\n double factor = 0;\n string suffix = \"\";\n\n bool enabled() const noexcept { return factor > 0; }\n };\n\n static Scale const SCALE_NONE;\n\n static Scale const SCALE_PERCENT;\n static Scale const SCALE_PER_MILLE;\n static Scale const SCALE_BASIS_POINTS;\n\n static Scale const SCALE_TERA;\n static Scale const SCALE_GIGA;\n static Scale const SCALE_MEGA;\n static Scale const SCALE_KILO;\n static Scale const SCALE_DECI;\n static Scale const SCALE_CENTI;\n static Scale const SCALE_MILLI;\n static Scale const SCALE_MICRO;\n static Scale const SCALE_NANO;\n static Scale const SCALE_PICO;\n static Scale const SCALE_FEMTO;\n\n static Scale const SCALE_GIBI;\n static Scale const SCALE_MEBI;\n static Scale const SCALE_KIBI;\n\n \/*\n * Arguments to a number formatter.\n *\/\n struct Args\n {\n int size = 8;\n int precision = PRECISION_NONE;\n char sign = SIGN_NEGATIVE;\n char pad = ' ';\n char point = '.';\n char bad = '#';\n string nan = \"NaN\";\n string inf = \"inf\";\n Scale scale = {};\n };\n \n Number() = default;\n Number(Number const&) = default;\n Number(Number&&) = default;\n Number& operator=(Number const&) = default;\n Number& operator=(Number&&) = default;\n ~Number() noexcept = default;\n\n Number(Args const& args) \n : args_(args) { check(args_); set_up(); }\n Number(Args&& args) \n : args_(std::move(args)) { check(args_); set_up(); }\n\n \/*\n * Convenience ctor for the most common options.\n *\/\n explicit \n Number(\n int const size,\n int const precision =PRECISION_NONE,\n char const sign =SIGN_NEGATIVE)\n : Number(Args{size, .precision=precision, .sign=sign})\n {\n }\n\n Args const& get_args() const noexcept\n { return args_; }\n void set_args(Args const& args) \n { check(args); args_ = args; set_up(); }\n void set_args(Args&& args) \n { check(args); args_ = std::move(args); set_up(); }\n\n size_t get_width() const noexcept { return width_; }\n string operator()(long val) const;\n string operator()(double val) const;\n\n \/\/ Make sure we use the integer implementation for integral types.\n string operator()(int val) const { return operator()((long) val); }\n string operator()(short val) const { return operator()((long) val); }\n string operator()(char val) const { return operator()((long) val); }\n string operator()(unsigned long val) const { return operator()((long) val); }\n string operator()(unsigned int val) const { return operator()((long) val); }\n string operator()(unsigned short val) const { return operator()((long) val); }\n string operator()(unsigned char val) const { return operator()((long) val); }\n\nprivate:\n\n static void check(Args const&);\n char get_sign_char(bool nonneg) const;\n string format_inf_nan(string const& str, int sign) const;\n void set_up();\n\n Args args_ = {};\n\n \/\/ Display width.\n size_t width_;\n \/\/ Maximum allocation size.\n size_t alloc_size_;\n\n string nan_;\n string pos_inf_;\n string neg_inf_;\n string bad_;\n\n};\n\n\n\/\/------------------------------------------------------------------------------\n\ninline void\nNumber::check(\n Args const& args)\n{\n \/\/ FIXME: Use Expect() or similar.\n assert(args.size >= 0);\n assert(args.precision == PRECISION_NONE || args.precision >= 0);\n assert(args.size > 0 || args.precision > 0);\n assert(args.pad == PAD_SPACE || args.pad == PAD_ZERO);\n assert(\n args.sign == SIGN_NONE \n || args.sign == SIGN_NEGATIVE \n || args.sign == SIGN_ALWAYS);\n assert(args.scale.factor >= 0);\n}\n\n\ninline char \nNumber::get_sign_char(\n bool const nonneg) \n const\n{\n assert(args_.sign != SIGN_NONE);\n return nonneg ? (args_.sign == SIGN_ALWAYS ? '+' : ' ') : '-';\n}\n\n\ninline string \nNumber::format_inf_nan(\n string const& str, \n int const sign) \n const\n{\n \/\/ Tack on the sign.\n bool const has_sign = args_.sign != SIGN_NONE;\n string result = \n ! has_sign || sign == 0 ? str\n : get_sign_char(sign > 0) + str;\n int const len = string_length(result);\n int const size = args_.size + has_sign;\n\n \/\/ Try to put it in the integer part.\n if (len <= (int) width_)\n result = pad(\n pad(result, size, \" \", PAD_POSITION_RIGHT_JUSTIFY), \n width_, \" \", PAD_POSITION_LEFT_JUSTIFY);\n else \n \/\/ Doesn't fit at all.\n string_truncate(result, width_);\n\n return result;\n}\n\n\ninline void\nNumber::set_up()\n{\n auto sz =\n args_.size\n + (args_.precision == PRECISION_NONE ? 0 : 1 + args_.precision)\n + (args_.sign == SIGN_NEGATIVE || args_.sign == SIGN_ALWAYS ? 1 : 0);\n width_ = sz + (args_.scale.enabled() ? string_length(args_.scale.suffix) : 0);\n alloc_size_ = sz + (args_.scale.enabled() ? args_.scale.suffix.size() : 0);\n\n nan_ = format_inf_nan(args_.nan, 0);\n pos_inf_ = format_inf_nan(args_.inf, 1);\n neg_inf_ = format_inf_nan(args_.inf, -1);\n bad_ = std::string(width_, args_.bad);\n}\n\n\n} \/\/ namespace fixfmt\n\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2011, Willow Garage, Inc.\n * Copyright (c) 2012-, Open Perception, Inc.\n * \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing pcl::console::print_error;\nusing pcl::console::print_info;\nusing pcl::console::print_value;\n\n\/\/boost::mutex mutex_;\nboost::shared_ptr > grabber;\npcl::PointCloud::ConstPtr cloud_;\nstd::string out_folder;\nint counter;\n\nvoid\nprintHelp (int, char **argv)\n{\n print_error (\"Syntax is: %s \\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\"\\t-rgb_dir \\t \\t= directory path to RGB images to be read from\\n\");\n print_info (\"\\t-depth_dir \\t \\t= directory path to Depth images to be read from\\n\");\n print_info (\"\\t-out_dir \\t \\t= directory path to put the pcd files\\n\");\n \/\/print_info (\"\\t-fps frequency = frames per second\\n\");\n print_info (\"\\n\");\n}\n\nstruct EventHelper\n{\n void \n cloud_cb (const pcl::PointCloud::ConstPtr & cloud)\n {\n std::stringstream ss;\n ss << out_folder << \"\/\" << grabber->getPrevDepthFileName() << \".pcd\";\n pcl::io::savePCDFileASCII (ss.str(), *cloud);\n }\n};\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n counter = 0;\n out_folder.clear();\n\n if (argc > 1)\n {\n for (int i = 1; i < argc; i++)\n {\n if (std::string (argv[i]) == \"-h\")\n {\n printHelp (argc, argv);\n return (-1);\n }\n }\n }\n\n float frames_per_second = 0; \/\/ 0 means only if triggered!\n pcl::console::parse (argc, argv, \"-fps\", frames_per_second);\n if (frames_per_second < 0)\n frames_per_second = 0.0;\n\n float focal_length = 525.0;\n pcl::console::parse (argc, argv, \"-focal\", focal_length);\n\n std::string depth_path = \"\";\n pcl::console::parse_argument (argc, argv, \"-depth_dir\", depth_path);\n\n std::string rgb_path = \"\";\n pcl::console::parse_argument (argc, argv, \"-rgb_dir\", rgb_path);\n\n pcl::console::parse_argument (argc, argv, \"-out_dir\", out_folder);\n\n if (out_folder == \"\" || !boost::filesystem::exists (out_folder))\n {\n PCL_INFO(\"No correct directory was given with the -out_dir flag. Setting to current dir\\n\");\n out_folder = \".\/\";\n }\n else\n PCL_INFO(\"Using %s as output dir\", out_folder);\n\n if (rgb_path != \"\" && depth_path != \"\" && boost::filesystem::exists (rgb_path) && boost::filesystem::exists (depth_path))\n {\n grabber.reset (new pcl::ImageGrabber (depth_path, rgb_path, frames_per_second, false));\n }\n else\n {\n PCL_INFO(\"No directory was given with the -_dir flag.\");\n printHelp (argc, argv);\n return (-1);\n }\n grabber->setDepthImageUnits (float (1E-3));\n \/\/grabber->setFocalLength(focal_length); \/\/ FIXME\n\n EventHelper h;\n boost::function::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);\n boost::signals2::connection c1 = grabber->registerCallback (f);\n\n do\n {\n grabber->trigger();\n }\n while (!grabber->atLastFrame());\n grabber->trigger(); \/\/ Attempt to process the last frame\n grabber->stop ();\n}\n\/* ]--- *\/\nsmall error in print statement\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2011, Willow Garage, Inc.\n * Copyright (c) 2012-, Open Perception, Inc.\n * \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing pcl::console::print_error;\nusing pcl::console::print_info;\nusing pcl::console::print_value;\n\n\/\/boost::mutex mutex_;\nboost::shared_ptr > grabber;\npcl::PointCloud::ConstPtr cloud_;\nstd::string out_folder;\nint counter;\n\nvoid\nprintHelp (int, char **argv)\n{\n print_error (\"Syntax is: %s \\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\"\\t-rgb_dir \\t \\t= directory path to RGB images to be read from\\n\");\n print_info (\"\\t-depth_dir \\t \\t= directory path to Depth images to be read from\\n\");\n print_info (\"\\t-out_dir \\t \\t= directory path to put the pcd files\\n\");\n \/\/print_info (\"\\t-fps frequency = frames per second\\n\");\n print_info (\"\\n\");\n}\n\nstruct EventHelper\n{\n void \n cloud_cb (const pcl::PointCloud::ConstPtr & cloud)\n {\n std::stringstream ss;\n ss << out_folder << \"\/\" << grabber->getPrevDepthFileName() << \".pcd\";\n pcl::io::savePCDFileASCII (ss.str(), *cloud);\n }\n};\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n counter = 0;\n out_folder.clear();\n\n if (argc > 1)\n {\n for (int i = 1; i < argc; i++)\n {\n if (std::string (argv[i]) == \"-h\")\n {\n printHelp (argc, argv);\n return (-1);\n }\n }\n }\n\n float frames_per_second = 0; \/\/ 0 means only if triggered!\n pcl::console::parse (argc, argv, \"-fps\", frames_per_second);\n if (frames_per_second < 0)\n frames_per_second = 0.0;\n\n float focal_length = 525.0;\n pcl::console::parse (argc, argv, \"-focal\", focal_length);\n\n std::string depth_path = \"\";\n pcl::console::parse_argument (argc, argv, \"-depth_dir\", depth_path);\n\n std::string rgb_path = \"\";\n pcl::console::parse_argument (argc, argv, \"-rgb_dir\", rgb_path);\n\n pcl::console::parse_argument (argc, argv, \"-out_dir\", out_folder);\n\n if (out_folder == \"\" || !boost::filesystem::exists (out_folder))\n {\n PCL_INFO(\"No correct directory was given with the -out_dir flag. Setting to current dir\\n\");\n out_folder = \".\/\";\n }\n else\n PCL_INFO(\"Using %s as output dir\", out_folder.c_str());\n\n if (rgb_path != \"\" && depth_path != \"\" && boost::filesystem::exists (rgb_path) && boost::filesystem::exists (depth_path))\n {\n grabber.reset (new pcl::ImageGrabber (depth_path, rgb_path, frames_per_second, false));\n }\n else\n {\n PCL_INFO(\"No directory was given with the -_dir flag.\");\n printHelp (argc, argv);\n return (-1);\n }\n grabber->setDepthImageUnits (float (1E-3));\n \/\/grabber->setFocalLength(focal_length); \/\/ FIXME\n\n EventHelper h;\n boost::function::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);\n boost::signals2::connection c1 = grabber->registerCallback (f);\n\n do\n {\n grabber->trigger();\n }\n while (!grabber->atLastFrame());\n grabber->trigger(); \/\/ Attempt to process the last frame\n grabber->stop ();\n}\n\/* ]--- *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: arealink.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: kz $ $Date: 2004-10-04 20:03:30 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_AREALINK_HXX\n#define SC_AREALINK_HXX\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n#ifndef SC_REFRESHTIMER_HXX\n#include \"refreshtimer.hxx\"\n#endif\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n#ifndef _LNKBASE_HXX \/\/autogen\n#include \n#endif\n\nclass ScDocShell;\nclass SfxObjectShell;\n\nclass ScAreaLink : public ::sfx2::SvBaseLink, public ScRefreshTimer\n{\nprivate:\n ScDocShell* pDocShell; \/\/ Container\n String aFileName;\n String aFilterName;\n String aOptions;\n String aSourceArea;\n ScRange aDestArea;\n BOOL bAddUndo;\n BOOL bInCreate;\n BOOL bDoInsert; \/\/ wird fuer das erste Update auf FALSE gesetzt\n\n BOOL FindExtRange( ScRange& rRange, ScDocument* pSrcDoc, const String& rAreaName );\n\npublic:\n TYPEINFO();\n ScAreaLink( SfxObjectShell* pShell, const String& rFile,\n const String& rFilter, const String& rOpt,\n const String& rArea, const ScRange& rDest, ULONG nRefresh );\n virtual ~ScAreaLink();\n\n virtual void Closed();\n virtual void DataChanged( const String& rMimeType,\n const ::com::sun::star::uno::Any & rValue );\n\n virtual BOOL Edit(Window* pParent);\n\n BOOL Refresh( const String& rNewFile, const String& rNewFilter,\n const String& rNewArea, ULONG nNewRefresh );\n\n void SetInCreate(BOOL bSet) { bInCreate = bSet; }\n void SetDoInsert(BOOL bSet) { bDoInsert = bSet; }\n void SetDestArea(const ScRange& rNew);\n void SetSource(const String& rDoc, const String& rFlt, const String& rOpt,\n const String& rArea);\n\n BOOL IsEqual( const String& rFile, const String& rFilter, const String& rOpt,\n const String& rSource, const ScRange& rDest ) const;\n\n const String& GetFile() const { return aFileName; }\n const String& GetFilter() const { return aFilterName; }\n const String& GetOptions() const { return aOptions; }\n const String& GetSource() const { return aSourceArea; }\n const ScRange& GetDestArea() const { return aDestArea; }\n\n DECL_LINK( RefreshHdl, ScAreaLink* );\n\n};\n\n\n#endif\nINTEGRATION: CWS ooo19126 (1.7.326); FILE MERGED 2005\/09\/05 15:00:32 rt 1.7.326.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: arealink.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 17:22:38 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_AREALINK_HXX\n#define SC_AREALINK_HXX\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n#ifndef SC_REFRESHTIMER_HXX\n#include \"refreshtimer.hxx\"\n#endif\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n#ifndef _LNKBASE_HXX \/\/autogen\n#include \n#endif\n\nclass ScDocShell;\nclass SfxObjectShell;\n\nclass ScAreaLink : public ::sfx2::SvBaseLink, public ScRefreshTimer\n{\nprivate:\n ScDocShell* pDocShell; \/\/ Container\n String aFileName;\n String aFilterName;\n String aOptions;\n String aSourceArea;\n ScRange aDestArea;\n BOOL bAddUndo;\n BOOL bInCreate;\n BOOL bDoInsert; \/\/ wird fuer das erste Update auf FALSE gesetzt\n\n BOOL FindExtRange( ScRange& rRange, ScDocument* pSrcDoc, const String& rAreaName );\n\npublic:\n TYPEINFO();\n ScAreaLink( SfxObjectShell* pShell, const String& rFile,\n const String& rFilter, const String& rOpt,\n const String& rArea, const ScRange& rDest, ULONG nRefresh );\n virtual ~ScAreaLink();\n\n virtual void Closed();\n virtual void DataChanged( const String& rMimeType,\n const ::com::sun::star::uno::Any & rValue );\n\n virtual BOOL Edit(Window* pParent);\n\n BOOL Refresh( const String& rNewFile, const String& rNewFilter,\n const String& rNewArea, ULONG nNewRefresh );\n\n void SetInCreate(BOOL bSet) { bInCreate = bSet; }\n void SetDoInsert(BOOL bSet) { bDoInsert = bSet; }\n void SetDestArea(const ScRange& rNew);\n void SetSource(const String& rDoc, const String& rFlt, const String& rOpt,\n const String& rArea);\n\n BOOL IsEqual( const String& rFile, const String& rFilter, const String& rOpt,\n const String& rSource, const ScRange& rDest ) const;\n\n const String& GetFile() const { return aFileName; }\n const String& GetFilter() const { return aFilterName; }\n const String& GetOptions() const { return aOptions; }\n const String& GetSource() const { return aSourceArea; }\n const ScRange& GetDestArea() const { return aDestArea; }\n\n DECL_LINK( RefreshHdl, ScAreaLink* );\n\n};\n\n\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: BorderHandler.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2008-03-05 16:49:04 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef INCLUDED_BORDERHANDLER_HXX\n#define INCLUDED_BORDERHANDLER_HXX\n\n#ifndef INCLUDED_WRITERFILTERDLLAPI_H\n#include \n#endif\n#include \n#include \n#ifndef _COM_SUN_STAR_TABLE_BORDERLINE_HPP_\n#include \n#endif\n\nnamespace writerfilter {\nnamespace dmapper\n{\nclass PropertyMap;\nclass WRITERFILTER_DLLPRIVATE BorderHandler : public Properties\n{\npublic:\n \/\/todo: order is a guess\n enum BorderPosition\n {\n BORDER_TOP,\n BORDER_LEFT,\n BORDER_BOTTOM,\n BORDER_RIGHT,\n BORDER_HORIZONTAL,\n BORDER_VERTICAL,\n BORDER_COUNT\n };\n\nprivate:\n sal_Int8 m_nCurrentBorderPosition;\n \/\/values of the current border\n sal_Int32 m_nLineWidth;\n sal_Int32 m_nLineType;\n sal_Int32 m_nLineColor;\n sal_Int32 m_nLineDistance;\n bool m_bOOXML;\n\n ::com::sun::star::table::BorderLine m_aBorderLines[BORDER_COUNT];\n\npublic:\n BorderHandler( bool bOOXML );\n virtual ~BorderHandler();\n\n \/\/ Properties\n virtual void attribute(Id Name, Value & val);\n virtual void sprm(Sprm & sprm);\n\n ::boost::shared_ptr getProperties();\n ::com::sun::star::table::BorderLine getBorderLine();\n sal_Int32 getLineDistance() const { return m_nLineDistance;}\n};\ntypedef boost::shared_ptr< BorderHandler > BorderHandlerPtr;\n}}\n\n#endif \/\/\nINTEGRATION: CWS changefileheader (1.4.4); FILE MERGED 2008\/04\/01 13:02:26 thb 1.4.4.2: #i85898# Stripping all external header guards 2008\/03\/28 15:52:59 rt 1.4.4.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: BorderHandler.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef INCLUDED_BORDERHANDLER_HXX\n#define INCLUDED_BORDERHANDLER_HXX\n\n#include \n#include \n#include \n#include \n\nnamespace writerfilter {\nnamespace dmapper\n{\nclass PropertyMap;\nclass WRITERFILTER_DLLPRIVATE BorderHandler : public Properties\n{\npublic:\n \/\/todo: order is a guess\n enum BorderPosition\n {\n BORDER_TOP,\n BORDER_LEFT,\n BORDER_BOTTOM,\n BORDER_RIGHT,\n BORDER_HORIZONTAL,\n BORDER_VERTICAL,\n BORDER_COUNT\n };\n\nprivate:\n sal_Int8 m_nCurrentBorderPosition;\n \/\/values of the current border\n sal_Int32 m_nLineWidth;\n sal_Int32 m_nLineType;\n sal_Int32 m_nLineColor;\n sal_Int32 m_nLineDistance;\n bool m_bOOXML;\n\n ::com::sun::star::table::BorderLine m_aBorderLines[BORDER_COUNT];\n\npublic:\n BorderHandler( bool bOOXML );\n virtual ~BorderHandler();\n\n \/\/ Properties\n virtual void attribute(Id Name, Value & val);\n virtual void sprm(Sprm & sprm);\n\n ::boost::shared_ptr getProperties();\n ::com::sun::star::table::BorderLine getBorderLine();\n sal_Int32 getLineDistance() const { return m_nLineDistance;}\n};\ntypedef boost::shared_ptr< BorderHandler > BorderHandlerPtr;\n}}\n\n#endif \/\/\n<|endoftext|>"} {"text":"#include \"EEPROM_ACCESS_PARTICLE.h\"\r\n\r\n\/\/typedef struct reading {\r\n\/\/ String data;\t\t\t\t\t\/\/Assuming a maximum of 30 characters\r\n\/\/ struct reading * next;\r\n\/\/} reading_t;\r\n\r\n\/\/reading_t * reading_queue_head = NULL;\r\n\r\nvoid storeData(String msg)\r\n{\r\n\tint position;\r\n\tint offset;\r\n\t\r\n\tEEPROM.put(0, DATA_IN_EEP);\t\t\/\/Indicates that data is present in EEPROM\r\n\tEEPROM.get(5, position);\t\t\/\/The starting position of most recently stored data\r\n\t\r\n\tif(position == 0)\t\t\t\t\/\/Sets the start point of the new data to be stored\r\n\t{\r\n\t\toffset = position + 10;\r\n\t}else\r\n\t{\r\n\t\toffset = position + STRING_LEN;\r\n\t}\r\n\t\r\n\tEEPROM.put(offset, msg);\r\n\t\r\n\tEEPROM.put(5, offset);\t\t\t\/\/Updates the start position\r\n}\r\n\r\n\/*void addToQueue(String msg)\r\n{\r\n reading_t * new_reading = new reading_t;\r\n new_reading->next = reading_queue_head;\r\n reading_queue_head = new_reading;\/\/store the value\r\n new_reading->data = msg;\r\n}\r\n\r\nvoid processQueue()\r\n{\r\n\treading_t * current = reading_queue_head;\r\n \r\n while(reading_queue_head != NULL){\r\n current = reading_queue_head;\r\n boolean success = Particle.publish(\"colorinfo\", reading_queue_head->data);\t\/\/I assume that colorinfo is used everywhere\r\n\r\n if(success){\t\t\t\t\t\/\/message was sent\r\n reading_queue_head = reading_queue_head->next;\r\n free(current);\r\n if(reading_queue_head != NULL){\r\n delay(1000); \t\t\t\t\/\/wait a second before trying the next message Particle does not let us go faster than this\r\n }else{\t\t\t\t\t\t\/\/we are done here\r\n break;\r\n }\r\n }else{\t\t\t\t\t\t\t\/\/we failed to send try again later\r\n\t\tbreak;\r\n }\r\n }\r\n}*\/\r\n\r\nvoid processData()\r\n{\r\n\tint status;\r\n\tEEPROM.get(0,status);\r\n\t\r\n\tif(status == DATA_IN_EEP)\r\n\t{\r\n\t\tint position;\r\n\t\tString msg;\r\n\t\tboolean fail;\r\n\t\t\r\n\t\tEEPROM.get(5,position);\t\t\t\/\/Gets position of latestest data stored\t\r\n\t\t\r\n\t\twhile(position > 10)\r\n\t\t{\r\n\t\t\tEEPROM.get(position, msg);\t\/\/copies data\r\n\t\t\tboolean success = Particle.publish(\"colorinfo\", msg);\t\/\/publishes data onto the cloud\r\n\t\t\tif(!success)\t\t\t\t\/\/data to cloud transfer is unsuccesful\r\n\t\t\t{\r\n\t\t\t\tEEPROM.put(5, position);\t\/\/the position of latest data changes \r\n\t\t\t\tfail = TRUE;\r\n\t\t\t\tbreak;\t\t\t\t\r\n\t\t\t}\r\n\t\t\t\/\/addToQueue(msg);\t\t\t\/\/adds data onto Q.\r\n\t\t\tposition = position - STRING_LEN;\t\/\/position is shifted to next data stored\r\n\t\t}\r\n\t\t\r\n\t\tif(!fail)\r\n\t\t{\r\n\t\t\tposition = 0;\r\n\t\t\t\r\n\t\t\tEEPROM.clear();\t\t\t\t\t\/\/clears all data in EEPROM\r\n\t\t\tEEPROM.put(5, position);\t\t\/\/sets initial position\r\n\t\t\tEEPROM.put(0, NO_DATA_IN_EEP);\t\t\/\/indicates no data in EEPROM\r\n\t\t}\r\n\t\t\/\/processQueue();\t\t\t\t\t\/\/processes data in correct order of stroage\r\n\t}\r\n}\r\nUpdate EEPROM_ACCESS_PARTICLE.cpp#include \"EEPROM_ACCESS_PARTICLE.h\"\r\n\r\n\/\/typedef struct reading {\r\n\/\/ String data;\t\t\t\t\t\/\/Assuming a maximum of 30 characters\r\n\/\/ struct reading * next;\r\n\/\/} reading_t;\r\n\r\n\/\/reading_t * reading_queue_head = NULL;\r\n\r\nvoid storeData(String msg)\r\n{\r\n\tint position;\r\n\tint offset;\r\n\t\r\n\tEEPROM.put(0, DATA_IN_EEP);\t\t\/\/Indicates that data is present in EEPROM\r\n\tEEPROM.get(5, position);\t\t\/\/The starting position of most recently stored data\r\n\t\r\n\tif(position == 0)\t\t\t\t\/\/Sets the start point of the new data to be stored\r\n\t{\r\n\t\toffset = position + 10;\r\n\t}else\r\n\t{\r\n\t\toffset = position + STRING_LEN;\r\n\t}\r\n\t\r\n\tEEPROM.put(offset, msg);\r\n\t\r\n\tEEPROM.put(5, offset);\t\t\t\/\/Updates the start position\r\n}\r\n\r\n\/*void addToQueue(String msg)\r\n{\r\n reading_t * new_reading = new reading_t;\r\n new_reading->next = reading_queue_head;\r\n reading_queue_head = new_reading;\/\/store the value\r\n new_reading->data = msg;\r\n}\r\n\r\nvoid processQueue()\r\n{\r\n\treading_t * current = reading_queue_head;\r\n \r\n while(reading_queue_head != NULL){\r\n current = reading_queue_head;\r\n boolean success = Particle.publish(\"colorinfo\", reading_queue_head->data);\t\/\/I assume that colorinfo is used everywhere\r\n\r\n if(success){\t\t\t\t\t\/\/message was sent\r\n reading_queue_head = reading_queue_head->next;\r\n free(current);\r\n if(reading_queue_head != NULL){\r\n delay(1000); \t\t\t\t\/\/wait a second before trying the next message Particle does not let us go faster than this\r\n }else{\t\t\t\t\t\t\/\/we are done here\r\n break;\r\n }\r\n }else{\t\t\t\t\t\t\t\/\/we failed to send try again later\r\n\t\tbreak;\r\n }\r\n }\r\n}*\/\r\n\r\nvoid processData()\r\n{\r\n\tint status;\r\n\tEEPROM.get(0,status);\r\n\t\r\n\tif(status == DATA_IN_EEP)\r\n\t{\r\n\t\tint position;\r\n\t\tchar msg[32];\r\n\t\tboolean fail;\r\n\t\t\r\n\t\tEEPROM.get(5,position);\t\t\t\/\/Gets position of latestest data stored\t\r\n\t\t\r\n\t\twhile(position > 10)\r\n\t\t{\r\n\t\t\tEEPROM.get(position, msg);\t\/\/copies data\r\n\t\t\tboolean success = Particle.publish(\"colorinfo\", msg);\t\/\/publishes data onto the cloud\r\n\t\t\tif(!success)\t\t\t\t\/\/data to cloud transfer is unsuccesful\r\n\t\t\t{\r\n\t\t\t\tEEPROM.put(5, position);\t\/\/the position of latest data changes \r\n\t\t\t\tfail = TRUE;\r\n\t\t\t\tbreak;\t\t\t\t\r\n\t\t\t}\r\n\t\t\t\/\/addToQueue(msg);\t\t\t\/\/adds data onto Q.\r\n\t\t\tposition = position - STRING_LEN;\t\/\/position is shifted to next data stored\r\n\t\t}\r\n\t\t\r\n\t\tif(!fail)\r\n\t\t{\r\n\t\t\tposition = 0;\r\n\t\t\t\r\n\t\t\tEEPROM.clear();\t\t\t\t\t\/\/clears all data in EEPROM\r\n\t\t\tEEPROM.put(5, position);\t\t\/\/sets initial position\r\n\t\t\tEEPROM.put(0, NO_DATA_IN_EEP);\t\t\/\/indicates no data in EEPROM\r\n\t\t}\r\n\t\t\/\/processQueue();\t\t\t\t\t\/\/processes data in correct order of stroage\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Utility module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Nz\n{\n\tinline PixelFormatInfo::PixelFormatInfo() :\n\tcontent(PixelFormatContent_Undefined),\n\tbitsPerPixel(0)\n\t{\n\t}\n\n\tinline PixelFormatInfo::PixelFormatInfo(PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :\n\tcontent(formatContent),\n\tredType(subType),\n\tgreenType(subType),\n\tblueType(subType),\n\talphaType(subType),\n\tbitsPerPixel(bpp)\n\t{\n\t}\n\n\tinline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :\n\tcontent(formatContent),\n\tredType(subType),\n\tgreenType(subType),\n\tblueType(subType),\n\talphaType(subType),\n\tname(formatName),\n\tbitsPerPixel(bpp)\n\t{\n\t}\n\n\tinline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, Bitset<> rMask, Bitset<> gMask, Bitset<> bMask, Bitset<> aMask, PixelFormatSubType subType) :\n\tredMask(rMask),\n\tgreenMask(gMask),\n\tblueMask(bMask),\n\talphaMask(aMask),\n\tcontent(formatContent),\n\tredType(subType),\n\tgreenType(subType),\n\tblueType(subType),\n\talphaType(subType),\n\tname(formatName)\n\t{\n\t\tRecomputeBitsPerPixel();\n\t}\n\n\tinline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, PixelFormatSubType rType, Bitset<> rMask, PixelFormatSubType gType, Bitset<> gMask, PixelFormatSubType bType, Bitset<> bMask, PixelFormatSubType aType, Bitset<> aMask, UInt8 bpp) :\n\tredMask(rMask),\n\tgreenMask(gMask),\n\tblueMask(bMask),\n\talphaMask(aMask),\n\tcontent(formatContent),\n\tredType(rType),\n\tgreenType(gType),\n\tblueType(bType),\n\talphaType(aType),\n\tname(formatName)\n\t{\n\t\tif (bpp == 0)\n\t\t\tRecomputeBitsPerPixel();\n\t}\n\n\tinline void PixelFormatInfo::Clear()\n\t{\n\t\tbitsPerPixel = 0;\n\t\talphaMask.Clear();\n\t\tblueMask.Clear();\n\t\tgreenMask.Clear();\n\t\tredMask.Clear();\n\t\tname.Clear();\n\t}\n\n\tinline bool PixelFormatInfo::IsCompressed() const\n\t{\n\t\treturn redType == PixelFormatSubType_Compressed ||\n\t\t greenType == PixelFormatSubType_Compressed ||\n\t\t blueType == PixelFormatSubType_Compressed ||\n\t\t alphaType == PixelFormatSubType_Compressed;\n\t}\n\n\tinline bool PixelFormatInfo::IsValid() const\n\t{\n\t\treturn bitsPerPixel != 0;\n\t}\n\n\tinline void PixelFormatInfo::RecomputeBitsPerPixel()\n\t{\n\t\tBitset<> counter;\n\t\tcounter |= redMask;\n\t\tcounter |= greenMask;\n\t\tcounter |= blueMask;\n\t\tcounter |= alphaMask;\n\n\t\tbitsPerPixel = counter.Count();\n\t}\n\n\tinline bool PixelFormatInfo::Validate() const\n\t{\n\t\tif (!IsValid())\n\t\t\treturn false;\n\n\t\tif (content <= PixelFormatContent_Undefined || content > PixelFormatContent_Max)\n\t\t\treturn false;\n\n\t\tstd::array*, 4> masks = {&redMask, &greenMask, &blueMask, &alphaMask};\n\t\tstd::array types = {redType, greenType, blueType, alphaType};\n\n\t\tfor (unsigned int i = 0; i < 4; ++i)\n\t\t{\n\t\t\tunsigned int usedBits = masks[i]->Count();\n\t\t\tif (usedBits == 0)\n\t\t\t\tcontinue;\n\n\t\t\tif (usedBits > bitsPerPixel)\n\t\t\t\treturn false;\n\n\t\t\tswitch (types[i])\n\t\t\t{\n\t\t\t\tcase PixelFormatSubType_Half:\n\t\t\t\t\tif (usedBits != 16)\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PixelFormatSubType_Float:\n\t\t\t\t\tif (usedBits != 32)\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\n\n\tinline std::size_t PixelFormat::ComputeSize(PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth)\n\t{\n\t\tif (IsCompressed(format))\n\t\t{\n\t\t\tswitch (format)\n\t\t\t{\n\t\t\t\tcase PixelFormatType_DXT1:\n\t\t\t\tcase PixelFormatType_DXT3:\n\t\t\t\tcase PixelFormatType_DXT5:\n\t\t\t\t\treturn (((width + 3) \/ 4) * ((height + 3) \/ 4) * (format == PixelFormatType_DXT1) ? 8 : 16) * depth;\n\n\t\t\t\tdefault:\n\t\t\t\t\tNazaraError(\"Unsupported format\");\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\treturn width * height * depth * GetBytesPerPixel(format);\n\t}\n\n\tinline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* src, void* dst)\n\t{\n\t\tif (srcFormat == dstFormat)\n\t\t{\n\t\t\tstd::memcpy(dst, src, GetBytesPerPixel(srcFormat));\n\t\t\treturn true;\n\t\t}\n\n\t\t#if NAZARA_UTILITY_SAFE\n\t\tif (IsCompressed(srcFormat))\n\t\t{\n\t\t\tNazaraError(\"Cannot convert single pixel from compressed format\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (IsCompressed(dstFormat))\n\t\t{\n\t\t\tNazaraError(\"Cannot convert single pixel to compressed format\");\n\t\t\treturn false;\n\t\t}\n\t\t#endif\n\n\t\tConvertFunction func = s_convertFunctions[srcFormat][dstFormat];\n\t\tif (!func)\n\t\t{\n\t\t\tNazaraError(\"Pixel format conversion from \" + GetName(srcFormat) + \" to \" + GetName(dstFormat) + \" is not supported\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!func(reinterpret_cast(src), reinterpret_cast(src) + GetBytesPerPixel(srcFormat), reinterpret_cast(dst)))\n\t\t{\n\t\t\tNazaraError(\"Pixel format conversion from \" + GetName(srcFormat) + \" to \" + GetName(dstFormat) + \" failed\");\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tinline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* start, const void* end, void* dst)\n\t{\n\t\tif (srcFormat == dstFormat)\n\t\t{\n\t\t\tstd::memcpy(dst, start, reinterpret_cast(end)-reinterpret_cast(start));\n\t\t\treturn true;\n\t\t}\n\n\t\tConvertFunction func = s_convertFunctions[srcFormat][dstFormat];\n\t\tif (!func)\n\t\t{\n\t\t\tNazaraError(\"Pixel format conversion from \" + GetName(srcFormat) + \" to \" + GetName(dstFormat) + \" is not supported\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!func(reinterpret_cast(start), reinterpret_cast(end), reinterpret_cast(dst)))\n\t\t{\n\t\t\tNazaraError(\"Pixel format conversion from \" + GetName(srcFormat) + \" to \" + GetName(dstFormat) + \" failed\");\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tinline bool PixelFormat::Flip(PixelFlipping flipping, PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth, const void* src, void* dst)\n\t{\n\t\t#if NAZARA_UTILITY_SAFE\n\t\tif (!IsValid(format))\n\t\t{\n\t\t\tNazaraError(\"Invalid pixel format\");\n\t\t\treturn false;\n\t\t}\n\t\t#endif\n\n\t\tauto it = s_flipFunctions[flipping].find(format);\n\t\tif (it != s_flipFunctions[flipping].end())\n\t\t\tit->second(width, height, depth, reinterpret_cast(src), reinterpret_cast(dst));\n\t\telse\n\t\t{\n\t\t\t\/\/ Flipping générique\n\n\t\t\t#if NAZARA_UTILITY_SAFE\n\t\t\tif (IsCompressed(format))\n\t\t\t{\n\t\t\t\tNazaraError(\"No function to flip compressed format\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t#endif\n\n\t\t\tUInt8 bpp = GetBytesPerPixel(format);\n\t\t\tunsigned int lineStride = width*bpp;\n\t\t\tswitch (flipping)\n\t\t\t{\n\t\t\t\tcase PixelFlipping_Horizontally:\n\t\t\t\t{\n\t\t\t\t\tif (src == dst)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned int z = 0; z < depth; ++z)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tUInt8* ptr = reinterpret_cast(dst) + width*height*z;\n\t\t\t\t\t\t\tfor (unsigned int y = 0; y < height\/2; ++y)\n\t\t\t\t\t\t\t\tstd::swap_ranges(&ptr[y*lineStride], &ptr[(y+1)*lineStride-1], &ptr[(height-y-1)*lineStride]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned int z = 0; z < depth; ++z)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst UInt8* srcPtr = reinterpret_cast(src);\n\t\t\t\t\t\t\tUInt8* dstPtr = reinterpret_cast(dst) + (width-1)*height*depth*bpp;\n\t\t\t\t\t\t\tfor (unsigned int y = 0; y < height; ++y)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tstd::memcpy(dstPtr, srcPtr, lineStride);\n\n\t\t\t\t\t\t\t\tsrcPtr += lineStride;\n\t\t\t\t\t\t\t\tdstPtr -= lineStride;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase PixelFlipping_Vertically:\n\t\t\t\t{\n\t\t\t\t\tif (src == dst)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned int z = 0; z < depth; ++z)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tUInt8* ptr = reinterpret_cast(dst) + width*height*z;\n\t\t\t\t\t\t\tfor (unsigned int y = 0; y < height; ++y)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfor (unsigned int x = 0; x < width\/2; ++x)\n\t\t\t\t\t\t\t\t\tstd::swap_ranges(&ptr[x*bpp], &ptr[(x+1)*bpp], &ptr[(width-x)*bpp]);\n\n\t\t\t\t\t\t\t\tptr += lineStride;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned int z = 0; z < depth; ++z)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tUInt8* ptr = reinterpret_cast(dst) + width*height*z;\n\t\t\t\t\t\t\tfor (unsigned int y = 0; y < height; ++y)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfor (unsigned int x = 0; x < width; ++x)\n\t\t\t\t\t\t\t\t\tstd::memcpy(&ptr[x*bpp], &ptr[(width-x)*bpp], bpp);\n\n\t\t\t\t\t\t\t\tptr += lineStride;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tinline UInt8 PixelFormat::GetBitsPerPixel(PixelFormatType format)\n\t{\n\t\treturn s_pixelFormatInfos[format].bitsPerPixel;\n\t}\n\n\tinline UInt8 PixelFormat::GetBytesPerPixel(PixelFormatType format)\n\t{\n\t\treturn GetBitsPerPixel(format)\/8;\n\t}\n\n\tinline PixelFormatContent PixelFormat::GetContent(PixelFormatType format)\n\t{\n\t\treturn s_pixelFormatInfos[format].content;\n\t}\n\n\tinline const PixelFormatInfo& PixelFormat::GetInfo(PixelFormatType format)\n\t{\n\t\treturn s_pixelFormatInfos[format];\n\t}\n\n\tinline const String& PixelFormat::GetName(PixelFormatType format)\n\t{\n\t\treturn s_pixelFormatInfos[format].name;\n\t}\n\n\tinline bool PixelFormat::HasAlpha(PixelFormatType format)\n\t{\n\t\treturn s_pixelFormatInfos[format].alphaMask.TestAny();\n\t}\n\n\tinline bool PixelFormat::IsCompressed(PixelFormatType format)\n\t{\n\t\treturn s_pixelFormatInfos[format].IsCompressed();\n\t}\n\n\tinline bool PixelFormat::IsConversionSupported(PixelFormatType srcFormat, PixelFormatType dstFormat)\n\t{\n\t\tif (srcFormat == dstFormat)\n\t\t\treturn true;\n\n\t\treturn s_convertFunctions[srcFormat][dstFormat] != nullptr;\n\t}\n\n\tinline bool PixelFormat::IsValid(PixelFormatType format)\n\t{\n\t\treturn format != PixelFormatType_Undefined;\n\t}\n\n\tinline void PixelFormat::SetConvertFunction(PixelFormatType srcFormat, PixelFormatType dstFormat, ConvertFunction func)\n\t{\n\t\ts_convertFunctions[srcFormat][dstFormat] = func;\n\t}\n\n\tinline void PixelFormat::SetFlipFunction(PixelFlipping flipping, PixelFormatType format, FlipFunction func)\n\t{\n\t\ts_flipFunctions[flipping][format] = func;\n\t}\n}\n\n#include \nUtility\/PixelFormat: Fix ComputeSize for DXT formats\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Utility module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Nz\n{\n\tinline PixelFormatInfo::PixelFormatInfo() :\n\tcontent(PixelFormatContent_Undefined),\n\tbitsPerPixel(0)\n\t{\n\t}\n\n\tinline PixelFormatInfo::PixelFormatInfo(PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :\n\tcontent(formatContent),\n\tredType(subType),\n\tgreenType(subType),\n\tblueType(subType),\n\talphaType(subType),\n\tbitsPerPixel(bpp)\n\t{\n\t}\n\n\tinline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, UInt8 bpp, PixelFormatSubType subType) :\n\tcontent(formatContent),\n\tredType(subType),\n\tgreenType(subType),\n\tblueType(subType),\n\talphaType(subType),\n\tname(formatName),\n\tbitsPerPixel(bpp)\n\t{\n\t}\n\n\tinline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, Bitset<> rMask, Bitset<> gMask, Bitset<> bMask, Bitset<> aMask, PixelFormatSubType subType) :\n\tredMask(rMask),\n\tgreenMask(gMask),\n\tblueMask(bMask),\n\talphaMask(aMask),\n\tcontent(formatContent),\n\tredType(subType),\n\tgreenType(subType),\n\tblueType(subType),\n\talphaType(subType),\n\tname(formatName)\n\t{\n\t\tRecomputeBitsPerPixel();\n\t}\n\n\tinline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, PixelFormatSubType rType, Bitset<> rMask, PixelFormatSubType gType, Bitset<> gMask, PixelFormatSubType bType, Bitset<> bMask, PixelFormatSubType aType, Bitset<> aMask, UInt8 bpp) :\n\tredMask(rMask),\n\tgreenMask(gMask),\n\tblueMask(bMask),\n\talphaMask(aMask),\n\tcontent(formatContent),\n\tredType(rType),\n\tgreenType(gType),\n\tblueType(bType),\n\talphaType(aType),\n\tname(formatName)\n\t{\n\t\tif (bpp == 0)\n\t\t\tRecomputeBitsPerPixel();\n\t}\n\n\tinline void PixelFormatInfo::Clear()\n\t{\n\t\tbitsPerPixel = 0;\n\t\talphaMask.Clear();\n\t\tblueMask.Clear();\n\t\tgreenMask.Clear();\n\t\tredMask.Clear();\n\t\tname.Clear();\n\t}\n\n\tinline bool PixelFormatInfo::IsCompressed() const\n\t{\n\t\treturn redType == PixelFormatSubType_Compressed ||\n\t\t greenType == PixelFormatSubType_Compressed ||\n\t\t blueType == PixelFormatSubType_Compressed ||\n\t\t alphaType == PixelFormatSubType_Compressed;\n\t}\n\n\tinline bool PixelFormatInfo::IsValid() const\n\t{\n\t\treturn bitsPerPixel != 0;\n\t}\n\n\tinline void PixelFormatInfo::RecomputeBitsPerPixel()\n\t{\n\t\tBitset<> counter;\n\t\tcounter |= redMask;\n\t\tcounter |= greenMask;\n\t\tcounter |= blueMask;\n\t\tcounter |= alphaMask;\n\n\t\tbitsPerPixel = counter.Count();\n\t}\n\n\tinline bool PixelFormatInfo::Validate() const\n\t{\n\t\tif (!IsValid())\n\t\t\treturn false;\n\n\t\tif (content <= PixelFormatContent_Undefined || content > PixelFormatContent_Max)\n\t\t\treturn false;\n\n\t\tstd::array*, 4> masks = {&redMask, &greenMask, &blueMask, &alphaMask};\n\t\tstd::array types = {redType, greenType, blueType, alphaType};\n\n\t\tfor (unsigned int i = 0; i < 4; ++i)\n\t\t{\n\t\t\tunsigned int usedBits = masks[i]->Count();\n\t\t\tif (usedBits == 0)\n\t\t\t\tcontinue;\n\n\t\t\tif (usedBits > bitsPerPixel)\n\t\t\t\treturn false;\n\n\t\t\tswitch (types[i])\n\t\t\t{\n\t\t\t\tcase PixelFormatSubType_Half:\n\t\t\t\t\tif (usedBits != 16)\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PixelFormatSubType_Float:\n\t\t\t\t\tif (usedBits != 32)\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\n\n\tinline std::size_t PixelFormat::ComputeSize(PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth)\n\t{\n\t\tif (IsCompressed(format))\n\t\t{\n\t\t\tswitch (format)\n\t\t\t{\n\t\t\t\tcase PixelFormatType_DXT1:\n\t\t\t\tcase PixelFormatType_DXT3:\n\t\t\t\tcase PixelFormatType_DXT5:\n\t\t\t\t\treturn (((width + 3) \/ 4) * ((height + 3) \/ 4) * ((format == PixelFormatType_DXT1) ? 8 : 16)) * depth;\n\n\t\t\t\tdefault:\n\t\t\t\t\tNazaraError(\"Unsupported format\");\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\treturn width * height * depth * GetBytesPerPixel(format);\n\t}\n\n\tinline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* src, void* dst)\n\t{\n\t\tif (srcFormat == dstFormat)\n\t\t{\n\t\t\tstd::memcpy(dst, src, GetBytesPerPixel(srcFormat));\n\t\t\treturn true;\n\t\t}\n\n\t\t#if NAZARA_UTILITY_SAFE\n\t\tif (IsCompressed(srcFormat))\n\t\t{\n\t\t\tNazaraError(\"Cannot convert single pixel from compressed format\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (IsCompressed(dstFormat))\n\t\t{\n\t\t\tNazaraError(\"Cannot convert single pixel to compressed format\");\n\t\t\treturn false;\n\t\t}\n\t\t#endif\n\n\t\tConvertFunction func = s_convertFunctions[srcFormat][dstFormat];\n\t\tif (!func)\n\t\t{\n\t\t\tNazaraError(\"Pixel format conversion from \" + GetName(srcFormat) + \" to \" + GetName(dstFormat) + \" is not supported\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!func(reinterpret_cast(src), reinterpret_cast(src) + GetBytesPerPixel(srcFormat), reinterpret_cast(dst)))\n\t\t{\n\t\t\tNazaraError(\"Pixel format conversion from \" + GetName(srcFormat) + \" to \" + GetName(dstFormat) + \" failed\");\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tinline bool PixelFormat::Convert(PixelFormatType srcFormat, PixelFormatType dstFormat, const void* start, const void* end, void* dst)\n\t{\n\t\tif (srcFormat == dstFormat)\n\t\t{\n\t\t\tstd::memcpy(dst, start, reinterpret_cast(end)-reinterpret_cast(start));\n\t\t\treturn true;\n\t\t}\n\n\t\tConvertFunction func = s_convertFunctions[srcFormat][dstFormat];\n\t\tif (!func)\n\t\t{\n\t\t\tNazaraError(\"Pixel format conversion from \" + GetName(srcFormat) + \" to \" + GetName(dstFormat) + \" is not supported\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!func(reinterpret_cast(start), reinterpret_cast(end), reinterpret_cast(dst)))\n\t\t{\n\t\t\tNazaraError(\"Pixel format conversion from \" + GetName(srcFormat) + \" to \" + GetName(dstFormat) + \" failed\");\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tinline bool PixelFormat::Flip(PixelFlipping flipping, PixelFormatType format, unsigned int width, unsigned int height, unsigned int depth, const void* src, void* dst)\n\t{\n\t\t#if NAZARA_UTILITY_SAFE\n\t\tif (!IsValid(format))\n\t\t{\n\t\t\tNazaraError(\"Invalid pixel format\");\n\t\t\treturn false;\n\t\t}\n\t\t#endif\n\n\t\tauto it = s_flipFunctions[flipping].find(format);\n\t\tif (it != s_flipFunctions[flipping].end())\n\t\t\tit->second(width, height, depth, reinterpret_cast(src), reinterpret_cast(dst));\n\t\telse\n\t\t{\n\t\t\t\/\/ Flipping générique\n\n\t\t\t#if NAZARA_UTILITY_SAFE\n\t\t\tif (IsCompressed(format))\n\t\t\t{\n\t\t\t\tNazaraError(\"No function to flip compressed format\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t#endif\n\n\t\t\tUInt8 bpp = GetBytesPerPixel(format);\n\t\t\tunsigned int lineStride = width*bpp;\n\t\t\tswitch (flipping)\n\t\t\t{\n\t\t\t\tcase PixelFlipping_Horizontally:\n\t\t\t\t{\n\t\t\t\t\tif (src == dst)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned int z = 0; z < depth; ++z)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tUInt8* ptr = reinterpret_cast(dst) + width*height*z;\n\t\t\t\t\t\t\tfor (unsigned int y = 0; y < height\/2; ++y)\n\t\t\t\t\t\t\t\tstd::swap_ranges(&ptr[y*lineStride], &ptr[(y+1)*lineStride-1], &ptr[(height-y-1)*lineStride]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned int z = 0; z < depth; ++z)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst UInt8* srcPtr = reinterpret_cast(src);\n\t\t\t\t\t\t\tUInt8* dstPtr = reinterpret_cast(dst) + (width-1)*height*depth*bpp;\n\t\t\t\t\t\t\tfor (unsigned int y = 0; y < height; ++y)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tstd::memcpy(dstPtr, srcPtr, lineStride);\n\n\t\t\t\t\t\t\t\tsrcPtr += lineStride;\n\t\t\t\t\t\t\t\tdstPtr -= lineStride;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase PixelFlipping_Vertically:\n\t\t\t\t{\n\t\t\t\t\tif (src == dst)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned int z = 0; z < depth; ++z)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tUInt8* ptr = reinterpret_cast(dst) + width*height*z;\n\t\t\t\t\t\t\tfor (unsigned int y = 0; y < height; ++y)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfor (unsigned int x = 0; x < width\/2; ++x)\n\t\t\t\t\t\t\t\t\tstd::swap_ranges(&ptr[x*bpp], &ptr[(x+1)*bpp], &ptr[(width-x)*bpp]);\n\n\t\t\t\t\t\t\t\tptr += lineStride;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (unsigned int z = 0; z < depth; ++z)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tUInt8* ptr = reinterpret_cast(dst) + width*height*z;\n\t\t\t\t\t\t\tfor (unsigned int y = 0; y < height; ++y)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfor (unsigned int x = 0; x < width; ++x)\n\t\t\t\t\t\t\t\t\tstd::memcpy(&ptr[x*bpp], &ptr[(width-x)*bpp], bpp);\n\n\t\t\t\t\t\t\t\tptr += lineStride;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tinline UInt8 PixelFormat::GetBitsPerPixel(PixelFormatType format)\n\t{\n\t\treturn s_pixelFormatInfos[format].bitsPerPixel;\n\t}\n\n\tinline UInt8 PixelFormat::GetBytesPerPixel(PixelFormatType format)\n\t{\n\t\treturn GetBitsPerPixel(format)\/8;\n\t}\n\n\tinline PixelFormatContent PixelFormat::GetContent(PixelFormatType format)\n\t{\n\t\treturn s_pixelFormatInfos[format].content;\n\t}\n\n\tinline const PixelFormatInfo& PixelFormat::GetInfo(PixelFormatType format)\n\t{\n\t\treturn s_pixelFormatInfos[format];\n\t}\n\n\tinline const String& PixelFormat::GetName(PixelFormatType format)\n\t{\n\t\treturn s_pixelFormatInfos[format].name;\n\t}\n\n\tinline bool PixelFormat::HasAlpha(PixelFormatType format)\n\t{\n\t\treturn s_pixelFormatInfos[format].alphaMask.TestAny();\n\t}\n\n\tinline bool PixelFormat::IsCompressed(PixelFormatType format)\n\t{\n\t\treturn s_pixelFormatInfos[format].IsCompressed();\n\t}\n\n\tinline bool PixelFormat::IsConversionSupported(PixelFormatType srcFormat, PixelFormatType dstFormat)\n\t{\n\t\tif (srcFormat == dstFormat)\n\t\t\treturn true;\n\n\t\treturn s_convertFunctions[srcFormat][dstFormat] != nullptr;\n\t}\n\n\tinline bool PixelFormat::IsValid(PixelFormatType format)\n\t{\n\t\treturn format != PixelFormatType_Undefined;\n\t}\n\n\tinline void PixelFormat::SetConvertFunction(PixelFormatType srcFormat, PixelFormatType dstFormat, ConvertFunction func)\n\t{\n\t\ts_convertFunctions[srcFormat][dstFormat] = func;\n\t}\n\n\tinline void PixelFormat::SetFlipFunction(PixelFlipping flipping, PixelFormatType format, FlipFunction func)\n\t{\n\t\ts_flipFunctions[flipping][format] = func;\n\t}\n}\n\n#include \n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/nacl\/nacl_browsertest_util.h\"\n\nnamespace {\n\n\/\/ These tests fail on Linux ASAN bots: .\n#if defined(OS_LINUX) && defined(ADDRESS_SANITIZER)\n#define MAYBE_SimpleLoad DISABLED_SimpleLoad\n#define MAYBE_ExitStatus DISABLED_ExitStatus\n#define MAYBE_PPAPICore DISABLED_PPAPICore\n#define MAYBE_ProgressEvents DISABLED_ProgressEvents\n#define MAYBE_CrossOriginCORS DISABLED_CrossOriginCORS\n#define MAYBE_CrossOriginFail DISABLED_CrossOriginFail\n#else\n#define MAYBE_SimpleLoad SimpleLoad\n#define MAYBE_PPAPICore PPAPICore\n#define MAYBE_ProgressEvents ProgressEvents\n#define MAYBE_CrossOriginCORS CrossOriginCORS\n#define MAYBE_CrossOriginFail CrossOriginFail\n#if defined(OS_WIN) && !defined(NDEBUG)\n\/\/ http:\/\/crbug.com\/174380\n#define MAYBE_ExitStatus DISABLED_ExitStatus\n#else\n#define MAYBE_ExitStatus ExitStatus\n#endif\n#endif\n\nNACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_SimpleLoad, {\n RunLoadTest(FILE_PATH_LITERAL(\"nacl_load_test.html\"));\n})\n\nNACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_ExitStatus, {\n RunNaClIntegrationTest(FILE_PATH_LITERAL(\n \"pm_exit_status_test.html?trigger=exit0&expected_exit=0\"));\n RunNaClIntegrationTest(FILE_PATH_LITERAL(\n \"pm_exit_status_test.html?trigger=exit7&expected_exit=7\"));\n RunNaClIntegrationTest(FILE_PATH_LITERAL(\n \"pm_exit_status_test.html?trigger=exit254&expected_exit=254\"));\n RunNaClIntegrationTest(FILE_PATH_LITERAL(\n \"pm_exit_status_test.html?trigger=exitneg2&expected_exit=254\"));\n})\n\nNACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_PPAPICore, {\n RunNaClIntegrationTest(FILE_PATH_LITERAL(\"ppapi_ppb_core.html\"));\n})\n\nNACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_ProgressEvents, {\n RunNaClIntegrationTest(FILE_PATH_LITERAL(\"ppapi_progress_events.html\"));\n})\n\nIN_PROC_BROWSER_TEST_F(NaClBrowserTestStatic, MAYBE_CrossOriginCORS) {\n RunLoadTest(FILE_PATH_LITERAL(\"cross_origin\/cors.html\"));\n}\n\nIN_PROC_BROWSER_TEST_F(NaClBrowserTestStatic, MAYBE_CrossOriginFail) {\n RunLoadTest(FILE_PATH_LITERAL(\"cross_origin\/fail.html\"));\n}\n\n} \/\/ namespace anonymous\nNaCl: split exit status browser test into 3 smaller tests.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/nacl\/nacl_browsertest_util.h\"\n\nnamespace {\n\n\/\/ These tests fail on Linux ASAN bots: .\n#if defined(OS_LINUX) && defined(ADDRESS_SANITIZER)\n#define MAYBE_SimpleLoad DISABLED_SimpleLoad\n#define MAYBE_ExitStatus0 DISABLED_ExitStatus0\n#define MAYBE_ExitStatus254 DISABLED_ExitStatus254\n#define MAYBE_ExitStatusNeg2 DISABLED_ExitStatusNeg2\n#define MAYBE_PPAPICore DISABLED_PPAPICore\n#define MAYBE_ProgressEvents DISABLED_ProgressEvents\n#define MAYBE_CrossOriginCORS DISABLED_CrossOriginCORS\n#define MAYBE_CrossOriginFail DISABLED_CrossOriginFail\n#else\n#define MAYBE_SimpleLoad SimpleLoad\n#define MAYBE_ExitStatus0 ExitStatus0\n#define MAYBE_ExitStatus254 ExitStatus254\n#define MAYBE_ExitStatusNeg2 ExitStatusNeg2\n#define MAYBE_PPAPICore PPAPICore\n#define MAYBE_ProgressEvents ProgressEvents\n#define MAYBE_CrossOriginCORS CrossOriginCORS\n#define MAYBE_CrossOriginFail CrossOriginFail\n#endif\n\nNACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_SimpleLoad, {\n RunLoadTest(FILE_PATH_LITERAL(\"nacl_load_test.html\"));\n})\n\nNACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_ExitStatus0, {\n RunNaClIntegrationTest(FILE_PATH_LITERAL(\n \"pm_exit_status_test.html?trigger=exit0&expected_exit=0\"));\n})\n\nNACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_ExitStatus254, {\n RunNaClIntegrationTest(FILE_PATH_LITERAL(\n \"pm_exit_status_test.html?trigger=exit254&expected_exit=254\"));\n})\n\nNACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_ExitStatusNeg2, {\n RunNaClIntegrationTest(FILE_PATH_LITERAL(\n \"pm_exit_status_test.html?trigger=exitneg2&expected_exit=254\"));\n})\n\nNACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_PPAPICore, {\n RunNaClIntegrationTest(FILE_PATH_LITERAL(\"ppapi_ppb_core.html\"));\n})\n\nNACL_BROWSER_TEST_F(NaClBrowserTest, MAYBE_ProgressEvents, {\n RunNaClIntegrationTest(FILE_PATH_LITERAL(\"ppapi_progress_events.html\"));\n})\n\nIN_PROC_BROWSER_TEST_F(NaClBrowserTestStatic, MAYBE_CrossOriginCORS) {\n RunLoadTest(FILE_PATH_LITERAL(\"cross_origin\/cors.html\"));\n}\n\nIN_PROC_BROWSER_TEST_F(NaClBrowserTestStatic, MAYBE_CrossOriginFail) {\n RunLoadTest(FILE_PATH_LITERAL(\"cross_origin\/fail.html\"));\n}\n\n} \/\/ namespace anonymous\n<|endoftext|>"} {"text":"\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {BrainProtonDensitySlice.png}\n\/\/ ARGUMENTS: LaplacianRecursiveGaussianImageFilterOutput3.mha 3\n\/\/ OUTPUTS: {LaplacianRecursiveGaussianImageFilterOutput3.png}\n\/\/ Software Guide : EndCommandLineArgs\n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {BrainProtonDensitySlice.png}\n\/\/ ARGUMENTS: LaplacianRecursiveGaussianImageFilterOutput5.mha 5\n\/\/ OUTPUTS: {LaplacianRecursiveGaussianImageFilterOutput5.png}\n\/\/ Software Guide : EndCommandLineArgs\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example illustrates how to use the\n\/\/ \\doxygen{RecursiveGaussianImageFilter} for computing the Laplacian of a 2D\n\/\/ image.\n\/\/\n\/\/ \\index{itk::RecursiveGaussianImageFilter}\n\/\/\n\/\/ Software Guide : EndLatex\n\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkAddImageFilter.h\"\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The first step required to use this filter is to include its header file.\n\/\/\n\/\/ \\index{itk::RecursiveGaussianImageFilter!header}\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkRecursiveGaussianImageFilter.h\"\n\/\/ Software Guide : EndCodeSnippet\n#include \"itkRescaleIntensityImageFilter.h\"\n\n\nint main( int argc, char * argv[] )\n{\n if( argc < 4 )\n {\n std::cerr << \"Usage: \" << std::endl;\n std::cerr << argv[0] << \" inputImageFile outputImageFile sigma [RescaledOutputImageFile] \" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Types should be selected on the desired input and output pixel types.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef float InputPixelType;\n typedef float OutputPixelType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The input and output image types are instantiated using the pixel types.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::Image< InputPixelType, 2 > InputImageType;\n typedef itk::Image< OutputPixelType, 2 > OutputImageType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n typedef itk::ImageFileReader< InputImageType > ReaderType;\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The filter type is now instantiated using both the input image and the\n \/\/ output image types.\n \/\/\n \/\/ \\index{itk::RecursiveGaussianImageFilter!Instantiation}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::RecursiveGaussianImageFilter<\n InputImageType, OutputImageType > FilterType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( argv[1] );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ This filter applies the approximation of the convolution along a single\n \/\/ dimension. It is therefore necessary to concatenate several of these filters\n \/\/ to produce smoothing in all directions. In this example, we create a pair\n \/\/ of filters since we are processing a $2D$ image. The filters are\n \/\/ created by invoking the \\code{New()} method and assigning the result to\n \/\/ a \\doxygen{SmartPointer}.\n \/\/\n \/\/ We need two filters for computing the X component of the Laplacian and\n \/\/ two other filters for computing the Y component.\n \/\/\n \/\/ \\index{itk::RecursiveGaussianImageFilter!New()}\n \/\/ \\index{itk::RecursiveGaussianImageFilter!Pointer}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n FilterType::Pointer filterX1 = FilterType::New();\n FilterType::Pointer filterY1 = FilterType::New();\n\n FilterType::Pointer filterX2 = FilterType::New();\n FilterType::Pointer filterY2 = FilterType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Since each one of the newly created filters has the potential to perform\n \/\/ filtering along any dimension, we have to restrict each one to a\n \/\/ particular direction. This is done with the \\code{SetDirection()} method.\n \/\/\n \/\/ \\index{RecursiveGaussianImageFilter!SetDirection()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filterX1->SetDirection( 0 ); \/\/ 0 --> X direction\n filterY1->SetDirection( 1 ); \/\/ 1 --> Y direction\n\n filterX2->SetDirection( 0 ); \/\/ 0 --> X direction\n filterY2->SetDirection( 1 ); \/\/ 1 --> Y direction\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The \\doxygen{RecursiveGaussianImageFilter} can approximate the\n \/\/ convolution with the Gaussian or with its first and second\n \/\/ derivatives. We select one of these options by using the\n \/\/ \\code{SetOrder()} method. Note that the argument is an \\code{enum} whose\n \/\/ values can be \\code{ZeroOrder}, \\code{FirstOrder} and\n \/\/ \\code{SecondOrder}. For example, to compute the $x$ partial derivative we\n \/\/ should select \\code{FirstOrder} for $x$ and \\code{ZeroOrder} for\n \/\/ $y$. Here we want only to smooth in $x$ and $y$, so we select\n \/\/ \\code{ZeroOrder} in both directions.\n \/\/\n \/\/ \\index{RecursiveGaussianImageFilter!SetOrder()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filterX1->SetOrder( FilterType::ZeroOrder );\n filterY1->SetOrder( FilterType::SecondOrder );\n\n filterX2->SetOrder( FilterType::SecondOrder );\n filterY2->SetOrder( FilterType::ZeroOrder );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ There are two typical ways of normalizing Gaussians depending on their\n \/\/ application. For scale-space analysis it is desirable to use a\n \/\/ normalization that will preserve the maximum value of the input. This\n \/\/ normalization is represented by the following equation.\n \/\/\n \/\/ \\begin{equation}\n \/\/ \\frac{ 1 }{ \\sigma \\sqrt{ 2 \\pi } }\n \/\/ \\end{equation}\n \/\/\n \/\/ In applications that use the Gaussian as a solution of the diffusion\n \/\/ equation it is desirable to use a normalization that preserve the\n \/\/ integral of the signal. This last approach can be seen as a conservation\n \/\/ of mass principle. This is represented by the following equation.\n \/\/\n \/\/ \\begin{equation}\n \/\/ \\frac{ 1 }{ \\sigma^2 \\sqrt{ 2 \\pi } }\n \/\/ \\end{equation}\n \/\/\n \/\/ The \\doxygen{RecursiveGaussianImageFilter} has a boolean flag that allows\n \/\/ users to select between these two normalization options. Selection is\n \/\/ done with the method \\code{SetNormalizeAcrossScale()}. Enable this flag\n \/\/ to analyzing an image across scale-space. In the current example, this\n \/\/ setting has no impact because we are actually renormalizing the output to\n \/\/ the dynamic range of the reader, so we simply disable the flag.\n \/\/\n \/\/ \\index{RecursiveGaussianImageFilter!SetNormalizeAcrossScale()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n const bool normalizeAcrossScale = false;\n filterX1->SetNormalizeAcrossScale( normalizeAcrossScale );\n filterY1->SetNormalizeAcrossScale( normalizeAcrossScale );\n filterX2->SetNormalizeAcrossScale( normalizeAcrossScale );\n filterY2->SetNormalizeAcrossScale( normalizeAcrossScale );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The input image can be obtained from the output of another\n \/\/ filter. Here, an image reader is used as the source. The image is passed to\n \/\/ the $x$ filter and then to the $y$ filter. The reason for keeping these\n \/\/ two filters separate is that it is usual in scale-space applications to\n \/\/ compute not only the smoothing but also combinations of derivatives at\n \/\/ different orders and smoothing. Some factorization is possible when\n \/\/ separate filters are used to generate the intermediate results. Here\n \/\/ this capability is less interesting, though, since we only want to smooth\n \/\/ the image in all directions.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filterX1->SetInput( reader->GetOutput() );\n filterY1->SetInput( filterX1->GetOutput() );\n\n filterY2->SetInput( reader->GetOutput() );\n filterX2->SetInput( filterY2->GetOutput() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ It is now time to select the $\\sigma$ of the Gaussian used to smooth the\n \/\/ data. Note that $\\sigma$ must be passed to both filters and that sigma\n \/\/ is considered to be in millimeters. That is, at the moment of applying\n \/\/ the smoothing process, the filter will take into account the spacing\n \/\/ values defined in the image.\n \/\/\n \/\/ \\index{itk::RecursiveGaussianImageFilter!SetSigma()}\n \/\/ \\index{SetSigma()!itk::RecursiveGaussianImageFilter}\n \/\/\n \/\/ Software Guide : EndLatex\n\n const double sigma = atof( argv[3] );\n\n \/\/ Software Guide : BeginCodeSnippet\n filterX1->SetSigma( sigma );\n filterY1->SetSigma( sigma );\n filterX2->SetSigma( sigma );\n filterY2->SetSigma( sigma );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Finally the two components of the Laplacian should be added together. The\n \/\/ \\doxygen{AddImageFilter} is used for this purpose.\n \/\/\n \/\/ \\index{itk::AddImageFilter!Instantiation}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::AddImageFilter<\n OutputImageType,\n OutputImageType,\n OutputImageType > AddFilterType;\n\n AddFilterType::Pointer addFilter = AddFilterType::New();\n\n addFilter->SetInput1( filterY1->GetOutput() );\n addFilter->SetInput2( filterX2->GetOutput() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The filters are triggered by invoking \\code{Update()} on the Add filter\n \/\/ at the end of the pipeline.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n try\n {\n addFilter->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n std::cout << \"ExceptionObject caught !\" << std::endl;\n std::cout << err << std::endl;\n return EXIT_FAILURE;\n }\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The resulting image could be saved to a file using the\n \/\/ \\doxygen{ImageFileWriter} class.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef float WritePixelType;\n\n typedef itk::Image< WritePixelType, 2 > WriteImageType;\n\n typedef itk::ImageFileWriter< WriteImageType > WriterType;\n\n WriterType::Pointer writer = WriterType::New();\n\n writer->SetInput( addFilter->GetOutput() );\n\n writer->SetFileName( argv[2] );\n\n writer->Update();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ \\begin{figure}\n \/\/ \\center\n \/\/ \\includegraphics[width=0.44\\textwidth]{LaplacianRecursiveGaussianImageFilterOutput3}\n \/\/ \\includegraphics[width=0.44\\textwidth]{LaplacianRecursiveGaussianImageFilterOutput5}\n \/\/ \\itkcaption[Output of the LaplacianRecursiveGaussianImageFilter.]{Effect of the\n \/\/ LaplacianRecursiveGaussianImageFilter on a slice from a MRI proton density image\n \/\/ of the brain.}\n \/\/ \\label{fig:LaplacianRecursiveGaussianImageFilterInputOutput}\n \/\/ \\end{figure}\n \/\/\n \/\/ Figure~\\ref{fig:LaplacianRecursiveGaussianImageFilterInputOutput} illustrates the\n \/\/ effect of this filter on a MRI proton density image of the brain using\n \/\/ $\\sigma$ values of $3$ (left) and $5$ (right). The figure shows how the\n \/\/ attenuation of noise can be regulated by selecting the appropriate\n \/\/ standard deviation. This type of scale-tunable filter is suitable for\n \/\/ performing scale-space analysis.\n \/\/\n \/\/ Software Guide : EndLatex\n\n\n \/\/ Rescale float outputs to png for inclusion in the Software guide\n \/\/\n if (argc > 4)\n {\n typedef unsigned char CharPixelType;\n typedef itk::Image CharImageType;\n\n typedef itk::RescaleIntensityImageFilter< OutputImageType, CharImageType>\n RescaleFilterType;\n\n RescaleFilterType::Pointer rescale = RescaleFilterType::New();\n rescale->SetInput( addFilter->GetOutput() );\n rescale->SetOutputMinimum( 0 );\n rescale->SetOutputMaximum( 255 );\n typedef itk::ImageFileWriter< CharImageType > CharWriterType;\n CharWriterType::Pointer charWriter = CharWriterType::New();\n charWriter->SetFileName( argv[4] );\n charWriter->SetInput( rescale->GetOutput() );\n charWriter->Update();\n }\n\n\n return EXIT_SUCCESS;\n}\nDOC: Remove duplicate text in LaplacianRecursiveGaussian example.\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {BrainProtonDensitySlice.png}\n\/\/ ARGUMENTS: LaplacianRecursiveGaussianImageFilterOutput3.mha 3\n\/\/ OUTPUTS: {LaplacianRecursiveGaussianImageFilterOutput3.png}\n\/\/ Software Guide : EndCommandLineArgs\n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {BrainProtonDensitySlice.png}\n\/\/ ARGUMENTS: LaplacianRecursiveGaussianImageFilterOutput5.mha 5\n\/\/ OUTPUTS: {LaplacianRecursiveGaussianImageFilterOutput5.png}\n\/\/ Software Guide : EndCommandLineArgs\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example illustrates how to use the\n\/\/ \\doxygen{RecursiveGaussianImageFilter} for computing the Laplacian of a 2D\n\/\/ image.\n\/\/\n\/\/ \\index{itk::RecursiveGaussianImageFilter}\n\/\/\n\/\/ Software Guide : EndLatex\n\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkAddImageFilter.h\"\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The first step required to use this filter is to include its header file.\n\/\/\n\/\/ \\index{itk::RecursiveGaussianImageFilter!header}\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkRecursiveGaussianImageFilter.h\"\n\/\/ Software Guide : EndCodeSnippet\n#include \"itkRescaleIntensityImageFilter.h\"\n\n\nint main( int argc, char * argv[] )\n{\n if( argc < 4 )\n {\n std::cerr << \"Usage: \" << std::endl;\n std::cerr << argv[0] << \" inputImageFile outputImageFile sigma [RescaledOutputImageFile] \" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Types should be selected on the desired input and output pixel types.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef float InputPixelType;\n typedef float OutputPixelType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The input and output image types are instantiated using the pixel types.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::Image< InputPixelType, 2 > InputImageType;\n typedef itk::Image< OutputPixelType, 2 > OutputImageType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n typedef itk::ImageFileReader< InputImageType > ReaderType;\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The filter type is now instantiated using both the input image and the\n \/\/ output image types.\n \/\/\n \/\/ \\index{itk::RecursiveGaussianImageFilter!Instantiation}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::RecursiveGaussianImageFilter<\n InputImageType, OutputImageType > FilterType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( argv[1] );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ This filter applies the approximation of the convolution along a single\n \/\/ dimension. It is therefore necessary to concatenate several of these filters\n \/\/ to produce smoothing in all directions. In this example, we create a pair\n \/\/ of filters since we are processing a $2D$ image. The filters are\n \/\/ created by invoking the \\code{New()} method and assigning the result to\n \/\/ a \\doxygen{SmartPointer}.\n \/\/\n \/\/ We need two filters for computing the X component of the Laplacian and\n \/\/ two other filters for computing the Y component.\n \/\/\n \/\/ \\index{itk::RecursiveGaussianImageFilter!New()}\n \/\/ \\index{itk::RecursiveGaussianImageFilter!Pointer}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n FilterType::Pointer filterX1 = FilterType::New();\n FilterType::Pointer filterY1 = FilterType::New();\n\n FilterType::Pointer filterX2 = FilterType::New();\n FilterType::Pointer filterY2 = FilterType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Since each one of the newly created filters has the potential to perform\n \/\/ filtering along any dimension, we have to restrict each one to a\n \/\/ particular direction. This is done with the \\code{SetDirection()} method.\n \/\/\n \/\/ \\index{RecursiveGaussianImageFilter!SetDirection()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filterX1->SetDirection( 0 ); \/\/ 0 --> X direction\n filterY1->SetDirection( 1 ); \/\/ 1 --> Y direction\n\n filterX2->SetDirection( 0 ); \/\/ 0 --> X direction\n filterY2->SetDirection( 1 ); \/\/ 1 --> Y direction\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The \\doxygen{RecursiveGaussianImageFilter} can approximate the\n \/\/ convolution with the Gaussian or with its first and second\n \/\/ derivatives. We select one of these options by using the\n \/\/ \\code{SetOrder()} method. Note that the argument is an \\code{enum} whose\n \/\/ values can be \\code{ZeroOrder}, \\code{FirstOrder} and\n \/\/ \\code{SecondOrder}. For example, to compute the $x$ partial derivative we\n \/\/ should select \\code{FirstOrder} for $x$ and \\code{ZeroOrder} for\n \/\/ $y$. Here we want only to smooth in $x$ and $y$, so we select\n \/\/ \\code{ZeroOrder} in both directions.\n \/\/\n \/\/ \\index{RecursiveGaussianImageFilter!SetOrder()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filterX1->SetOrder( FilterType::ZeroOrder );\n filterY1->SetOrder( FilterType::SecondOrder );\n\n filterX2->SetOrder( FilterType::SecondOrder );\n filterY2->SetOrder( FilterType::ZeroOrder );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ There are two typical ways of normalizing Gaussians depending on their\n \/\/ application. For scale-space analysis it is desirable to use a\n \/\/ normalization that will preserve the maximum value of the input. This\n \/\/ normalization is represented by the following equation.\n \/\/\n \/\/ \\begin{equation}\n \/\/ \\frac{ 1 }{ \\sigma \\sqrt{ 2 \\pi } }\n \/\/ \\end{equation}\n \/\/\n \/\/ In applications that use the Gaussian as a solution of the diffusion\n \/\/ equation it is desirable to use a normalization that preserve the\n \/\/ integral of the signal. This last approach can be seen as a conservation\n \/\/ of mass principle. This is represented by the following equation.\n \/\/\n \/\/ \\begin{equation}\n \/\/ \\frac{ 1 }{ \\sigma^2 \\sqrt{ 2 \\pi } }\n \/\/ \\end{equation}\n \/\/\n \/\/ The \\doxygen{RecursiveGaussianImageFilter} has a boolean flag that allows\n \/\/ users to select between these two normalization options. Selection is\n \/\/ done with the method \\code{SetNormalizeAcrossScale()}. Enable this flag\n \/\/ to analyzing an image across scale-space. In the current example, this\n \/\/ setting has no impact because we are actually renormalizing the output to\n \/\/ the dynamic range of the reader, so we simply disable the flag.\n \/\/\n \/\/ \\index{RecursiveGaussianImageFilter!SetNormalizeAcrossScale()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n const bool normalizeAcrossScale = false;\n filterX1->SetNormalizeAcrossScale( normalizeAcrossScale );\n filterY1->SetNormalizeAcrossScale( normalizeAcrossScale );\n filterX2->SetNormalizeAcrossScale( normalizeAcrossScale );\n filterY2->SetNormalizeAcrossScale( normalizeAcrossScale );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The input image can be obtained from the output of another\n \/\/ filter. Here, an image reader is used as the source. The image is passed to\n \/\/ the $x$ filter and then to the $y$ filter. The reason for keeping these\n \/\/ two filters separate is that it is usual in scale-space applications to\n \/\/ compute not only the smoothing but also combinations of derivatives at\n \/\/ different orders and smoothing. Some factorization is possible when\n \/\/ separate filters are used to generate the intermediate results. Here\n \/\/ this capability is less interesting, though, since we only want to smooth\n \/\/ the image in all directions.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filterX1->SetInput( reader->GetOutput() );\n filterY1->SetInput( filterX1->GetOutput() );\n\n filterY2->SetInput( reader->GetOutput() );\n filterX2->SetInput( filterY2->GetOutput() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ It is now time to select the $\\sigma$ of the Gaussian used to smooth the\n \/\/ data. Note that $\\sigma$ must be passed to both filters and that sigma\n \/\/ is considered to be in millimeters. That is, at the moment of applying\n \/\/ the smoothing process, the filter will take into account the spacing\n \/\/ values defined in the image.\n \/\/\n \/\/ \\index{itk::RecursiveGaussianImageFilter!SetSigma()}\n \/\/ \\index{SetSigma()!itk::RecursiveGaussianImageFilter}\n \/\/\n \/\/ Software Guide : EndLatex\n\n const double sigma = atof( argv[3] );\n\n \/\/ Software Guide : BeginCodeSnippet\n filterX1->SetSigma( sigma );\n filterY1->SetSigma( sigma );\n filterX2->SetSigma( sigma );\n filterY2->SetSigma( sigma );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Finally the two components of the Laplacian should be added together. The\n \/\/ \\doxygen{AddImageFilter} is used for this purpose.\n \/\/\n \/\/ \\index{itk::AddImageFilter!Instantiation}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::AddImageFilter<\n OutputImageType,\n OutputImageType,\n OutputImageType > AddFilterType;\n\n AddFilterType::Pointer addFilter = AddFilterType::New();\n\n addFilter->SetInput1( filterY1->GetOutput() );\n addFilter->SetInput2( filterX2->GetOutput() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The filters are triggered by invoking \\code{Update()} on the Add filter\n \/\/ at the end of the pipeline.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n try\n {\n addFilter->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n std::cout << \"ExceptionObject caught !\" << std::endl;\n std::cout << err << std::endl;\n return EXIT_FAILURE;\n }\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The resulting image could be saved to a file using the\n \/\/ \\doxygen{ImageFileWriter} class.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef float WritePixelType;\n\n typedef itk::Image< WritePixelType, 2 > WriteImageType;\n\n typedef itk::ImageFileWriter< WriteImageType > WriterType;\n\n WriterType::Pointer writer = WriterType::New();\n\n writer->SetInput( addFilter->GetOutput() );\n\n writer->SetFileName( argv[2] );\n\n writer->Update();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ \\begin{figure}\n \/\/ \\center\n \/\/ \\includegraphics[width=0.44\\textwidth]{LaplacianRecursiveGaussianImageFilterOutput3}\n \/\/ \\includegraphics[width=0.44\\textwidth]{LaplacianRecursiveGaussianImageFilterOutput5}\n \/\/ \\itkcaption[Output of the LaplacianRecursiveGaussianImageFilter.]{Effect of the\n \/\/ LaplacianRecursiveGaussianImageFilter on a slice from a MRI proton density image\n \/\/ of the brain.}\n \/\/ \\label{fig:LaplacianRecursiveGaussianImageFilterInputOutput}\n \/\/ \\end{figure}\n \/\/\n \/\/ Software Guide : EndLatex\n\n\n \/\/ Rescale float outputs to png for inclusion in the Software guide\n \/\/\n if (argc > 4)\n {\n typedef unsigned char CharPixelType;\n typedef itk::Image CharImageType;\n\n typedef itk::RescaleIntensityImageFilter< OutputImageType, CharImageType>\n RescaleFilterType;\n\n RescaleFilterType::Pointer rescale = RescaleFilterType::New();\n rescale->SetInput( addFilter->GetOutput() );\n rescale->SetOutputMinimum( 0 );\n rescale->SetOutputMaximum( 255 );\n typedef itk::ImageFileWriter< CharImageType > CharWriterType;\n CharWriterType::Pointer charWriter = CharWriterType::New();\n charWriter->SetFileName( argv[4] );\n charWriter->SetInput( rescale->GetOutput() );\n charWriter->Update();\n }\n\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SC_DPOBJECT_HXX\n#define SC_DPOBJECT_HXX\n\n#include \"scdllapi.h\"\n#include \"global.hxx\"\n#include \"address.hxx\"\n#include \"collect.hxx\"\n#include \"dpoutput.hxx\"\n#include \"pivot.hxx\"\n#include \n\n#include \n#include \n#include \n\nnamespace com { namespace sun { namespace star { namespace sheet {\n\n struct DataPilotTablePositionData;\n struct DataPilotTableHeaderData;\n\n}}}}\n\nnamespace com { namespace sun { namespace star { namespace sheet {\n struct DataPilotFieldFilter;\n}}}}\n\nclass Rectangle;\nclass SvStream;\nclass ScDPSaveData;\nclass ScDPOutput;\nclass ScPivot;\nclass ScPivotCollection;\nstruct ScPivotParam;\nstruct ScImportSourceDesc;\nstruct ScSheetSourceDesc;\nclass ScStrCollection;\nclass TypedScStrCollection;\nstruct PivotField;\nclass ScDPCacheTable;\nclass ScDPTableData;\n\nstruct ScDPServiceDesc\n{\n String aServiceName;\n String aParSource;\n String aParName;\n String aParUser;\n String aParPass;\n\n ScDPServiceDesc( const String& rServ, const String& rSrc, const String& rNam,\n const String& rUser, const String& rPass ) :\n aServiceName( rServ ), aParSource( rSrc ), aParName( rNam ),\n aParUser( rUser ), aParPass( rPass ) { }\n\n sal_Bool operator== ( const ScDPServiceDesc& rOther ) const\n { return aServiceName == rOther.aServiceName &&\n aParSource == rOther.aParSource &&\n aParName == rOther.aParName &&\n aParUser == rOther.aParUser &&\n aParPass == rOther.aParPass; }\n};\n\n\nclass SC_DLLPUBLIC ScDPObject\n{\nprivate:\n ScDocument* pDoc;\n \/\/ settings\n ScDPSaveData* pSaveData;\n String aTableName;\n String aTableTag;\n ScRange aOutRange;\n ScSheetSourceDesc* pSheetDesc; \/\/ for sheet data\n ScImportSourceDesc* pImpDesc; \/\/ for database data\n ScDPServiceDesc* pServDesc; \/\/ for external service\n ::boost::shared_ptr mpTableData;\n \/\/ cached data\n com::sun::star::uno::Reference xSource;\n ScDPOutput* pOutput;\n sal_Bool bSettingsChanged;\n sal_Bool bAlive; \/\/ sal_False if only used to hold settings\n sal_uInt16 mnAutoFormatIndex;\n sal_Bool bAllowMove;\n long nHeaderRows; \/\/ page fields plus filter button\n bool mbHeaderLayout; \/\/ sal_True : grid, sal_False : standard\n\n\n SC_DLLPRIVATE ScDPTableData* GetTableData();\n SC_DLLPRIVATE void CreateObjects();\n SC_DLLPRIVATE void CreateOutput();\n sal_Bool bRefresh;\n long mnCacheId;\n\npublic:\n ScDPObject(ScDocument* pD);\n ScDPObject(const ScDPObject& r);\n ~ScDPObject();\n\n \/**\n * When a DP object is \"alive\", it has table output on a sheet. This flag\n * doesn't really change the behavior of the object, but is used only for\n * testing purposes.\n *\/\n void SetAlive(sal_Bool bSet);\n void SetAllowMove(sal_Bool bSet);\n\n void InvalidateData();\n void ClearSource();\n\n\n void Output( const ScAddress& rPos );\n ScRange GetNewOutputRange( bool& rOverflow );\n const ScRange GetOutputRangeByType( sal_Int32 nType );\n\n void SetSaveData(const ScDPSaveData& rData);\n ScDPSaveData* GetSaveData() const { return pSaveData; }\n\n void SetOutRange(const ScRange& rRange);\n const ScRange& GetOutRange() const { return aOutRange; }\n\n void SetHeaderLayout(bool bUseGrid);\n bool GetHeaderLayout() const;\n\n void SetSheetDesc(const ScSheetSourceDesc& rDesc);\n void SetImportDesc(const ScImportSourceDesc& rDesc);\n void SetServiceData(const ScDPServiceDesc& rDesc);\n\n void WriteSourceDataTo( ScDPObject& rDest ) const;\n void WriteTempDataTo( ScDPObject& rDest ) const;\n\n const ScSheetSourceDesc* GetSheetDesc() const { return pSheetDesc; }\n const ScImportSourceDesc* GetImportSourceDesc() const { return pImpDesc; }\n const ScDPServiceDesc* GetDPServiceDesc() const { return pServDesc; }\n\n com::sun::star::uno::Reference GetSource();\n\n sal_Bool IsSheetData() const;\n sal_Bool IsImportData() const { return(pImpDesc != NULL); }\n sal_Bool IsServiceData() const { return(pServDesc != NULL); }\n\n void SetName(const String& rNew);\n const String& GetName() const { return aTableName; }\n void SetTag(const String& rNew);\n const String& GetTag() const { return aTableTag; }\n\n \/**\n * Data description cell displays the description of a data dimension if\n * and only if there is only one data dimension. It's usually located at\n * the upper-left corner of the table output.\n *\/\n bool IsDataDescriptionCell(const ScAddress& rPos);\n\n bool IsDimNameInUse(const ::rtl::OUString& rName) const;\n String GetDimName( long nDim, sal_Bool& rIsDataLayout, sal_Int32* pFlags = NULL );\n sal_Bool IsDuplicated( long nDim );\n long GetDimCount();\n void GetHeaderPositionData(const ScAddress& rPos, ::com::sun::star::sheet::DataPilotTableHeaderData& rData);\n long GetHeaderDim( const ScAddress& rPos, sal_uInt16& rOrient );\n sal_Bool GetHeaderDrag( const ScAddress& rPos, sal_Bool bMouseLeft, sal_Bool bMouseTop,\n long nDragDim,\n Rectangle& rPosRect, sal_uInt16& rOrient, long& rDimPos );\n sal_Bool IsFilterButton( const ScAddress& rPos );\n\n sal_Bool GetPivotData( ScDPGetPivotDataField& rTarget, \/* returns result *\/\n const std::vector< ScDPGetPivotDataField >& rFilters );\n sal_Bool ParseFilters( ScDPGetPivotDataField& rTarget,\n std::vector< ScDPGetPivotDataField >& rFilters,\n const String& rFilterList );\n\n void GetMemberResultNames( ScStrCollection& rNames, long nDimension );\n\n void FillPageList( TypedScStrCollection& rStrings, long nField );\n\n void ToggleDetails(const ::com::sun::star::sheet::DataPilotTableHeaderData& rElemDesc, ScDPObject* pDestObj);\n\n sal_Bool FillOldParam(ScPivotParam& rParam) const;\n sal_Bool FillLabelData(ScPivotParam& rParam);\n void InitFromOldPivot(const ScPivot& rOld, ScDocument* pDoc, sal_Bool bSetSource);\n\n sal_Bool GetHierarchiesNA( sal_Int32 nDim, com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xHiers );\n sal_Bool GetHierarchies( sal_Int32 nDim, com::sun::star::uno::Sequence< rtl::OUString >& rHiers );\n\n sal_Int32 GetUsedHierarchy( sal_Int32 nDim );\n\n sal_Bool GetMembersNA( sal_Int32 nDim, com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xMembers );\n sal_Bool GetMembersNA( sal_Int32 nDim, sal_Int32 nHier, com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xMembers );\n\n bool GetMemberNames( sal_Int32 nDim, ::com::sun::star::uno::Sequence< ::rtl::OUString >& rNames );\n bool GetMembers( sal_Int32 nDim, sal_Int32 nHier, ::std::vector& rMembers );\n\n void UpdateReference( UpdateRefMode eUpdateRefMode,\n const ScRange& r, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );\n sal_Bool RefsEqual( const ScDPObject& r ) const;\n void WriteRefsTo( ScDPObject& r ) const;\n\n void GetPositionData(const ScAddress& rPos, ::com::sun::star::sheet::DataPilotTablePositionData& rPosData);\n\n bool GetDataFieldPositionData(const ScAddress& rPos,\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::sheet::DataPilotFieldFilter >& rFilters);\n\n void GetDrillDownData(const ScAddress& rPos,\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Any > >& rTableData);\n\n \/\/ apply drop-down attribute, initialize nHeaderRows, without accessing the source\n \/\/ (button attribute must be present)\n void RefreshAfterLoad();\n\n void BuildAllDimensionMembers();\n\n static sal_Bool HasRegisteredSources();\n static com::sun::star::uno::Sequence GetRegisteredSources();\n static com::sun::star::uno::Reference\n CreateSource( const ScDPServiceDesc& rDesc );\n\n static void ConvertOrientation( ScDPSaveData& rSaveData,\n const ::std::vector& rFields, sal_uInt16 nOrient,\n const com::sun::star::uno::Reference<\n com::sun::star::sheet::XDimensionsSupplier>& xSource,\n ::std::vector* pRefColFields = NULL,\n ::std::vector* pRefRowFields = NULL,\n ::std::vector* pRefPageFields = NULL );\n\n static bool IsOrientationAllowed( sal_uInt16 nOrient, sal_Int32 nDimFlags );\n};\n\n\nclass ScDPCollection\n{\nprivate:\n typedef ::boost::ptr_vector TablesType;\n\n ScDocument* pDoc;\n TablesType maTables;\n\npublic:\n ScDPCollection(ScDocument* pDocument);\n ScDPCollection(const ScDPCollection& r);\n ~ScDPCollection();\n\n SC_DLLPUBLIC size_t GetCount() const;\n SC_DLLPUBLIC ScDPObject* operator[](size_t nIndex);\n SC_DLLPUBLIC const ScDPObject* operator[](size_t nIndex) const;\n\n const ScDPObject* GetByName(const String& rName) const;\n\n void DeleteOnTab( SCTAB nTab );\n void UpdateReference( UpdateRefMode eUpdateRefMode,\n const ScRange& r, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );\n\n bool RefsEqual( const ScDPCollection& r ) const;\n void WriteRefsTo( ScDPCollection& r ) const;\n\n \/**\n * Create a new name that's not yet used by any existing data pilot\n * objects. All data pilot names are 'DataPilot' + , and the nMin\n * specifies the minimum number allowed.\n *\n * @param nMin minimum number allowed.\n *\n * @return new name for data pilot object.\n *\/\n String CreateNewName( sal_uInt16 nMin = 1 ) const;\n\n void FreeTable(ScDPObject* pDPObj);\n SC_DLLPUBLIC bool InsertNewTable(ScDPObject* pDPObj);\n\n bool HasDPTable(SCCOL nCol, SCROW nRow, SCTAB nTab) const;\n};\n\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nWaE: consistent struct\/class declaration\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SC_DPOBJECT_HXX\n#define SC_DPOBJECT_HXX\n\n#include \"scdllapi.h\"\n#include \"global.hxx\"\n#include \"address.hxx\"\n#include \"collect.hxx\"\n#include \"dpoutput.hxx\"\n#include \"pivot.hxx\"\n#include \n\n#include \n#include \n#include \n\nnamespace com { namespace sun { namespace star { namespace sheet {\n\n struct DataPilotTablePositionData;\n struct DataPilotTableHeaderData;\n\n}}}}\n\nnamespace com { namespace sun { namespace star { namespace sheet {\n struct DataPilotFieldFilter;\n}}}}\n\nclass Rectangle;\nclass SvStream;\nclass ScDPSaveData;\nclass ScDPOutput;\nclass ScPivot;\nclass ScPivotCollection;\nstruct ScPivotParam;\nstruct ScImportSourceDesc;\nclass ScSheetSourceDesc;\nclass ScStrCollection;\nclass TypedScStrCollection;\nstruct PivotField;\nclass ScDPCacheTable;\nclass ScDPTableData;\n\nstruct ScDPServiceDesc\n{\n String aServiceName;\n String aParSource;\n String aParName;\n String aParUser;\n String aParPass;\n\n ScDPServiceDesc( const String& rServ, const String& rSrc, const String& rNam,\n const String& rUser, const String& rPass ) :\n aServiceName( rServ ), aParSource( rSrc ), aParName( rNam ),\n aParUser( rUser ), aParPass( rPass ) { }\n\n sal_Bool operator== ( const ScDPServiceDesc& rOther ) const\n { return aServiceName == rOther.aServiceName &&\n aParSource == rOther.aParSource &&\n aParName == rOther.aParName &&\n aParUser == rOther.aParUser &&\n aParPass == rOther.aParPass; }\n};\n\n\nclass SC_DLLPUBLIC ScDPObject\n{\nprivate:\n ScDocument* pDoc;\n \/\/ settings\n ScDPSaveData* pSaveData;\n String aTableName;\n String aTableTag;\n ScRange aOutRange;\n ScSheetSourceDesc* pSheetDesc; \/\/ for sheet data\n ScImportSourceDesc* pImpDesc; \/\/ for database data\n ScDPServiceDesc* pServDesc; \/\/ for external service\n ::boost::shared_ptr mpTableData;\n \/\/ cached data\n com::sun::star::uno::Reference xSource;\n ScDPOutput* pOutput;\n sal_Bool bSettingsChanged;\n sal_Bool bAlive; \/\/ sal_False if only used to hold settings\n sal_uInt16 mnAutoFormatIndex;\n sal_Bool bAllowMove;\n long nHeaderRows; \/\/ page fields plus filter button\n bool mbHeaderLayout; \/\/ sal_True : grid, sal_False : standard\n\n\n SC_DLLPRIVATE ScDPTableData* GetTableData();\n SC_DLLPRIVATE void CreateObjects();\n SC_DLLPRIVATE void CreateOutput();\n sal_Bool bRefresh;\n long mnCacheId;\n\npublic:\n ScDPObject(ScDocument* pD);\n ScDPObject(const ScDPObject& r);\n ~ScDPObject();\n\n \/**\n * When a DP object is \"alive\", it has table output on a sheet. This flag\n * doesn't really change the behavior of the object, but is used only for\n * testing purposes.\n *\/\n void SetAlive(sal_Bool bSet);\n void SetAllowMove(sal_Bool bSet);\n\n void InvalidateData();\n void ClearSource();\n\n\n void Output( const ScAddress& rPos );\n ScRange GetNewOutputRange( bool& rOverflow );\n const ScRange GetOutputRangeByType( sal_Int32 nType );\n\n void SetSaveData(const ScDPSaveData& rData);\n ScDPSaveData* GetSaveData() const { return pSaveData; }\n\n void SetOutRange(const ScRange& rRange);\n const ScRange& GetOutRange() const { return aOutRange; }\n\n void SetHeaderLayout(bool bUseGrid);\n bool GetHeaderLayout() const;\n\n void SetSheetDesc(const ScSheetSourceDesc& rDesc);\n void SetImportDesc(const ScImportSourceDesc& rDesc);\n void SetServiceData(const ScDPServiceDesc& rDesc);\n\n void WriteSourceDataTo( ScDPObject& rDest ) const;\n void WriteTempDataTo( ScDPObject& rDest ) const;\n\n const ScSheetSourceDesc* GetSheetDesc() const { return pSheetDesc; }\n const ScImportSourceDesc* GetImportSourceDesc() const { return pImpDesc; }\n const ScDPServiceDesc* GetDPServiceDesc() const { return pServDesc; }\n\n com::sun::star::uno::Reference GetSource();\n\n sal_Bool IsSheetData() const;\n sal_Bool IsImportData() const { return(pImpDesc != NULL); }\n sal_Bool IsServiceData() const { return(pServDesc != NULL); }\n\n void SetName(const String& rNew);\n const String& GetName() const { return aTableName; }\n void SetTag(const String& rNew);\n const String& GetTag() const { return aTableTag; }\n\n \/**\n * Data description cell displays the description of a data dimension if\n * and only if there is only one data dimension. It's usually located at\n * the upper-left corner of the table output.\n *\/\n bool IsDataDescriptionCell(const ScAddress& rPos);\n\n bool IsDimNameInUse(const ::rtl::OUString& rName) const;\n String GetDimName( long nDim, sal_Bool& rIsDataLayout, sal_Int32* pFlags = NULL );\n sal_Bool IsDuplicated( long nDim );\n long GetDimCount();\n void GetHeaderPositionData(const ScAddress& rPos, ::com::sun::star::sheet::DataPilotTableHeaderData& rData);\n long GetHeaderDim( const ScAddress& rPos, sal_uInt16& rOrient );\n sal_Bool GetHeaderDrag( const ScAddress& rPos, sal_Bool bMouseLeft, sal_Bool bMouseTop,\n long nDragDim,\n Rectangle& rPosRect, sal_uInt16& rOrient, long& rDimPos );\n sal_Bool IsFilterButton( const ScAddress& rPos );\n\n sal_Bool GetPivotData( ScDPGetPivotDataField& rTarget, \/* returns result *\/\n const std::vector< ScDPGetPivotDataField >& rFilters );\n sal_Bool ParseFilters( ScDPGetPivotDataField& rTarget,\n std::vector< ScDPGetPivotDataField >& rFilters,\n const String& rFilterList );\n\n void GetMemberResultNames( ScStrCollection& rNames, long nDimension );\n\n void FillPageList( TypedScStrCollection& rStrings, long nField );\n\n void ToggleDetails(const ::com::sun::star::sheet::DataPilotTableHeaderData& rElemDesc, ScDPObject* pDestObj);\n\n sal_Bool FillOldParam(ScPivotParam& rParam) const;\n sal_Bool FillLabelData(ScPivotParam& rParam);\n void InitFromOldPivot(const ScPivot& rOld, ScDocument* pDoc, sal_Bool bSetSource);\n\n sal_Bool GetHierarchiesNA( sal_Int32 nDim, com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xHiers );\n sal_Bool GetHierarchies( sal_Int32 nDim, com::sun::star::uno::Sequence< rtl::OUString >& rHiers );\n\n sal_Int32 GetUsedHierarchy( sal_Int32 nDim );\n\n sal_Bool GetMembersNA( sal_Int32 nDim, com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xMembers );\n sal_Bool GetMembersNA( sal_Int32 nDim, sal_Int32 nHier, com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& xMembers );\n\n bool GetMemberNames( sal_Int32 nDim, ::com::sun::star::uno::Sequence< ::rtl::OUString >& rNames );\n bool GetMembers( sal_Int32 nDim, sal_Int32 nHier, ::std::vector& rMembers );\n\n void UpdateReference( UpdateRefMode eUpdateRefMode,\n const ScRange& r, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );\n sal_Bool RefsEqual( const ScDPObject& r ) const;\n void WriteRefsTo( ScDPObject& r ) const;\n\n void GetPositionData(const ScAddress& rPos, ::com::sun::star::sheet::DataPilotTablePositionData& rPosData);\n\n bool GetDataFieldPositionData(const ScAddress& rPos,\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::sheet::DataPilotFieldFilter >& rFilters);\n\n void GetDrillDownData(const ScAddress& rPos,\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Any > >& rTableData);\n\n \/\/ apply drop-down attribute, initialize nHeaderRows, without accessing the source\n \/\/ (button attribute must be present)\n void RefreshAfterLoad();\n\n void BuildAllDimensionMembers();\n\n static sal_Bool HasRegisteredSources();\n static com::sun::star::uno::Sequence GetRegisteredSources();\n static com::sun::star::uno::Reference\n CreateSource( const ScDPServiceDesc& rDesc );\n\n static void ConvertOrientation( ScDPSaveData& rSaveData,\n const ::std::vector& rFields, sal_uInt16 nOrient,\n const com::sun::star::uno::Reference<\n com::sun::star::sheet::XDimensionsSupplier>& xSource,\n ::std::vector* pRefColFields = NULL,\n ::std::vector* pRefRowFields = NULL,\n ::std::vector* pRefPageFields = NULL );\n\n static bool IsOrientationAllowed( sal_uInt16 nOrient, sal_Int32 nDimFlags );\n};\n\n\nclass ScDPCollection\n{\nprivate:\n typedef ::boost::ptr_vector TablesType;\n\n ScDocument* pDoc;\n TablesType maTables;\n\npublic:\n ScDPCollection(ScDocument* pDocument);\n ScDPCollection(const ScDPCollection& r);\n ~ScDPCollection();\n\n SC_DLLPUBLIC size_t GetCount() const;\n SC_DLLPUBLIC ScDPObject* operator[](size_t nIndex);\n SC_DLLPUBLIC const ScDPObject* operator[](size_t nIndex) const;\n\n const ScDPObject* GetByName(const String& rName) const;\n\n void DeleteOnTab( SCTAB nTab );\n void UpdateReference( UpdateRefMode eUpdateRefMode,\n const ScRange& r, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );\n\n bool RefsEqual( const ScDPCollection& r ) const;\n void WriteRefsTo( ScDPCollection& r ) const;\n\n \/**\n * Create a new name that's not yet used by any existing data pilot\n * objects. All data pilot names are 'DataPilot' + , and the nMin\n * specifies the minimum number allowed.\n *\n * @param nMin minimum number allowed.\n *\n * @return new name for data pilot object.\n *\/\n String CreateNewName( sal_uInt16 nMin = 1 ) const;\n\n void FreeTable(ScDPObject* pDPObj);\n SC_DLLPUBLIC bool InsertNewTable(ScDPObject* pDPObj);\n\n bool HasDPTable(SCCOL nCol, SCROW nRow, SCTAB nTab) const;\n};\n\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"#include \"PyLogHook.h\"\n\n#include \n\n#include \n\n#include \n\n\/\/ todo: remove dependency\n#include \"..\/PyMeshPlugin.hh\"\n\nvoid* data = 0;\n\nvoid pyLog(const char* log)\n{\n assert(data); \/\/ todo: remove when depedency is removed\n reinterpret_cast(data)->pyOutput(log);\n}\n\nPyObject* stdOutPutCPP(PyObject* self, PyObject* args)\n{\n \/\/ parse parameters\n const char* str;\n if (!PyArg_ParseTuple(args, \"s\", &str))\n return NULL;\n\n \/\/ callback\n pyLog(str);\n\n \/\/ return nothing\n Py_INCREF(Py_None);\n return Py_None;\n}\n\nvoid stdOutPutCPP2(const char* w)\n{\n pyLog(w);\n}\n\nvoid initPyLogger(PyObject* module, void* customData)\n{\n assert(Py_IsInitialized());\n data = customData;\n\n const char* register_stdOutErrClass = \"\\\nimport sys\\n\\\nclass CatchOutErr:\\n\\\n def write(self, txt):\\n\\\n stdOutPutCPP(txt)\\n\\\n def flush(self):\\n\\\n pass\\n\\\nsys.stdout = CatchOutErr()\\n\\\nsys.stderr = CatchOutErr()\\n\\\n\";\n\n \n \n boost::python::object main_module(boost::python::handle<>(boost::python::borrowed(module)));\n boost::python::object main_namespace = main_module.attr(\"__dict__\");\n main_namespace[\"stdOutPutCPP\"] = stdOutPutCPP2;\n\n PyMethodDef pmd[] = { {\"stdOutPutCPP\",stdOutPutCPP,METH_VARARGS, \"\"},{NULL,NULL,0,NULL} };\n \/\/PyModule_AddFunctions(module, pmd);\n \/\/boost::python::exec(\"stdOutPutCPP(\\\"Hello non Hook\\\")\", main_namespace);\n\n PyRun_SimpleString(register_stdOutErrClass);\n\n PyErr_Print();\n}\n\n\nredirect PY error message to OF error output#include \"PyLogHook.h\"\n\n#include \n\n#include \n\n#include \n\n\/\/ todo: remove dependency\n#include \"..\/PyMeshPlugin.hh\"\n\nvoid* data = 0;\n\nvoid pyLog(const char* log)\n{\n assert(data);\n reinterpret_cast(data)->pyOutput(log);\n}\n\nvoid pyErr(const char* log)\n{\n assert(data);\n reinterpret_cast(data)->pyError(log);\n}\n\nPyObject* stdOutPutCPP(PyObject* self, PyObject* args)\n{\n \/\/ parse parameters\n const char* str;\n if (!PyArg_ParseTuple(args, \"s\", &str))\n return NULL;\n\n \/\/ callback\n pyLog(str);\n\n \/\/ return nothing\n Py_INCREF(Py_None);\n return Py_None;\n}\n\nPyObject* stdErrCPP(PyObject* self, PyObject* args)\n{\n \/\/ parse parameters\n const char* str;\n if (!PyArg_ParseTuple(args, \"s\", &str))\n return NULL;\n\n \/\/ callback\n pyErr(str);\n\n \/\/ return nothing\n Py_INCREF(Py_None);\n return Py_None;\n}\n\nvoid stdOutPutCPP2(const char* w)\n{\n pyLog(w);\n}\n\nvoid stdErrCPP2(const char* w)\n{\n pyErr(w);\n}\n\n\nvoid initPyLogger(PyObject* module, void* customData)\n{\n assert(Py_IsInitialized());\n data = customData;\n\n const char* register_stdOutErrClass = \"\\\nimport sys\\n\\\nclass OF_CatchOutput:\\n\\\n def write(self, txt):\\n\\\n stdOutPutCPP(txt)\\n\\\n def flush(self):\\n\\\n pass\\n\\\nclass OF_CatchError:\\n\\\n def write(self, txt):\\n\\\n stdErrCPP(txt)\\n\\\n def flush(self):\\n\\\n pass\\n\\\nsys.stdout = OF_CatchOutput()\\n\\\nsys.stderr = OF_CatchError()\\n\\\n\";\n\n \n \n boost::python::object main_module(boost::python::handle<>(boost::python::borrowed(module)));\n boost::python::object main_namespace = main_module.attr(\"__dict__\");\n main_namespace[\"stdOutPutCPP\"] = stdOutPutCPP2;\n main_namespace[\"stdErrCPP\"] = stdErrCPP2;\n\n \/\/PyMethodDef pmd[] = { \n \/\/ {\"stdOutPutCPP\",stdOutPutCPP,METH_VARARGS, \"\"},\n \/\/ {\"stdErrCPP\",stdErrCPP,METH_VARARGS, \"\"},\n \/\/ {NULL,NULL,0,NULL} };\n\n PyRun_SimpleString(register_stdOutErrClass);\n\n PyErr_Print();\n}\n\n\n<|endoftext|>"} {"text":"\/\/===--- DummyFuzzerMain.cpp - Entry point to sanity check the fuzzer -----===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Implementation of main so we can build and test without linking libFuzzer.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/Error.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm;\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size);\nextern \"C\" LLVM_ATTRIBUTE_WEAK int LLVMFuzzerInitialize(int *argc,\n char ***argv) {\n return 0;\n}\n\nint main(int argc, char *argv[]) {\n errs() << \"*** This tool was not linked to libFuzzer.\\n\"\n << \"*** No fuzzing will be performed.\\n\";\n if (int RC = LLVMFuzzerInitialize(&argc, &argv)) {\n errs() << \"Initialization failed\\n\";\n return RC;\n }\n\n for (int I = 1; I < argc; ++I) {\n StringRef Arg(argv[I]);\n if (Arg.startswith(\"-\")) {\n if (Arg.equals(\"-ignore_remaining_args=1\"))\n break;\n continue;\n }\n\n auto BufOrErr = MemoryBuffer::getFile(Arg, \/*FileSize-*\/ -1,\n \/*RequiresNullTerminator=*\/false);\n if (std::error_code EC = BufOrErr.getError()) {\n errs() << \"Error reading file: \" << Arg << \": \" << EC.message() << \"\\n\";\n return 1;\n }\n std::unique_ptr Buf = std::move(BufOrErr.get());\n errs() << \"Running: \" << Arg << \" (\" << Buf->getBufferSize() << \" bytes)\\n\";\n LLVMFuzzerTestOneInput(\n reinterpret_cast(Buf->getBufferStart()),\n Buf->getBufferSize());\n }\n}\nllvm-isel-fuzzer: Weak function invoke the ire of PE\/COFF\/\/===--- DummyFuzzerMain.cpp - Entry point to sanity check the fuzzer -----===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Implementation of main so we can build and test without linking libFuzzer.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/Error.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm;\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size);\nextern \"C\" int LLVMFuzzerInitialize(int *argc, char ***argv);\n\nint main(int argc, char *argv[]) {\n errs() << \"*** This tool was not linked to libFuzzer.\\n\"\n << \"*** No fuzzing will be performed.\\n\";\n if (int RC = LLVMFuzzerInitialize(&argc, &argv)) {\n errs() << \"Initialization failed\\n\";\n return RC;\n }\n\n for (int I = 1; I < argc; ++I) {\n StringRef Arg(argv[I]);\n if (Arg.startswith(\"-\")) {\n if (Arg.equals(\"-ignore_remaining_args=1\"))\n break;\n continue;\n }\n\n auto BufOrErr = MemoryBuffer::getFile(Arg, \/*FileSize-*\/ -1,\n \/*RequiresNullTerminator=*\/false);\n if (std::error_code EC = BufOrErr.getError()) {\n errs() << \"Error reading file: \" << Arg << \": \" << EC.message() << \"\\n\";\n return 1;\n }\n std::unique_ptr Buf = std::move(BufOrErr.get());\n errs() << \"Running: \" << Arg << \" (\" << Buf->getBufferSize() << \" bytes)\\n\";\n LLVMFuzzerTestOneInput(\n reinterpret_cast(Buf->getBufferStart()),\n Buf->getBufferSize());\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"snarkfront.hpp\"\n\nusing namespace snarkfront;\nusing namespace std;\n\nvoid printUsage(const char* exeName) {\n const string\n SHA = \" -b 1|224|256|384|512|512_224|512_256\",\n PAIR = \" -p BN128|Edwards\",\n R = \" -r\",\n DIG = \" -d digest\",\n EQ = \" -e pattern\",\n NEQ = \" -n pattern\",\n optPAIR = \" [-p BN128|Edwards]\",\n optR = \" [-r]\",\n optDIG = \" [-d hex_digest]\",\n optEQ = \" [-e equal_pattern]\",\n optNEQ = \" [-n not_equal_pattern]\";\n\n cout << \"usage: \" << exeName << SHA << optPAIR << optR << optDIG << optEQ << optNEQ << endl\n << endl\n << \"text from standard input:\" << endl\n << \"echo \\\"abc\\\" | \" << exeName << PAIR << SHA << endl\n << endl\n << \"pre-image pattern and hash:\" << endl\n << \"echo \\\"abc\\\" | \" << exeName << PAIR << SHA << DIG << EQ << NEQ << endl\n << endl\n << \"hash only, skip zero knowledge proof:\" << endl\n << \"echo \\\"abc\\\" | \" << exeName << SHA << endl\n << endl\n << \"random data:\" << endl\n << exeName << PAIR << SHA << R << endl;\n\n exit(EXIT_FAILURE);\n}\n\ntemplate \nbool runTest(const bool stdInput,\n const bool hashOnly,\n const string& hashDig,\n const string& eqPattern,\n const string& neqPattern)\n{\n DataBufferStream buf;\n\n if (stdInput) {\n \/\/ fill message block(s) from standard input\n cin >> buf;\n\n ZK_SHA::padMessage(buf);\n\n } else {\n \/\/ fill entire message block with random data\n random_device rd;\n const size_t M = sizeof(typename EVAL_SHA::WordType) \/ sizeof(uint32_t);\n for (size_t i = 0; i < 16 * M; ++i)\n buf->push32(rd());\n\n \/\/ no padding is not SHA-2 standard (compression function only)\n }\n\n if (!hashOnly) {\n \/\/ print buffer\n HexDumper dump(cout);\n dump.print(buf);\n }\n\n \/\/ compute message digest (adds padding if necessary)\n typename ZK_SHA::DigType zk_digest;\n if (eqPattern.empty() && neqPattern.empty()) {\n \/\/ just hash the buffer data\n zk_digest = digest(ZK_SHA(), buf);\n\n } else {\n \/\/ additional constraints on pre-image\n \/\/ must expose buffer as variables\n std::size_t idx = 0;\n\n ZK_SHA hashAlgo;\n\n auto bufCopy = buf;\n while (! bufCopy.empty()) {\n typename ZK_SHA::MsgType msg;\n bless(msg, bufCopy);\n hashAlgo.msgInput(msg);\n\n \/\/ pre-image buffer variables as octets\n typename ZK_SHA::PreType preimg;\n bless(preimg, msg);\n\n PrintHex pr(cout, false);\n\n \/\/ constraints on pre-image, if any\n for (std::size_t i = 0; i < preimg.size(); ++i) {\n \/\/ equal\n if ((idx < eqPattern.size()) && ('?' != eqPattern[idx])) {\n assert_true(preimg[i] == eqPattern[idx]);\n\n cout << \"constrain preimage[\" << idx << \"] == \";\n pr.pushOctet(eqPattern[idx]);\n cout << endl;\n }\n\n \/\/ not equal\n if ((idx < neqPattern.size()) && ('?' != neqPattern[idx])) {\n assert_true(preimg[i] != neqPattern[idx]);\n\n cout << \"constrain preimage[\" << idx << \"] != \";\n pr.pushOctet(neqPattern[idx]);\n cout << endl;\n }\n\n ++idx;\n }\n }\n\n hashAlgo.computeHash();\n zk_digest = hashAlgo.digest();\n }\n\n const auto eval_digest = digest(EVAL_SHA(), buf);\n\n assert(zk_digest.size() == eval_digest.size());\n\n DataBuffer hexpr(cout, false);\n\n \/\/ compare message digest values\n bool ok = true;\n for (size_t i = 0; i < zk_digest.size(); ++i) {\n if (zk_digest[i]->value() != eval_digest[i]) {\n ok = false;\n cout << \"digest[\" << i << \"] error zk: \";\n hexpr.push(zk_digest[i]->value());\n cout << \" eval: \";\n hexpr.push(eval_digest[i]);\n cout << endl;\n }\n }\n\n \/\/ message digest proof constraint\n if (hashDig.empty()) {\n \/\/ hash digest calculated by SHA template\n assert_true(zk_digest == eval_digest);\n\n } else {\n \/\/ hash digest specified as ASCII hex string\n vector v;\n if (!asciiHexToVector(hashDig, v)) {\n ok = false;\n\n } else {\n \/\/ check that hash digest is correct size\n const size_t N = sizeof(typename EVAL_SHA::DigType);\n if (v.size() != N) {\n ok = false;\n cout << \"error: hash digest \" << hashDig\n << \" must be for \" << N << \" octets\"\n << endl;\n\n } else {\n DataBufferStream digBuf(v);\n\n typename ZK_SHA::DigType dig;\n bless(dig, digBuf);\n\n assert_true(zk_digest == dig);\n }\n }\n }\n\n if (!hashOnly) cout << \"digest \";\n cout << asciiHex(eval_digest, !hashOnly) << endl;\n\n return ok;\n}\n\ntemplate \nbool runTest(const string& shaBits,\n const bool stdInput,\n const bool hashOnly,\n const string& hashDig,\n const string& eqPattern,\n const string& neqPattern)\n{\n reset();\n\n bool valueOK = false;\n typedef typename PAIRING::Fr FR;\n\n if (\"1\" == shaBits) {\n valueOK = runTest, eval::SHA1>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n } else if (\"224\" == shaBits) {\n valueOK = runTest, eval::SHA224>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n } else if (\"256\" == shaBits) {\n valueOK = runTest, eval::SHA256>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n } else if (\"384\" == shaBits) {\n valueOK = runTest, eval::SHA384>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n } else if (\"512\" == shaBits) {\n valueOK = runTest, eval::SHA512>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n } else if (\"512_224\" == shaBits) {\n valueOK = runTest, eval::SHA512_224>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n } else if (\"512_256\" == shaBits) {\n valueOK = runTest, eval::SHA512_256>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n }\n\n \/\/ special case for hash only, skip zero knowledge proof\n if (hashOnly) return valueOK;\n\n cout << \"variable count \" << variable_count() << endl;\n\n GenericProgressBar progress1(cerr), progress2(cerr, 50);\n\n cerr << \"generate key pair\";\n const auto key = keypair(progress2);\n cerr << endl;\n\n const auto in = input();\n\n cerr << \"generate proof\";\n const auto p = proof(key, progress2);\n cerr << endl;\n\n cerr << \"verify proof \";\n const bool proofOK = verify(key, in, p, progress1);\n cerr << endl;\n\n return valueOK && proofOK;\n}\n\nint main(int argc, char *argv[])\n{\n Getopt cmdLine(argc, argv, \"pbden\", \"\", \"r\");\n if (!cmdLine || cmdLine.empty()) printUsage(argv[0]);\n\n auto pairing = cmdLine.getString('p');\n\n const auto\n shaBits = cmdLine.getString('b'),\n hashDig = cmdLine.getString('d'),\n eqPattern = cmdLine.getString('e'),\n neqPattern = cmdLine.getString('n');\n\n const auto stdInput = !cmdLine.getFlag('r');\n\n \/\/ special case for hash only, skip zero knowledge proof\n const bool hashOnly = pairing.empty() && validSHA2Name(shaBits) && stdInput;\n if (hashOnly) pairing = \"BN128\"; \/\/ elliptic curve pairing is arbitrary\n\n if (!validPairingName(pairing) || !validSHA2Name(shaBits))\n printUsage(argv[0]);\n\n bool result;\n\n if (pairingBN128(pairing)) {\n \/\/ Barreto-Naehrig 128 bits\n init_BN128();\n result = runTest(shaBits,\n stdInput,\n hashOnly,\n hashDig,\n eqPattern,\n neqPattern);\n\n } else if (pairingEdwards(pairing)) {\n \/\/ Edwards 80 bits\n init_Edwards();\n result = runTest(shaBits,\n stdInput,\n hashOnly,\n hashDig,\n eqPattern,\n neqPattern);\n }\n\n if (!hashOnly) {\n cout << \"test \" << (result ? \"passed\" : \"failed\") << endl;\n }\n\n return EXIT_SUCCESS;\n}\ndistinguish snarkfront.hpp#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"snarkfront.hpp\"\n\nusing namespace snarkfront;\nusing namespace std;\n\nvoid printUsage(const char* exeName) {\n const string\n SHA = \" -b 1|224|256|384|512|512_224|512_256\",\n PAIR = \" -p BN128|Edwards\",\n R = \" -r\",\n DIG = \" -d digest\",\n EQ = \" -e pattern\",\n NEQ = \" -n pattern\",\n optPAIR = \" [-p BN128|Edwards]\",\n optR = \" [-r]\",\n optDIG = \" [-d hex_digest]\",\n optEQ = \" [-e equal_pattern]\",\n optNEQ = \" [-n not_equal_pattern]\";\n\n cout << \"usage: \" << exeName << SHA << optPAIR << optR << optDIG << optEQ << optNEQ << endl\n << endl\n << \"text from standard input:\" << endl\n << \"echo \\\"abc\\\" | \" << exeName << PAIR << SHA << endl\n << endl\n << \"pre-image pattern and hash:\" << endl\n << \"echo \\\"abc\\\" | \" << exeName << PAIR << SHA << DIG << EQ << NEQ << endl\n << endl\n << \"hash only, skip zero knowledge proof:\" << endl\n << \"echo \\\"abc\\\" | \" << exeName << SHA << endl\n << endl\n << \"random data:\" << endl\n << exeName << PAIR << SHA << R << endl;\n\n exit(EXIT_FAILURE);\n}\n\ntemplate \nbool runTest(const bool stdInput,\n const bool hashOnly,\n const string& hashDig,\n const string& eqPattern,\n const string& neqPattern)\n{\n DataBufferStream buf;\n\n if (stdInput) {\n \/\/ fill message block(s) from standard input\n cin >> buf;\n\n ZK_SHA::padMessage(buf);\n\n } else {\n \/\/ fill entire message block with random data\n random_device rd;\n const size_t M = sizeof(typename EVAL_SHA::WordType) \/ sizeof(uint32_t);\n for (size_t i = 0; i < 16 * M; ++i)\n buf->push32(rd());\n\n \/\/ no padding is not SHA-2 standard (compression function only)\n }\n\n if (!hashOnly) {\n \/\/ print buffer\n HexDumper dump(cout);\n dump.print(buf);\n }\n\n \/\/ compute message digest (adds padding if necessary)\n typename ZK_SHA::DigType zk_digest;\n if (eqPattern.empty() && neqPattern.empty()) {\n \/\/ just hash the buffer data\n zk_digest = digest(ZK_SHA(), buf);\n\n } else {\n \/\/ additional constraints on pre-image\n \/\/ must expose buffer as variables\n std::size_t idx = 0;\n\n ZK_SHA hashAlgo;\n\n auto bufCopy = buf;\n while (! bufCopy.empty()) {\n typename ZK_SHA::MsgType msg;\n bless(msg, bufCopy);\n hashAlgo.msgInput(msg);\n\n \/\/ pre-image buffer variables as octets\n typename ZK_SHA::PreType preimg;\n bless(preimg, msg);\n\n PrintHex pr(cout, false);\n\n \/\/ constraints on pre-image, if any\n for (std::size_t i = 0; i < preimg.size(); ++i) {\n \/\/ equal\n if ((idx < eqPattern.size()) && ('?' != eqPattern[idx])) {\n assert_true(preimg[i] == eqPattern[idx]);\n\n cout << \"constrain preimage[\" << idx << \"] == \";\n pr.pushOctet(eqPattern[idx]);\n cout << endl;\n }\n\n \/\/ not equal\n if ((idx < neqPattern.size()) && ('?' != neqPattern[idx])) {\n assert_true(preimg[i] != neqPattern[idx]);\n\n cout << \"constrain preimage[\" << idx << \"] != \";\n pr.pushOctet(neqPattern[idx]);\n cout << endl;\n }\n\n ++idx;\n }\n }\n\n hashAlgo.computeHash();\n zk_digest = hashAlgo.digest();\n }\n\n const auto eval_digest = digest(EVAL_SHA(), buf);\n\n assert(zk_digest.size() == eval_digest.size());\n\n DataBuffer hexpr(cout, false);\n\n \/\/ compare message digest values\n bool ok = true;\n for (size_t i = 0; i < zk_digest.size(); ++i) {\n if (zk_digest[i]->value() != eval_digest[i]) {\n ok = false;\n cout << \"digest[\" << i << \"] error zk: \";\n hexpr.push(zk_digest[i]->value());\n cout << \" eval: \";\n hexpr.push(eval_digest[i]);\n cout << endl;\n }\n }\n\n \/\/ message digest proof constraint\n if (hashDig.empty()) {\n \/\/ hash digest calculated by SHA template\n assert_true(zk_digest == eval_digest);\n\n } else {\n \/\/ hash digest specified as ASCII hex string\n vector v;\n if (!asciiHexToVector(hashDig, v)) {\n ok = false;\n\n } else {\n \/\/ check that hash digest is correct size\n const size_t N = sizeof(typename EVAL_SHA::DigType);\n if (v.size() != N) {\n ok = false;\n cout << \"error: hash digest \" << hashDig\n << \" must be for \" << N << \" octets\"\n << endl;\n\n } else {\n DataBufferStream digBuf(v);\n\n typename ZK_SHA::DigType dig;\n bless(dig, digBuf);\n\n assert_true(zk_digest == dig);\n }\n }\n }\n\n if (!hashOnly) cout << \"digest \";\n cout << asciiHex(eval_digest, !hashOnly) << endl;\n\n return ok;\n}\n\ntemplate \nbool runTest(const string& shaBits,\n const bool stdInput,\n const bool hashOnly,\n const string& hashDig,\n const string& eqPattern,\n const string& neqPattern)\n{\n reset();\n\n bool valueOK = false;\n typedef typename PAIRING::Fr FR;\n\n if (\"1\" == shaBits) {\n valueOK = runTest, eval::SHA1>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n } else if (\"224\" == shaBits) {\n valueOK = runTest, eval::SHA224>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n } else if (\"256\" == shaBits) {\n valueOK = runTest, eval::SHA256>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n } else if (\"384\" == shaBits) {\n valueOK = runTest, eval::SHA384>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n } else if (\"512\" == shaBits) {\n valueOK = runTest, eval::SHA512>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n } else if (\"512_224\" == shaBits) {\n valueOK = runTest, eval::SHA512_224>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n } else if (\"512_256\" == shaBits) {\n valueOK = runTest, eval::SHA512_256>(stdInput, hashOnly,\n hashDig, eqPattern, neqPattern);\n }\n\n \/\/ special case for hash only, skip zero knowledge proof\n if (hashOnly) return valueOK;\n\n cout << \"variable count \" << variable_count() << endl;\n\n GenericProgressBar progress1(cerr), progress2(cerr, 50);\n\n cerr << \"generate key pair\";\n const auto key = keypair(progress2);\n cerr << endl;\n\n const auto in = input();\n\n cerr << \"generate proof\";\n const auto p = proof(key, progress2);\n cerr << endl;\n\n cerr << \"verify proof \";\n const bool proofOK = verify(key, in, p, progress1);\n cerr << endl;\n\n return valueOK && proofOK;\n}\n\nint main(int argc, char *argv[])\n{\n Getopt cmdLine(argc, argv, \"pbden\", \"\", \"r\");\n if (!cmdLine || cmdLine.empty()) printUsage(argv[0]);\n\n auto pairing = cmdLine.getString('p');\n\n const auto\n shaBits = cmdLine.getString('b'),\n hashDig = cmdLine.getString('d'),\n eqPattern = cmdLine.getString('e'),\n neqPattern = cmdLine.getString('n');\n\n const auto stdInput = !cmdLine.getFlag('r');\n\n \/\/ special case for hash only, skip zero knowledge proof\n const bool hashOnly = pairing.empty() && validSHA2Name(shaBits) && stdInput;\n if (hashOnly) pairing = \"BN128\"; \/\/ elliptic curve pairing is arbitrary\n\n if (!validPairingName(pairing) || !validSHA2Name(shaBits))\n printUsage(argv[0]);\n\n bool result;\n\n if (pairingBN128(pairing)) {\n \/\/ Barreto-Naehrig 128 bits\n init_BN128();\n result = runTest(shaBits,\n stdInput,\n hashOnly,\n hashDig,\n eqPattern,\n neqPattern);\n\n } else if (pairingEdwards(pairing)) {\n \/\/ Edwards 80 bits\n init_Edwards();\n result = runTest(shaBits,\n stdInput,\n hashOnly,\n hashDig,\n eqPattern,\n neqPattern);\n }\n\n if (!hashOnly) {\n cout << \"test \" << (result ? \"passed\" : \"failed\") << endl;\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*!\n*\t@file\tpsalm.cpp\n*\t@brief\tMain file for \"psalm\"\n*\n*\t\"psalm\" (Pretty Subdivision ALgorithms on Meshes) is a CLI tool that\n*\timplements the Doo-Sabin and Catmull-Clark subdivision schemes.\n*\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"mesh.h\"\n\nusing namespace std;\n\nmesh scene_mesh;\nstring input;\nstring output;\n\n\/*!\n*\tShows usage information for the program.\n*\/\n\nvoid show_usage()\n{\n\tcout\t<< \"psalm\\n\\n\"\n\t\t<< \"Usage: psalm [arguments] [file...]\\n\\n\"\n\t\t<< \"Arguments:\\n\\n\"\n\t\t<< \"-a, --algorithm \\tSelect subdivision algorithm to use on the\\n\"\n\t\t<< \"\\t\\t\\t\\tinput mesh. Valid values for are:\\n\\n\"\n\t\t<< \"\\t\\t\\t\\t\\t* catmull-clark, catmull, clark, cc\\n\"\n\t\t<< \"\\t\\t\\t\\t\\t* doo-sabin, doo, sabin, ds\\n\"\n\t\t<< \"\\t\\t\\t\\t\\t* loop, l\\n\\n\"\n\t\t<< \"\\t\\t\\t\\tDefault algorithm: Catmull-Clark\\n\\n\"\n\t\t<< \"-t, --type \\t\\tSelect type of input data. Valid values for\\n\"\n\t\t<< \"\\t\\t\\t\\tthe parameter are:\\n\\n\"\n\t\t<< \"\\t\\t\\t\\t\\t* ply (Standford PLY files)\\n\"\n\t\t<< \"\\t\\t\\t\\t\\t* obj (Wavefront OBJ files)\\n\"\n\t\t<< \"\\t\\t\\t\\t\\t* off (Geomview object files)\\n\\n\"\n\t\t<< \"-i, --ignore \\tIgnore any face whose number of sides matches\\n\"\n\t\t<< \"\\t\\t\\t\\tone of the numbers in the list. Use commas to\\n\"\n\t\t<< \"\\t\\t\\t\\tseparate list values.\\n\\n\"\n\t\t<< \"-o, --output \\t\\tSet output file\\n\\n\"\n\t\t<< \"-n, --steps \\t\\t\\tSet number of subdivision steps to perform on\\n\"\n\t\t<< \"\\t\\t\\t\\tthe input mesh.\\n\\n\"\n\t\t<< \"\\t\\t\\t\\tDefault value: 0\\n\\n\"\n\t\t<< \"-h, --help\\t\\t\\tShow this screen\\n\"\n\t\t<< \"\\n\";\n}\n\n\/*!\n*\tHandles user interaction.\n*\n*\t@param argc Number of command-line arguments\n*\t@param argv Vector of command-line arguments\n*\/\n\nint main(int argc, char* argv[])\n{\n\tstatic option cmd_line_opts[] =\n\t{\n\t\t{\"output\",\trequired_argument,\tNULL,\t'o'},\n\t\t{\"steps\",\trequired_argument,\tNULL,\t'n'},\n\t\t{\"type\",\trequired_argument,\tNULL,\t't'},\n\t\t{\"ignore\",\trequired_argument,\tNULL,\t'i'},\n\t\t{\"algorithm\",\trequired_argument,\tNULL,\t'a'},\n\n\t\t{\"help\",\tno_argument,\t\tNULL,\t'h'},\n\n\t\t{NULL, 0, NULL, 0}\n\t};\n\n\tshort type\t= mesh::TYPE_EXT;\n\tshort algorithm\t= mesh::ALG_CATMULL_CLARK;\n\n\tstd::set ignore_faces;\n\n\tsize_t steps\t= 0;\n\n\tint option = 0;\n\twhile((option = getopt_long(argc, argv, \"o:n:i:t:a:h\", cmd_line_opts, NULL)) != -1)\n\t{\n\t\tswitch(option)\n\t\t{\n\t\t\tcase 'o':\n\t\t\t\toutput = optarg;\n\t\t\t\tbreak;\n\n\t\t\tcase 't':\n\t\t\t{\n\t\t\t\tstring type_str = optarg;\n\t\t\t\ttransform(type_str.begin(), type_str.end(), type_str.begin(), (int(*)(int)) tolower);\n\n\t\t\t\tif(type_str == \"ply\")\n\t\t\t\t\ttype = mesh::TYPE_PLY;\n\t\t\t\telse if(type_str == \"obj\")\n\t\t\t\t\ttype = mesh::TYPE_OBJ;\n\t\t\t\telse if(type_str == \"off\")\n\t\t\t\t\ttype = mesh::TYPE_OFF;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcerr << \"Error: \\\"\" << type_str << \"\\\" is an unknown mesh data type.\\n\";\n\t\t\t\t\tshow_usage();\n\t\t\t\t\treturn(-1);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'a':\n\t\t\t{\n\t\t\t\tstring algorithm_str = optarg;\n\t\t\t\ttransform(algorithm_str.begin(), algorithm_str.end(), algorithm_str.begin(), (int(*)(int)) tolower);\n\n\t\t\t\tif(\talgorithm_str == \"catmull-clark\"\t||\n\t\t\t\t\talgorithm_str == \"catmull\"\t\t||\n\t\t\t\t\talgorithm_str == \"clark\"\t\t||\n\t\t\t\t\talgorithm_str == \"cc\")\n\t\t\t\t\talgorithm = mesh::ALG_CATMULL_CLARK;\n\t\t\t\telse if(algorithm_str == \"doo-sabin\"\t\t||\n\t\t\t\t\talgorithm_str == \"doo\"\t\t\t||\n\t\t\t\t\talgorithm_str == \"sabin\"\t\t||\n\t\t\t\t\talgorithm_str == \"ds\")\n\t\t\t\t\talgorithm = mesh::ALG_DOO_SABIN;\n\t\t\t\telse if(algorithm_str == \"loop\"\t||\n\t\t\t\t\talgorithm_str == \"l\")\n\t\t\t\t\talgorithm = mesh::ALG_LOOP;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcerr << \"Error: \\\"\" << algorithm_str << \"\\\" is an unknown algorithm.\\n\";\n\t\t\t\t\tshow_usage();\n\t\t\t\t\treturn(-1);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'i':\n\t\t\t{\n\t\t\t\tstd::istringstream ignore_faces_str(optarg);\n\t\t\t\tstd::istringstream converter;\n\t\t\t\tstd::string val_str;\n\t\t\t\twhile(getline(ignore_faces_str, val_str, ','))\n\t\t\t\t{\n\t\t\t\t\tconverter.clear();\n\t\t\t\t\tconverter.str(val_str);\n\n\t\t\t\t\tsize_t value;\n\t\t\t\t\tconverter >> value;\n\t\t\t\t\tif(converter.fail())\n\t\t\t\t\t{\n\t\t\t\t\t\tshow_usage();\n\t\t\t\t\t\tcerr << \"psalm: Unable to convert \\\"\" << val_str << \"\\\" to a number.\\n\";\n\t\t\t\t\t\treturn(-1);\n\t\t\t\t\t}\n\n\t\t\t\t\tignore_faces.insert(value);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'n':\n\t\t\t{\n\t\t\t\tistringstream converter(optarg);\n\t\t\t\tconverter >> steps;\n\t\t\t\tif(converter.fail())\n\t\t\t\t{\n\t\t\t\t\tcerr << \"Error: Unable to convert \\\"\" << optarg << \"\\\" to a number.\\n\";\n\t\t\t\t\tshow_usage();\n\t\t\t\t\treturn(-1);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'h':\n\t\t\tcase '?':\n\t\t\t\tshow_usage();\n\t\t\t\treturn(0);\n\t\t}\n\t}\n\n\t\/\/ Read further command-line parameters; these are all supposed to be\n\t\/\/ input files. If the user already specified an output file, only one\n\t\/\/ input file will be accepted.\n\n\tvector files;\n\twhile(optind < argc)\n\t{\n\t\tfiles.push_back(argv[optind++]);\n\t\tif(output.length() != 0 && files.size() > 1)\n\t\t{\n\t\t\tcerr << \"Error: Output file specified, but more than one input file present.\\n\";\n\t\t\treturn(-1);\n\t\t}\n\t}\n\n\t\/\/ Replace the special file \"-\" by an empty string, thereby signalling\n\t\/\/ that standard input and standard output are to be used as file\n\t\/\/ streams.\n\n\tfor(vector::iterator it = files.begin(); it != files.end(); it++)\n\t{\n\t\tif(it->length() == 1 && (*it)[0] == '-')\n\t\t\t*it = \"\";\n\t}\n\n\tbool output_set = (output.length() > 0);\n\tif(output.length() == 1 && output[0] == '-')\n\t\toutput = \"\";\n\n\t\/\/ Try to read from STDIN if no input files have been specified\n\tif(files.size() == 0)\n\t\tfiles.push_back(\"\");\n\n\t\/\/ Apply subdivision algorithm to all files\n\n\tfor(vector::iterator it = files.begin(); it != files.end(); it++)\n\t{\n\t\tscene_mesh.load(*it, type);\n\t\tscene_mesh.subdivide(algorithm, steps);\n\t\tscene_mesh.prune(ignore_faces);\n\n\t\t\/\/ If an output file has been set (even if it is empty), it\n\t\t\/\/ will be used.\n\t\tif(output_set)\n\t\t\tscene_mesh.save(output, type);\n\n\t\t\/\/ If no output file has been set and the input file name is\n\t\t\/\/ not empty, the output will be written to a file.\n\t\telse if(it->length() > 0)\n\t\t{\n\t\t\tsize_t ext_pos = (*it).find_last_of(\".\");\n\t\t\tif(ext_pos == string::npos)\n\t\t\t\tscene_mesh.save(*it+\".subdivided\", type);\n\t\t\telse\n\t\t\t\tscene_mesh.save( (*it).substr(0, ext_pos) + \"_subdivided\"\n\t\t\t\t\t\t+(*it).substr(ext_pos));\n\t\t}\n\n\t\t\/\/ If no output file has been set and the input file name is\n\t\t\/\/ empty, the output will be written to STDOUT.\n\t\telse\n\t\t\tscene_mesh.save(\"\", type);\n\t}\n\n\treturn(0);\n}\nRemoved usage information in case of errors\/*!\n*\t@file\tpsalm.cpp\n*\t@brief\tMain file for \"psalm\"\n*\n*\t\"psalm\" (Pretty Subdivision ALgorithms on Meshes) is a CLI tool that\n*\timplements the Doo-Sabin and Catmull-Clark subdivision schemes.\n*\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"mesh.h\"\n\nusing namespace std;\n\nmesh scene_mesh;\nstring input;\nstring output;\n\n\/*!\n*\tShows usage information for the program.\n*\/\n\nvoid show_usage()\n{\n\tcout\t<< \"psalm\\n\\n\"\n\t\t<< \"Usage: psalm [arguments] [file...]\\n\\n\"\n\t\t<< \"Arguments:\\n\\n\"\n\t\t<< \"-a, --algorithm \\tSelect subdivision algorithm to use on the\\n\"\n\t\t<< \"\\t\\t\\t\\tinput mesh. Valid values for are:\\n\\n\"\n\t\t<< \"\\t\\t\\t\\t\\t* catmull-clark, catmull, clark, cc\\n\"\n\t\t<< \"\\t\\t\\t\\t\\t* doo-sabin, doo, sabin, ds\\n\"\n\t\t<< \"\\t\\t\\t\\t\\t* loop, l\\n\\n\"\n\t\t<< \"\\t\\t\\t\\tDefault algorithm: Catmull-Clark\\n\\n\"\n\t\t<< \"-t, --type \\t\\tSelect type of input data. Valid values for\\n\"\n\t\t<< \"\\t\\t\\t\\tthe parameter are:\\n\\n\"\n\t\t<< \"\\t\\t\\t\\t\\t* ply (Standford PLY files)\\n\"\n\t\t<< \"\\t\\t\\t\\t\\t* obj (Wavefront OBJ files)\\n\"\n\t\t<< \"\\t\\t\\t\\t\\t* off (Geomview object files)\\n\\n\"\n\t\t<< \"-i, --ignore \\tIgnore any face whose number of sides matches\\n\"\n\t\t<< \"\\t\\t\\t\\tone of the numbers in the list. Use commas to\\n\"\n\t\t<< \"\\t\\t\\t\\tseparate list values.\\n\\n\"\n\t\t<< \"-o, --output \\t\\tSet output file\\n\\n\"\n\t\t<< \"-n, --steps \\t\\t\\tSet number of subdivision steps to perform on\\n\"\n\t\t<< \"\\t\\t\\t\\tthe input mesh.\\n\\n\"\n\t\t<< \"\\t\\t\\t\\tDefault value: 0\\n\\n\"\n\t\t<< \"-h, --help\\t\\t\\tShow this screen\\n\"\n\t\t<< \"\\n\";\n}\n\n\/*!\n*\tHandles user interaction.\n*\n*\t@param argc Number of command-line arguments\n*\t@param argv Vector of command-line arguments\n*\/\n\nint main(int argc, char* argv[])\n{\n\tstatic option cmd_line_opts[] =\n\t{\n\t\t{\"output\",\trequired_argument,\tNULL,\t'o'},\n\t\t{\"steps\",\trequired_argument,\tNULL,\t'n'},\n\t\t{\"type\",\trequired_argument,\tNULL,\t't'},\n\t\t{\"ignore\",\trequired_argument,\tNULL,\t'i'},\n\t\t{\"algorithm\",\trequired_argument,\tNULL,\t'a'},\n\n\t\t{\"help\",\tno_argument,\t\tNULL,\t'h'},\n\n\t\t{NULL, 0, NULL, 0}\n\t};\n\n\tshort type\t= mesh::TYPE_EXT;\n\tshort algorithm\t= mesh::ALG_CATMULL_CLARK;\n\n\tstd::set ignore_faces;\n\n\tsize_t steps\t= 0;\n\n\tint option = 0;\n\twhile((option = getopt_long(argc, argv, \"o:n:i:t:a:h\", cmd_line_opts, NULL)) != -1)\n\t{\n\t\tswitch(option)\n\t\t{\n\t\t\tcase 'o':\n\t\t\t\toutput = optarg;\n\t\t\t\tbreak;\n\n\t\t\tcase 't':\n\t\t\t{\n\t\t\t\tstring type_str = optarg;\n\t\t\t\ttransform(type_str.begin(), type_str.end(), type_str.begin(), (int(*)(int)) tolower);\n\n\t\t\t\tif(type_str == \"ply\")\n\t\t\t\t\ttype = mesh::TYPE_PLY;\n\t\t\t\telse if(type_str == \"obj\")\n\t\t\t\t\ttype = mesh::TYPE_OBJ;\n\t\t\t\telse if(type_str == \"off\")\n\t\t\t\t\ttype = mesh::TYPE_OFF;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcerr << \"psalm: \\\"\" << type_str << \"\\\" is an unknown mesh data type.\\n\";\n\t\t\t\t\treturn(-1);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'a':\n\t\t\t{\n\t\t\t\tstring algorithm_str = optarg;\n\t\t\t\ttransform(algorithm_str.begin(), algorithm_str.end(), algorithm_str.begin(), (int(*)(int)) tolower);\n\n\t\t\t\tif(\talgorithm_str == \"catmull-clark\"\t||\n\t\t\t\t\talgorithm_str == \"catmull\"\t\t||\n\t\t\t\t\talgorithm_str == \"clark\"\t\t||\n\t\t\t\t\talgorithm_str == \"cc\")\n\t\t\t\t\talgorithm = mesh::ALG_CATMULL_CLARK;\n\t\t\t\telse if(algorithm_str == \"doo-sabin\"\t\t||\n\t\t\t\t\talgorithm_str == \"doo\"\t\t\t||\n\t\t\t\t\talgorithm_str == \"sabin\"\t\t||\n\t\t\t\t\talgorithm_str == \"ds\")\n\t\t\t\t\talgorithm = mesh::ALG_DOO_SABIN;\n\t\t\t\telse if(algorithm_str == \"loop\"\t||\n\t\t\t\t\talgorithm_str == \"l\")\n\t\t\t\t\talgorithm = mesh::ALG_LOOP;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcerr << \"psalm: \\\"\" << algorithm_str << \"\\\" is an unknown algorithm.\\n\";\n\t\t\t\t\treturn(-1);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'i':\n\t\t\t{\n\t\t\t\tstd::istringstream ignore_faces_str(optarg);\n\t\t\t\tstd::istringstream converter;\n\t\t\t\tstd::string val_str;\n\t\t\t\twhile(getline(ignore_faces_str, val_str, ','))\n\t\t\t\t{\n\t\t\t\t\tconverter.clear();\n\t\t\t\t\tconverter.str(val_str);\n\n\t\t\t\t\tsize_t value;\n\t\t\t\t\tconverter >> value;\n\t\t\t\t\tif(converter.fail())\n\t\t\t\t\t{\n\t\t\t\t\t\tcerr << \"psalm: Unable to convert \\\"\" << val_str << \"\\\" to a number.\\n\";\n\t\t\t\t\t\treturn(-1);\n\t\t\t\t\t}\n\n\t\t\t\t\tignore_faces.insert(value);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'n':\n\t\t\t{\n\t\t\t\tistringstream converter(optarg);\n\t\t\t\tconverter >> steps;\n\t\t\t\tif(converter.fail())\n\t\t\t\t{\n\t\t\t\t\tcerr << \"psalm: Unable to convert \\\"\" << optarg << \"\\\" to a number.\\n\";\n\t\t\t\t\treturn(-1);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'h':\n\t\t\tcase '?':\n\t\t\t\tshow_usage();\n\t\t\t\treturn(0);\n\t\t}\n\t}\n\n\t\/\/ Read further command-line parameters; these are all supposed to be\n\t\/\/ input files. If the user already specified an output file, only one\n\t\/\/ input file will be accepted.\n\n\tvector files;\n\twhile(optind < argc)\n\t{\n\t\tfiles.push_back(argv[optind++]);\n\t\tif(output.length() != 0 && files.size() > 1)\n\t\t{\n\t\t\tcerr << \"psalm: Output file specified, but more than one input file present.\\n\";\n\t\t\treturn(-1);\n\t\t}\n\t}\n\n\t\/\/ Replace the special file \"-\" by an empty string, thereby signalling\n\t\/\/ that standard input and standard output are to be used as file\n\t\/\/ streams.\n\n\tfor(vector::iterator it = files.begin(); it != files.end(); it++)\n\t{\n\t\tif(it->length() == 1 && (*it)[0] == '-')\n\t\t\t*it = \"\";\n\t}\n\n\tbool output_set = (output.length() > 0);\n\tif(output.length() == 1 && output[0] == '-')\n\t\toutput = \"\";\n\n\t\/\/ Try to read from STDIN if no input files have been specified\n\tif(files.size() == 0)\n\t\tfiles.push_back(\"\");\n\n\t\/\/ Apply subdivision algorithm to all files\n\n\tfor(vector::iterator it = files.begin(); it != files.end(); it++)\n\t{\n\t\tscene_mesh.load(*it, type);\n\t\tscene_mesh.subdivide(algorithm, steps);\n\t\tscene_mesh.prune(ignore_faces);\n\n\t\t\/\/ If an output file has been set (even if it is empty), it\n\t\t\/\/ will be used.\n\t\tif(output_set)\n\t\t\tscene_mesh.save(output, type);\n\n\t\t\/\/ If no output file has been set and the input file name is\n\t\t\/\/ not empty, the output will be written to a file.\n\t\telse if(it->length() > 0)\n\t\t{\n\t\t\tsize_t ext_pos = (*it).find_last_of(\".\");\n\t\t\tif(ext_pos == string::npos)\n\t\t\t\tscene_mesh.save(*it+\".subdivided\", type);\n\t\t\telse\n\t\t\t\tscene_mesh.save( (*it).substr(0, ext_pos) + \"_subdivided\"\n\t\t\t\t\t\t+(*it).substr(ext_pos));\n\t\t}\n\n\t\t\/\/ If no output file has been set and the input file name is\n\t\t\/\/ empty, the output will be written to STDOUT.\n\t\telse\n\t\t\tscene_mesh.save(\"\", type);\n\t}\n\n\treturn(0);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2018 Kenton Varda and contributors\n\/\/ Licensed under the MIT License:\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"json-rpc.h\"\n#include \n#include \n\nnamespace capnp {\n\nstatic constexpr uint64_t JSON_NAME_ANNOTATION_ID = 0xfa5b1fd61c2e7c3dull;\nstatic constexpr uint64_t JSON_NOTIFICATION_ANNOTATION_ID = 0xa0a054dea32fd98cull;\n\nclass JsonRpc::CapabilityImpl final: public DynamicCapability::Server {\npublic:\n CapabilityImpl(JsonRpc& parent, InterfaceSchema schema)\n : DynamicCapability::Server(schema), parent(parent) {}\n\n kj::Promise call(InterfaceSchema::Method method,\n CallContext context) override {\n auto proto = method.getProto();\n bool isNotification = false;\n kj::StringPtr name = proto.getName();\n for (auto annotation: proto.getAnnotations()) {\n switch (annotation.getId()) {\n case JSON_NAME_ANNOTATION_ID:\n name = annotation.getValue().getText();\n break;\n case JSON_NOTIFICATION_ANNOTATION_ID:\n isNotification = true;\n break;\n }\n }\n\n capnp::MallocMessageBuilder message;\n auto value = message.getRoot();\n auto list = value.initObject(3 + !isNotification);\n\n uint index = 0;\n\n auto jsonrpc = list[index++];\n jsonrpc.setName(\"jsonrpc\");\n jsonrpc.initValue().setString(\"2.0\");\n\n uint callId = parent.callCount++;\n\n if (!isNotification) {\n auto id = list[index++];\n id.setName(\"id\");\n id.initValue().setNumber(callId);\n }\n\n auto methodName = list[index++];\n methodName.setName(\"method\");\n methodName.initValue().setString(name);\n\n auto params = list[index++];\n params.setName(\"params\");\n parent.codec.encode(context.getParams(), params.initValue());\n\n auto writePromise = parent.queueWrite(parent.codec.encode(value));\n\n if (isNotification) {\n auto sproto = context.getResultsType().getProto().getStruct();\n MessageSize size { sproto.getDataWordCount(), sproto.getPointerCount() };\n context.initResults(size);\n return kj::mv(writePromise);\n } else {\n auto paf = kj::newPromiseAndFulfiller();\n parent.awaitedResponses.insert(callId, AwaitedResponse { context, kj::mv(paf.fulfiller) });\n auto promise = writePromise.then([p = kj::mv(paf.promise)]() mutable { return kj::mv(p); });\n auto& parentRef = parent;\n return promise.attach(kj::defer([&parentRef,callId]() {\n parentRef.awaitedResponses.erase(callId);\n }));\n }\n }\n\nprivate:\n JsonRpc& parent;\n};\n\nJsonRpc::JsonRpc(Transport& transport, DynamicCapability::Client interface)\n : JsonRpc(transport, kj::mv(interface), kj::newPromiseAndFulfiller()) {}\nJsonRpc::JsonRpc(Transport& transport, DynamicCapability::Client interfaceParam,\n kj::PromiseFulfillerPair paf)\n : transport(transport),\n interface(kj::mv(interfaceParam)),\n errorPromise(paf.promise.fork()),\n errorFulfiller(kj::mv(paf.fulfiller)),\n readTask(readLoop().eagerlyEvaluate([this](kj::Exception&& e) {\n errorFulfiller->reject(kj::mv(e));\n })),\n tasks(*this) {\n codec.handleByAnnotation(interface.getSchema());\n codec.handleByAnnotation();\n\n for (auto method: interface.getSchema().getMethods()) {\n auto proto = method.getProto();\n kj::StringPtr name = proto.getName();\n for (auto annotation: proto.getAnnotations()) {\n switch (annotation.getId()) {\n case JSON_NAME_ANNOTATION_ID:\n name = annotation.getValue().getText();\n break;\n }\n }\n methodMap.insert(name, method);\n }\n}\n\nDynamicCapability::Client JsonRpc::getPeer(InterfaceSchema schema) {\n codec.handleByAnnotation(interface.getSchema());\n return kj::heap(*this, schema);\n}\n\nstatic kj::HttpHeaderTable& staticHeaderTable() {\n static kj::HttpHeaderTable HEADER_TABLE;\n return HEADER_TABLE;\n}\n\nkj::Promise JsonRpc::queueWrite(kj::String text) {\n auto fork = writeQueue.then([this, text = kj::mv(text)]() mutable {\n auto promise = transport.send(text);\n return promise.attach(kj::mv(text));\n }).eagerlyEvaluate([this](kj::Exception&& e) {\n errorFulfiller->reject(kj::mv(e));\n }).fork();\n writeQueue = fork.addBranch();\n return fork.addBranch();\n}\n\nvoid JsonRpc::queueError(kj::Maybe id, int code, kj::StringPtr message) {\n MallocMessageBuilder capnpMessage;\n auto jsonResponse = capnpMessage.getRoot();\n jsonResponse.setJsonrpc(\"2.0\");\n KJ_IF_MAYBE(i, id) {\n jsonResponse.setId(*i);\n } else {\n jsonResponse.initId().setNull();\n }\n auto error = jsonResponse.initError();\n error.setCode(code);\n error.setMessage(message);\n\n \/\/ OK to discard result of queueWrite() since it's just one branch of a fork.\n queueWrite(codec.encode(jsonResponse));\n}\n\nkj::Promise JsonRpc::readLoop() {\n return transport.receive().then([this](kj::String message) -> kj::Promise {\n MallocMessageBuilder capnpMessage;\n auto rpcMessageBuilder = capnpMessage.getRoot();\n\n KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {\n codec.decode(message, rpcMessageBuilder);\n })) {\n queueError(nullptr, -32700, kj::str(\"Parse error: \", exception->getDescription()));\n return readLoop();\n }\n\n KJ_CONTEXT(\"decoding JSON-RPC message\", message);\n\n auto rpcMessage = rpcMessageBuilder.asReader();\n\n if (!rpcMessage.hasJsonrpc()) {\n queueError(nullptr, -32700, kj::str(\"Missing 'jsonrpc' field.\"));\n return readLoop();\n } else if (rpcMessage.getJsonrpc() != \"2.0\") {\n queueError(nullptr, -32700,\n kj::str(\"Unknown JSON-RPC version. This peer implements version '2.0'.\"));\n return readLoop();\n }\n\n switch (rpcMessage.which()) {\n case json::RpcMessage::NONE:\n queueError(nullptr, -32700, kj::str(\"message has none of params, result, or error\"));\n break;\n\n case json::RpcMessage::PARAMS: {\n \/\/ a call\n auto schema = interface.getSchema();\n KJ_IF_MAYBE(method, schema.findMethodByName(rpcMessage.getMethod())) {\n auto req = interface.newRequest(*method);\n KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {\n codec.decode(rpcMessage.getParams(), req);\n })) {\n kj::Maybe id;\n if (rpcMessage.hasId()) id = rpcMessage.getId();\n queueError(id, -32602,\n kj::str(\"Type error in method params: \", exception->getDescription()));\n break;\n }\n\n if (rpcMessage.hasId()) {\n auto id = rpcMessage.getId();\n auto idCopy = kj::heapArray(id.totalSize().wordCount + 1);\n memset(idCopy.begin(), 0, idCopy.asBytes().size());\n copyToUnchecked(id, idCopy);\n auto idPtr = readMessageUnchecked(idCopy.begin());\n\n auto promise = req.send()\n .then([this,idPtr](Response response) mutable {\n MallocMessageBuilder capnpMessage;\n auto jsonResponse = capnpMessage.getRoot();\n jsonResponse.setJsonrpc(\"2.0\");\n jsonResponse.setId(idPtr);\n codec.encode(DynamicStruct::Reader(response), jsonResponse.initResult());\n return queueWrite(codec.encode(jsonResponse));\n }, [this,idPtr](kj::Exception&& e) {\n MallocMessageBuilder capnpMessage;\n auto jsonResponse = capnpMessage.getRoot();\n jsonResponse.setJsonrpc(\"2.0\");\n jsonResponse.setId(idPtr);\n auto error = jsonResponse.initError();\n switch (e.getType()) {\n case kj::Exception::Type::FAILED:\n error.setCode(-32000);\n break;\n case kj::Exception::Type::DISCONNECTED:\n error.setCode(-32001);\n break;\n case kj::Exception::Type::OVERLOADED:\n error.setCode(-32002);\n break;\n case kj::Exception::Type::UNIMPLEMENTED:\n error.setCode(-32601); \/\/ method not found\n break;\n }\n error.setMessage(e.getDescription());\n return queueWrite(codec.encode(jsonResponse));\n });\n tasks.add(promise.attach(kj::mv(idCopy)));\n } else {\n \/\/ No 'id', so this is a notification.\n tasks.add(req.send().ignoreResult().catch_([](kj::Exception&& exception) {\n if (exception.getType() != kj::Exception::Type::UNIMPLEMENTED) {\n KJ_LOG(ERROR, \"JSON-RPC notification threw exception into the abyss\", exception);\n }\n }));\n }\n } else {\n if (rpcMessage.hasId()) {\n queueError(rpcMessage.getId(), -32601, \"Method not found\");\n } else {\n \/\/ Ignore notification for unknown method.\n }\n }\n break;\n }\n\n case json::RpcMessage::RESULT: {\n auto id = rpcMessage.getId();\n if (!id.isNumber()) {\n \/\/ JSON-RPC doesn't define what to do if receiving a response with an invalid id.\n KJ_LOG(ERROR, \"JSON-RPC response has invalid ID\");\n } else KJ_IF_MAYBE(awaited, awaitedResponses.find((uint)id.getNumber())) {\n KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {\n codec.decode(rpcMessage.getResult(), awaited->context.getResults());\n awaited->fulfiller->fulfill();\n })) {\n \/\/ Errors always propagate from callee to caller, so we don't want to throw this error\n \/\/ back to the server.\n awaited->fulfiller->reject(kj::mv(*exception));\n }\n } else {\n \/\/ Probably, this is the response to a call that was canceled.\n }\n break;\n }\n\n case json::RpcMessage::ERROR: {\n auto id = rpcMessage.getId();\n if (id.isNull()) {\n \/\/ Error message will be logged by KJ_CONTEXT, above.\n KJ_LOG(ERROR, \"peer reports JSON-RPC protocol error\");\n } else if (!id.isNumber()) {\n \/\/ JSON-RPC doesn't define what to do if receiving a response with an invalid id.\n KJ_LOG(ERROR, \"JSON-RPC response has invalid ID\");\n } else KJ_IF_MAYBE(awaited, awaitedResponses.find((uint)id.getNumber())) {\n auto error = rpcMessage.getError();\n auto code = error.getCode();\n kj::Exception::Type type =\n code == -32601 ? kj::Exception::Type::UNIMPLEMENTED\n : kj::Exception::Type::FAILED;\n awaited->fulfiller->reject(kj::Exception(\n type, __FILE__, __LINE__, kj::str(error.getMessage())));\n } else {\n \/\/ Probably, this is the response to a call that was canceled.\n }\n break;\n }\n }\n\n return readLoop();\n });\n}\n\nvoid JsonRpc::taskFailed(kj::Exception&& exception) {\n errorFulfiller->reject(kj::mv(exception));\n}\n\n\/\/ =======================================================================================\n\nJsonRpc::ContentLengthTransport::ContentLengthTransport(kj::AsyncIoStream& stream)\n : stream(stream), input(kj::newHttpInputStream(stream, staticHeaderTable())) {}\nJsonRpc::ContentLengthTransport::~ContentLengthTransport() noexcept(false) {}\n\nkj::Promise JsonRpc::ContentLengthTransport::send(kj::StringPtr text) {\n auto headers = kj::str(\"Content-Length: \", text.size(), \"\\r\\n\\r\\n\");\n parts[0] = headers.asBytes();\n parts[1] = text.asBytes();\n return stream.write(parts).attach(kj::mv(headers));\n}\n\nkj::Promise JsonRpc::ContentLengthTransport::receive() {\n return input->readMessage()\n .then([this](kj::HttpInputStream::Message&& message) {\n auto promise = message.body->readAllText();\n return promise.attach(kj::mv(message.body));\n });\n}\n\n} \/\/ namespace capnp\nSilence compiler warning\/\/ Copyright (c) 2018 Kenton Varda and contributors\n\/\/ Licensed under the MIT License:\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"json-rpc.h\"\n#include \n#include \n\nnamespace capnp {\n\nstatic constexpr uint64_t JSON_NAME_ANNOTATION_ID = 0xfa5b1fd61c2e7c3dull;\nstatic constexpr uint64_t JSON_NOTIFICATION_ANNOTATION_ID = 0xa0a054dea32fd98cull;\n\nclass JsonRpc::CapabilityImpl final: public DynamicCapability::Server {\npublic:\n CapabilityImpl(JsonRpc& parent, InterfaceSchema schema)\n : DynamicCapability::Server(schema), parent(parent) {}\n\n kj::Promise call(InterfaceSchema::Method method,\n CallContext context) override {\n auto proto = method.getProto();\n bool isNotification = false;\n kj::StringPtr name = proto.getName();\n for (auto annotation: proto.getAnnotations()) {\n switch (annotation.getId()) {\n case JSON_NAME_ANNOTATION_ID:\n name = annotation.getValue().getText();\n break;\n case JSON_NOTIFICATION_ANNOTATION_ID:\n isNotification = true;\n break;\n }\n }\n\n capnp::MallocMessageBuilder message;\n auto value = message.getRoot();\n auto list = value.initObject(3 + !isNotification);\n\n uint index = 0;\n\n auto jsonrpc = list[index++];\n jsonrpc.setName(\"jsonrpc\");\n jsonrpc.initValue().setString(\"2.0\");\n\n uint callId = parent.callCount++;\n\n if (!isNotification) {\n auto id = list[index++];\n id.setName(\"id\");\n id.initValue().setNumber(callId);\n }\n\n auto methodName = list[index++];\n methodName.setName(\"method\");\n methodName.initValue().setString(name);\n\n auto params = list[index++];\n params.setName(\"params\");\n parent.codec.encode(context.getParams(), params.initValue());\n\n auto writePromise = parent.queueWrite(parent.codec.encode(value));\n\n if (isNotification) {\n auto sproto = context.getResultsType().getProto().getStruct();\n MessageSize size { sproto.getDataWordCount(), sproto.getPointerCount() };\n context.initResults(size);\n return kj::mv(writePromise);\n } else {\n auto paf = kj::newPromiseAndFulfiller();\n parent.awaitedResponses.insert(callId, AwaitedResponse { context, kj::mv(paf.fulfiller) });\n auto promise = writePromise.then([p = kj::mv(paf.promise)]() mutable { return kj::mv(p); });\n auto& parentRef = parent;\n return promise.attach(kj::defer([&parentRef,callId]() {\n parentRef.awaitedResponses.erase(callId);\n }));\n }\n }\n\nprivate:\n JsonRpc& parent;\n};\n\nJsonRpc::JsonRpc(Transport& transport, DynamicCapability::Client interface)\n : JsonRpc(transport, kj::mv(interface), kj::newPromiseAndFulfiller()) {}\nJsonRpc::JsonRpc(Transport& transport, DynamicCapability::Client interfaceParam,\n kj::PromiseFulfillerPair paf)\n : transport(transport),\n interface(kj::mv(interfaceParam)),\n errorPromise(paf.promise.fork()),\n errorFulfiller(kj::mv(paf.fulfiller)),\n readTask(readLoop().eagerlyEvaluate([this](kj::Exception&& e) {\n errorFulfiller->reject(kj::mv(e));\n })),\n tasks(*this) {\n codec.handleByAnnotation(interface.getSchema());\n codec.handleByAnnotation();\n\n for (auto method: interface.getSchema().getMethods()) {\n auto proto = method.getProto();\n kj::StringPtr name = proto.getName();\n for (auto annotation: proto.getAnnotations()) {\n switch (annotation.getId()) {\n case JSON_NAME_ANNOTATION_ID:\n name = annotation.getValue().getText();\n break;\n }\n }\n methodMap.insert(name, method);\n }\n}\n\nDynamicCapability::Client JsonRpc::getPeer(InterfaceSchema schema) {\n codec.handleByAnnotation(interface.getSchema());\n return kj::heap(*this, schema);\n}\n\nstatic kj::HttpHeaderTable& staticHeaderTable() {\n static kj::HttpHeaderTable HEADER_TABLE;\n return HEADER_TABLE;\n}\n\nkj::Promise JsonRpc::queueWrite(kj::String text) {\n auto fork = writeQueue.then([this, text = kj::mv(text)]() mutable {\n auto promise = transport.send(text);\n return promise.attach(kj::mv(text));\n }).eagerlyEvaluate([this](kj::Exception&& e) {\n errorFulfiller->reject(kj::mv(e));\n }).fork();\n writeQueue = fork.addBranch();\n return fork.addBranch();\n}\n\nvoid JsonRpc::queueError(kj::Maybe id, int code, kj::StringPtr message) {\n MallocMessageBuilder capnpMessage;\n auto jsonResponse = capnpMessage.getRoot();\n jsonResponse.setJsonrpc(\"2.0\");\n KJ_IF_MAYBE(i, id) {\n jsonResponse.setId(*i);\n } else {\n jsonResponse.initId().setNull();\n }\n auto error = jsonResponse.initError();\n error.setCode(code);\n error.setMessage(message);\n\n \/\/ OK to discard result of queueWrite() since it's just one branch of a fork.\n queueWrite(codec.encode(jsonResponse));\n}\n\nkj::Promise JsonRpc::readLoop() {\n return transport.receive().then([this](kj::String message) -> kj::Promise {\n MallocMessageBuilder capnpMessage;\n auto rpcMessageBuilder = capnpMessage.getRoot();\n\n KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {\n codec.decode(message, rpcMessageBuilder);\n })) {\n queueError(nullptr, -32700, kj::str(\"Parse error: \", exception->getDescription()));\n return readLoop();\n }\n\n KJ_CONTEXT(\"decoding JSON-RPC message\", message);\n\n auto rpcMessage = rpcMessageBuilder.asReader();\n\n if (!rpcMessage.hasJsonrpc()) {\n queueError(nullptr, -32700, kj::str(\"Missing 'jsonrpc' field.\"));\n return readLoop();\n } else if (rpcMessage.getJsonrpc() != \"2.0\") {\n queueError(nullptr, -32700,\n kj::str(\"Unknown JSON-RPC version. This peer implements version '2.0'.\"));\n return readLoop();\n }\n\n switch (rpcMessage.which()) {\n case json::RpcMessage::NONE:\n queueError(nullptr, -32700, kj::str(\"message has none of params, result, or error\"));\n break;\n\n case json::RpcMessage::PARAMS: {\n \/\/ a call\n auto schema = interface.getSchema();\n KJ_IF_MAYBE(method, schema.findMethodByName(rpcMessage.getMethod())) {\n auto req = interface.newRequest(*method);\n KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {\n codec.decode(rpcMessage.getParams(), req);\n })) {\n kj::Maybe id;\n if (rpcMessage.hasId()) id = rpcMessage.getId();\n queueError(id, -32602,\n kj::str(\"Type error in method params: \", exception->getDescription()));\n break;\n }\n\n if (rpcMessage.hasId()) {\n auto id = rpcMessage.getId();\n auto idCopy = kj::heapArray(id.totalSize().wordCount + 1);\n memset(idCopy.begin(), 0, idCopy.asBytes().size());\n copyToUnchecked(id, idCopy);\n auto idPtr = readMessageUnchecked(idCopy.begin());\n\n auto promise = req.send()\n .then([this,idPtr](Response response) mutable {\n MallocMessageBuilder capnpMessage;\n auto jsonResponse = capnpMessage.getRoot();\n jsonResponse.setJsonrpc(\"2.0\");\n jsonResponse.setId(idPtr);\n codec.encode(DynamicStruct::Reader(response), jsonResponse.initResult());\n return queueWrite(codec.encode(jsonResponse));\n }, [this,idPtr](kj::Exception&& e) {\n MallocMessageBuilder capnpMessage;\n auto jsonResponse = capnpMessage.getRoot();\n jsonResponse.setJsonrpc(\"2.0\");\n jsonResponse.setId(idPtr);\n auto error = jsonResponse.initError();\n switch (e.getType()) {\n case kj::Exception::Type::FAILED:\n error.setCode(-32000);\n break;\n case kj::Exception::Type::DISCONNECTED:\n error.setCode(-32001);\n break;\n case kj::Exception::Type::OVERLOADED:\n error.setCode(-32002);\n break;\n case kj::Exception::Type::UNIMPLEMENTED:\n error.setCode(-32601); \/\/ method not found\n break;\n }\n error.setMessage(e.getDescription());\n return queueWrite(codec.encode(jsonResponse));\n });\n tasks.add(promise.attach(kj::mv(idCopy)));\n } else {\n \/\/ No 'id', so this is a notification.\n tasks.add(req.send().ignoreResult().catch_([](kj::Exception&& exception) {\n if (exception.getType() != kj::Exception::Type::UNIMPLEMENTED) {\n KJ_LOG(ERROR, \"JSON-RPC notification threw exception into the abyss\", exception);\n }\n }));\n }\n } else {\n if (rpcMessage.hasId()) {\n queueError(rpcMessage.getId(), -32601, \"Method not found\");\n } else {\n \/\/ Ignore notification for unknown method.\n }\n }\n break;\n }\n\n case json::RpcMessage::RESULT: {\n auto id = rpcMessage.getId();\n if (!id.isNumber()) {\n \/\/ JSON-RPC doesn't define what to do if receiving a response with an invalid id.\n KJ_LOG(ERROR, \"JSON-RPC response has invalid ID\");\n } else KJ_IF_MAYBE(awaited, awaitedResponses.find((uint)id.getNumber())) {\n KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {\n codec.decode(rpcMessage.getResult(), awaited->context.getResults());\n awaited->fulfiller->fulfill();\n })) {\n \/\/ Errors always propagate from callee to caller, so we don't want to throw this error\n \/\/ back to the server.\n awaited->fulfiller->reject(kj::mv(*exception));\n }\n } else {\n \/\/ Probably, this is the response to a call that was canceled.\n }\n break;\n }\n\n case json::RpcMessage::ERROR: {\n auto id = rpcMessage.getId();\n if (id.isNull()) {\n \/\/ Error message will be logged by KJ_CONTEXT, above.\n KJ_LOG(ERROR, \"peer reports JSON-RPC protocol error\");\n } else if (!id.isNumber()) {\n \/\/ JSON-RPC doesn't define what to do if receiving a response with an invalid id.\n KJ_LOG(ERROR, \"JSON-RPC response has invalid ID\");\n } else KJ_IF_MAYBE(awaited, awaitedResponses.find((uint)id.getNumber())) {\n auto error = rpcMessage.getError();\n auto code = error.getCode();\n kj::Exception::Type type =\n code == -32601 ? kj::Exception::Type::UNIMPLEMENTED\n : kj::Exception::Type::FAILED;\n awaited->fulfiller->reject(kj::Exception(\n type, __FILE__, __LINE__, kj::str(error.getMessage())));\n } else {\n \/\/ Probably, this is the response to a call that was canceled.\n }\n break;\n }\n }\n\n return readLoop();\n });\n}\n\nvoid JsonRpc::taskFailed(kj::Exception&& exception) {\n errorFulfiller->reject(kj::mv(exception));\n}\n\n\/\/ =======================================================================================\n\nJsonRpc::ContentLengthTransport::ContentLengthTransport(kj::AsyncIoStream& stream)\n : stream(stream), input(kj::newHttpInputStream(stream, staticHeaderTable())) {}\nJsonRpc::ContentLengthTransport::~ContentLengthTransport() noexcept(false) {}\n\nkj::Promise JsonRpc::ContentLengthTransport::send(kj::StringPtr text) {\n auto headers = kj::str(\"Content-Length: \", text.size(), \"\\r\\n\\r\\n\");\n parts[0] = headers.asBytes();\n parts[1] = text.asBytes();\n return stream.write(parts).attach(kj::mv(headers));\n}\n\nkj::Promise JsonRpc::ContentLengthTransport::receive() {\n return input->readMessage()\n .then([](kj::HttpInputStream::Message&& message) {\n auto promise = message.body->readAllText();\n return promise.attach(kj::mv(message.body));\n });\n}\n\n} \/\/ namespace capnp\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\r\n\/\/ Use of this source code is governed by a BSD-style license that can be\r\n\/\/ found in the LICENSE file.\r\n\r\n#include \r\n\r\n#include \"chrome_frame\/chrome_launcher.h\"\r\n\r\n\/\/ We want to keep this EXE tiny, so we avoid all dependencies and link to no\r\n\/\/ libraries, and we do not use the C runtime.\r\n\/\/\r\n\/\/ To catch errors in debug builds, we define an extremely simple assert macro.\r\n#ifndef NDEBUG\r\n#define CLM_ASSERT(x) do { if (!(x)) { ::DebugBreak(); } } while (false)\r\n#else\r\n#define CLM_ASSERT(x)\r\n#endif \/\/ NDEBUG\r\n\r\n\/\/ In release builds, we skip the standard library completely to minimize\r\n\/\/ size. This is more work in debug builds, and unnecessary, hence the\r\n\/\/ different signatures.\r\n#ifndef NDEBUG\r\nint APIENTRY wWinMain(HINSTANCE, HINSTANCE, wchar_t*, int) {\r\n#else\r\nextern \"C\" void __cdecl WinMainCRTStartup() {\r\n#endif \/\/ NDEBUG\r\n \/\/ This relies on the chrome_launcher.exe residing in the same directory\r\n \/\/ as our DLL. We build a full path to avoid loading it from any other\r\n \/\/ directory in the DLL search path.\r\n \/\/\r\n \/\/ The code is a bit verbose because we can't use the standard library.\r\n const wchar_t kBaseName[] = L\"npchrome_tab.dll\";\r\n wchar_t file_path[MAX_PATH + (sizeof(kBaseName) \/ sizeof(kBaseName[0])) + 1];\r\n file_path[0] = L'\\0';\r\n ::GetModuleFileName(::GetModuleHandle(NULL), file_path, MAX_PATH);\r\n\r\n \/\/ Find index of last slash, and null-terminate the string after it.\r\n \/\/\r\n \/\/ Proof for security purposes, since we can't use the safe string\r\n \/\/ manipulation functions from the runtime:\r\n \/\/ - File_path is always null-terminated, by us initially and by \r\n \/\/ ::GetModuleFileName if it puts anything into the buffer.\r\n \/\/ - If there is no slash in the path then it's a relative path, not an\r\n \/\/ absolute one, and the code ends up creating a relative path to\r\n \/\/ npchrome_tab.dll.\r\n \/\/ - It's safe to use lstrcatW since we know the maximum length of both\r\n \/\/ parts we are concatenating, and we know the buffer will fit them in\r\n \/\/ the worst case.\r\n int slash_index = lstrlenW(file_path);\r\n \/\/ Invariant: 0 <= slash_index < MAX_PATH\r\n CLM_ASSERT(slash_index > 0);\r\n while (slash_index > 0 && file_path[slash_index] != L'\\\\')\r\n --slash_index;\r\n \/\/ Invariant: 0 <= slash_index < MAX_PATH and it is either the index of \r\n \/\/ the last \\ in the path, or 0.\r\n if (slash_index != 0)\r\n ++slash_index; \/\/ don't remove the last '\\'\r\n file_path[slash_index] = L'\\0';\r\n\r\n lstrcatW(file_path, kBaseName);\r\n\r\n UINT exit_code = ERROR_FILE_NOT_FOUND;\r\n HMODULE chrome_tab = ::LoadLibrary(file_path);\r\n CLM_ASSERT(chrome_tab);\r\n if (chrome_tab) {\r\n chrome_launcher::CfLaunchChromeProc proc = \r\n reinterpret_cast(\r\n ::GetProcAddress(chrome_tab, \"CfLaunchChrome\"));\r\n CLM_ASSERT(proc);\r\n if (proc) {\r\n exit_code = proc();\r\n } else {\r\n exit_code = ERROR_INVALID_FUNCTION;\r\n }\r\n\r\n ::FreeLibrary(chrome_tab);\r\n }\r\n ::ExitProcess(exit_code);\r\n}\r\nSetting the SVN eol style to LF on chrome frame sources\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"chrome_frame\/chrome_launcher.h\"\n\n\/\/ We want to keep this EXE tiny, so we avoid all dependencies and link to no\n\/\/ libraries, and we do not use the C runtime.\n\/\/\n\/\/ To catch errors in debug builds, we define an extremely simple assert macro.\n#ifndef NDEBUG\n#define CLM_ASSERT(x) do { if (!(x)) { ::DebugBreak(); } } while (false)\n#else\n#define CLM_ASSERT(x)\n#endif \/\/ NDEBUG\n\n\/\/ In release builds, we skip the standard library completely to minimize\n\/\/ size. This is more work in debug builds, and unnecessary, hence the\n\/\/ different signatures.\n#ifndef NDEBUG\nint APIENTRY wWinMain(HINSTANCE, HINSTANCE, wchar_t*, int) {\n#else\nextern \"C\" void __cdecl WinMainCRTStartup() {\n#endif \/\/ NDEBUG\n \/\/ This relies on the chrome_launcher.exe residing in the same directory\n \/\/ as our DLL. We build a full path to avoid loading it from any other\n \/\/ directory in the DLL search path.\n \/\/\n \/\/ The code is a bit verbose because we can't use the standard library.\n const wchar_t kBaseName[] = L\"npchrome_tab.dll\";\n wchar_t file_path[MAX_PATH + (sizeof(kBaseName) \/ sizeof(kBaseName[0])) + 1];\n file_path[0] = L'\\0';\n ::GetModuleFileName(::GetModuleHandle(NULL), file_path, MAX_PATH);\n\n \/\/ Find index of last slash, and null-terminate the string after it.\n \/\/\n \/\/ Proof for security purposes, since we can't use the safe string\n \/\/ manipulation functions from the runtime:\n \/\/ - File_path is always null-terminated, by us initially and by \n \/\/ ::GetModuleFileName if it puts anything into the buffer.\n \/\/ - If there is no slash in the path then it's a relative path, not an\n \/\/ absolute one, and the code ends up creating a relative path to\n \/\/ npchrome_tab.dll.\n \/\/ - It's safe to use lstrcatW since we know the maximum length of both\n \/\/ parts we are concatenating, and we know the buffer will fit them in\n \/\/ the worst case.\n int slash_index = lstrlenW(file_path);\n \/\/ Invariant: 0 <= slash_index < MAX_PATH\n CLM_ASSERT(slash_index > 0);\n while (slash_index > 0 && file_path[slash_index] != L'\\\\')\n --slash_index;\n \/\/ Invariant: 0 <= slash_index < MAX_PATH and it is either the index of \n \/\/ the last \\ in the path, or 0.\n if (slash_index != 0)\n ++slash_index; \/\/ don't remove the last '\\'\n file_path[slash_index] = L'\\0';\n\n lstrcatW(file_path, kBaseName);\n\n UINT exit_code = ERROR_FILE_NOT_FOUND;\n HMODULE chrome_tab = ::LoadLibrary(file_path);\n CLM_ASSERT(chrome_tab);\n if (chrome_tab) {\n chrome_launcher::CfLaunchChromeProc proc = \n reinterpret_cast(\n ::GetProcAddress(chrome_tab, \"CfLaunchChrome\"));\n CLM_ASSERT(proc);\n if (proc) {\n exit_code = proc();\n } else {\n exit_code = ERROR_INVALID_FUNCTION;\n }\n\n ::FreeLibrary(chrome_tab);\n }\n ::ExitProcess(exit_code);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 Google Inc. All Rights Reserved.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n\n#include \"state_space_regression_model_manager.h\"\n#include \"state_space_gaussian_model_manager.h\"\n#include \"utils.h\"\n\n#include \"r_interface\/list_io.hpp\"\n#include \"r_interface\/prior_specification.hpp\"\n#include \"Models\/Glm\/PosteriorSamplers\/BregVsSampler.hpp\"\n#include \"Models\/Glm\/PosteriorSamplers\/SpikeSlabDaRegressionSampler.hpp\"\n#include \"Models\/StateSpace\/PosteriorSamplers\/StateSpacePosteriorSampler.hpp\"\n#include \"Models\/StateSpace\/StateSpaceModel.hpp\"\n#include \"Models\/StateSpace\/StateSpaceRegressionModel.hpp\"\n#include \"cpputil\/report_error.hpp\"\n\nnamespace BOOM {\nnamespace bsts {\n\nnamespace {\ntypedef StateSpaceRegressionModelManager SSRMF;\n} \/\/ namespace\n\nStateSpaceRegressionModelManager::StateSpaceRegressionModelManager()\n : predictor_dimension_(-1) {}\n\nStateSpaceRegressionModel * SSRMF::CreateBareModel(\n SEXP r_data_list,\n SEXP r_prior,\n SEXP r_options,\n RListIoManager *io_manager) {\n Matrix predictors;\n Vector response;\n std::vector response_is_observed;\n if (!Rf_isNull(r_data_list)) {\n if (Rf_inherits(r_data_list, \"bsts\")) {\n predictors = ToBoomMatrix(getListElement(r_data_list, \"predictors\"));\n SEXP r_response = getListElement(r_data_list, \"original.series\");\n response = ToBoomVector(r_response);\n response_is_observed = IsObserved(r_response);\n } else {\n \/\/ If we were passed data from R then use it to build the model.\n predictors = ToBoomMatrix(getListElement(r_data_list, \"predictors\"));\n response = ToBoomVector(getListElement(r_data_list, \"response\"));\n response_is_observed = ToVectorBool(getListElement(\n r_data_list, \"response.is.observed\"));\n }\n UnpackTimestampInfo(r_data_list);\n if (TimestampsAreTrivial()) {\n model_.reset(new StateSpaceRegressionModel(\n response,\n predictors,\n response_is_observed));\n } else {\n \/\/ timestamps are non-trivial.\n model_.reset(new StateSpaceRegressionModel(ncol(predictors)));\n std::vector> data;\n data.reserve(NumberOfTimePoints());\n for (int i = 0; i < NumberOfTimePoints(); ++i) {\n data.push_back(new StateSpace::MultiplexedRegressionData);\n }\n for (int i = 0; i < response.size(); ++i) {\n NEW(RegressionData, observation)(response[i], predictors.row(i));\n if (!response_is_observed[i]) {\n observation->set_missing_status(Data::completely_missing);\n }\n data[TimestampMapping(i)]->add_data(observation);\n }\n for (int i = 0; i < NumberOfTimePoints(); ++i) {\n if (data[i]->observed_sample_size() == 0) {\n data[i]->set_missing_status(Data::completely_missing);\n }\n model_->add_multiplexed_data(data[i]);\n }\n }\n } else {\n \/\/ No data was passed from R, so build the model from its default\n \/\/ constructor. We need to know the dimension of the predictors.\n if (predictor_dimension_ < 0) {\n report_error(\"If r_data_list is not passed, you must call \"\n \"SetPredictorDimension before calling \"\n \"CreateBareModel.\");\n }\n model_.reset(new StateSpaceRegressionModel(predictor_dimension_));\n }\n\n \/\/ A NULL r_prior signals that no posterior sampler is needed.\n if (!Rf_isNull(r_prior)) {\n SetRegressionSampler(r_prior, r_options);\n Ptr sampler(\n new StateSpacePosteriorSampler(model_.get()));\n if (!Rf_isNull(r_options)\n && !Rf_asLogical(getListElement(r_options, \"enable.threads\"))) {\n sampler->disable_threads();\n }\n model_->set_method(sampler);\n }\n\n \/\/ Make the io_manager aware of the model parameters.\n Ptr regression(model_->regression_model());\n io_manager->add_list_element(\n new GlmCoefsListElement(regression->coef_prm(), \"coefficients\"));\n io_manager->add_list_element(\n new StandardDeviationListElement(regression->Sigsq_prm(),\n \"sigma.obs\"));\n return model_.get();\n}\n\nvoid SSRMF::AddDataFromBstsObject(SEXP r_bsts_object) {\n AddData(ToBoomVector(getListElement(r_bsts_object, \"original.series\", true)),\n ToBoomMatrix(getListElement(r_bsts_object, \"predictors\", true)),\n IsObserved(getListElement(r_bsts_object, \"original.series\", true)));\n}\n\nvoid SSRMF::AddDataFromList(SEXP r_data_list) {\n AddData(ToBoomVector(getListElement(r_data_list, \"response\", true)),\n ToBoomMatrix(getListElement(r_data_list, \"predictors\", true)),\n ToVectorBool(getListElement(r_data_list,\n \"response.is.observed\", true)));\n}\n\nint SSRMF::UnpackForecastData(SEXP r_prediction_data) {\n forecast_predictors_ = ToBoomMatrix(getListElement(\n r_prediction_data, \"predictors\"));\n UnpackForecastTimestamps(r_prediction_data);\n return forecast_predictors_.nrow();\n}\n\nVector SSRMF::SimulateForecast(const Vector &final_state) {\n if (ForecastTimestamps().empty()) {\n return model_->simulate_forecast(rng(), forecast_predictors_, final_state);\n } else {\n return model_->simulate_multiplex_forecast(rng(),\n forecast_predictors_,\n final_state,\n ForecastTimestamps());\n }\n}\n\nvoid SSRMF::SetRegressionSampler(SEXP r_regression_prior,\n SEXP r_options) {\n \/\/ If either the prior object or the bma method is NULL then take\n \/\/ that as a signal the model is not being specified for the\n \/\/ purposes of MCMC, and bail out.\n if (Rf_isNull(r_regression_prior)\n || Rf_isNull(r_options)\n || Rf_isNull(getListElement(r_options, \"bma.method\"))) {\n return;\n }\n std::string bma_method = BOOM::ToString(getListElement(\n r_options, \"bma.method\"));\n if (bma_method == \"SSVS\") {\n SetSsvsRegressionSampler(r_regression_prior);\n } else if (bma_method == \"ODA\") {\n SetOdaRegressionSampler(r_regression_prior, r_options);\n } else {\n std::ostringstream err;\n err << \"Unrecognized value of bma_method: \" << bma_method;\n BOOM::report_error(err.str());\n }\n}\n\nvoid SSRMF::SetSsvsRegressionSampler(SEXP r_regression_prior) {\n BOOM::RInterface::RegressionConjugateSpikeSlabPrior prior(\n r_regression_prior, model_->regression_model()->Sigsq_prm());\n DropUnforcedCoefficients(model_->regression_model(),\n prior.prior_inclusion_probabilities());\n Ptr sampler(new BregVsSampler(\n model_->regression_model().get(),\n prior.slab(),\n prior.siginv_prior(),\n prior.spike()));\n sampler->set_sigma_upper_limit(prior.sigma_upper_limit());\n int max_flips = prior.max_flips();\n if (max_flips > 0) {\n sampler->limit_model_selection(max_flips);\n }\n model_->regression_model()->set_method(sampler);\n}\n\nvoid SSRMF::SetOdaRegressionSampler(SEXP r_regression_prior,\n SEXP r_options) {\n SEXP r_oda_options = getListElement(r_options, \"oda.options\");\n BOOM::RInterface::IndependentRegressionSpikeSlabPrior prior(\n r_regression_prior, model_->regression_model()->Sigsq_prm());\n double eigenvalue_fudge_factor = 0.001;\n double fallback_probability = 0.0;\n if (!Rf_isNull(r_oda_options)) {\n eigenvalue_fudge_factor = Rf_asReal(\n getListElement(r_oda_options, \"eigenvalue.fudge.factor\"));\n fallback_probability = Rf_asReal(\n getListElement(r_oda_options, \"fallback.probability\"));\n }\n Ptr sampler(\n new SpikeSlabDaRegressionSampler(\n model_->regression_model().get(),\n prior.slab(),\n prior.siginv_prior(),\n prior.prior_inclusion_probabilities(),\n eigenvalue_fudge_factor,\n fallback_probability));\n sampler->set_sigma_upper_limit(prior.sigma_upper_limit());\n DropUnforcedCoefficients(model_->regression_model(),\n prior.prior_inclusion_probabilities());\n model_->regression_model()->set_method(sampler);\n}\n\nvoid StateSpaceRegressionModelManager::SetPredictorDimension(int xdim) {\n predictor_dimension_ = xdim;\n}\n\nvoid StateSpaceRegressionModelManager::AddData(\n const Vector &response,\n const Matrix &predictors,\n const std::vector &response_is_observed) {\n if (nrow(predictors) != response.size()\n || response_is_observed.size() != response.size()) {\n std::ostringstream err;\n err << \"Argument sizes do not match in \"\n << \"StateSpaceRegressionModelManager::AddData\" << endl\n << \"nrow(predictors) = \" << nrow(predictors) << endl\n << \"response.size() = \" << response.size() << endl\n << \"observed.size() = \" << response_is_observed.size();\n report_error(err.str());\n }\n\n for (int i = 0; i < response.size(); ++i) {\n Ptr dp(new RegressionData(response[i], predictors.row(i)));\n if (!response_is_observed[i]) {\n dp->set_missing_status(Data::partly_missing);\n }\n model_->add_regression_data(dp);\n }\n}\n\nnamespace {\ntypedef StateSpaceRegressionHoldoutErrorSampler ErrorSampler;\n} \/\/ namespace\n\nvoid ErrorSampler::sample_holdout_prediction_errors() {\n model_->sample_posterior();\n errors_->resize(niter_, model_->time_dimension() + holdout_responses_.size());\n for (int i = 0; i < niter_; ++i) {\n model_->sample_posterior();\n Vector all_errors = model_->one_step_prediction_errors(standardize_);\n all_errors.concat(model_->one_step_holdout_prediction_errors(\n holdout_predictors_, holdout_responses_, model_->final_state(), standardize_));\n errors_->row(i) = all_errors;\n }\n}\n\nHoldoutErrorSampler StateSpaceRegressionModelManager::CreateHoldoutSampler(\n SEXP r_bsts_object,\n int cutpoint,\n bool standardize,\n Matrix *prediction_error_output) {\n RListIoManager io_manager;\n Ptr model =\n static_cast(CreateModel(\n R_NilValue,\n getListElement(r_bsts_object, \"state.specification\"),\n getListElement(r_bsts_object, \"prior\"),\n getListElement(r_bsts_object, \"model.options\"),\n &io_manager));\n AddDataFromBstsObject(r_bsts_object);\n\n std::vector> data = model->dat();\n model->clear_data();\n for (int i = 0; i <= cutpoint; ++i) {\n model->add_multiplexed_data(data[i]);\n }\n int holdout_sample_size = 0;\n for (int i = cutpoint + 1; i < data.size(); ++i) {\n holdout_sample_size += data[i]->total_sample_size();\n }\n Matrix holdout_predictors(holdout_sample_size,\n model->observation_model()->xdim());\n Vector holdout_response(holdout_sample_size);\n int index = 0;\n for (int i = cutpoint + 1; i < data.size(); ++i) {\n for (int j = 0; j < data[i]->total_sample_size(); ++j) {\n holdout_predictors.row(index) = data[i]->regression_data(j).x();\n holdout_response[index] = data[i]->regression_data(j).y();\n ++index;\n }\n }\n return HoldoutErrorSampler(new ErrorSampler(\n model, holdout_response, holdout_predictors,\n Rf_asInteger(getListElement(r_bsts_object, \"niter\")),\n standardize,\n prediction_error_output));\n}\n\n} \/\/ namespace bsts\n} \/\/ namespace BOOM\nFormatting and whitespace improvements.\/\/ Copyright 2018 Google Inc. All Rights Reserved.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n\n#include \"state_space_regression_model_manager.h\"\n#include \"state_space_gaussian_model_manager.h\"\n#include \"utils.h\"\n\n#include \"r_interface\/list_io.hpp\"\n#include \"r_interface\/prior_specification.hpp\"\n#include \"Models\/Glm\/PosteriorSamplers\/BregVsSampler.hpp\"\n#include \"Models\/Glm\/PosteriorSamplers\/SpikeSlabDaRegressionSampler.hpp\"\n#include \"Models\/StateSpace\/PosteriorSamplers\/StateSpacePosteriorSampler.hpp\"\n#include \"Models\/StateSpace\/StateSpaceModel.hpp\"\n#include \"Models\/StateSpace\/StateSpaceRegressionModel.hpp\"\n#include \"cpputil\/report_error.hpp\"\n\nnamespace BOOM {\n namespace bsts {\n\n namespace {\n typedef StateSpaceRegressionModelManager SSRMF;\n } \/\/ namespace\n\n StateSpaceRegressionModelManager::StateSpaceRegressionModelManager()\n : predictor_dimension_(-1) {}\n\n StateSpaceRegressionModel * SSRMF::CreateBareModel(\n SEXP r_data_list,\n SEXP r_prior,\n SEXP r_options,\n RListIoManager *io_manager) {\n Matrix predictors;\n Vector response;\n std::vector response_is_observed;\n if (!Rf_isNull(r_data_list)) {\n if (Rf_inherits(r_data_list, \"bsts\")) {\n predictors = ToBoomMatrix(getListElement(r_data_list, \"predictors\"));\n SEXP r_response = getListElement(r_data_list, \"original.series\");\n response = ToBoomVector(r_response);\n response_is_observed = IsObserved(r_response);\n } else {\n \/\/ If we were passed data from R then use it to build the model.\n predictors = ToBoomMatrix(getListElement(r_data_list, \"predictors\"));\n response = ToBoomVector(getListElement(r_data_list, \"response\"));\n response_is_observed = ToVectorBool(getListElement(\n r_data_list, \"response.is.observed\"));\n }\n UnpackTimestampInfo(r_data_list);\n if (TimestampsAreTrivial()) {\n model_.reset(new StateSpaceRegressionModel(\n response,\n predictors,\n response_is_observed));\n } else {\n \/\/ timestamps are non-trivial.\n model_.reset(new StateSpaceRegressionModel(ncol(predictors)));\n std::vector> data;\n data.reserve(NumberOfTimePoints());\n for (int i = 0; i < NumberOfTimePoints(); ++i) {\n data.push_back(new StateSpace::MultiplexedRegressionData);\n }\n for (int i = 0; i < response.size(); ++i) {\n NEW(RegressionData, observation)(response[i], predictors.row(i));\n if (!response_is_observed[i]) {\n observation->set_missing_status(Data::completely_missing);\n }\n data[TimestampMapping(i)]->add_data(observation);\n }\n for (int i = 0; i < NumberOfTimePoints(); ++i) {\n if (data[i]->observed_sample_size() == 0) {\n data[i]->set_missing_status(Data::completely_missing);\n }\n model_->add_multiplexed_data(data[i]);\n }\n }\n } else {\n \/\/ No data was passed from R, so build the model from its default\n \/\/ constructor. We need to know the dimension of the predictors.\n if (predictor_dimension_ < 0) {\n report_error(\"If r_data_list is not passed, you must call \"\n \"SetPredictorDimension before calling \"\n \"CreateBareModel.\");\n }\n model_.reset(new StateSpaceRegressionModel(predictor_dimension_));\n }\n\n \/\/ A NULL r_prior signals that no posterior sampler is needed.\n if (!Rf_isNull(r_prior)) {\n SetRegressionSampler(r_prior, r_options);\n Ptr sampler(\n new StateSpacePosteriorSampler(model_.get()));\n if (!Rf_isNull(r_options)\n && !Rf_asLogical(getListElement(r_options, \"enable.threads\"))) {\n sampler->disable_threads();\n }\n model_->set_method(sampler);\n }\n\n \/\/ Make the io_manager aware of the model parameters.\n Ptr regression(model_->regression_model());\n io_manager->add_list_element(\n new GlmCoefsListElement(regression->coef_prm(), \"coefficients\"));\n io_manager->add_list_element(\n new StandardDeviationListElement(regression->Sigsq_prm(),\n \"sigma.obs\"));\n return model_.get();\n }\n\n void SSRMF::AddDataFromBstsObject(SEXP r_bsts_object) {\n AddData(ToBoomVector(getListElement(\n r_bsts_object, \"original.series\", true)),\n ToBoomMatrix(getListElement(\n r_bsts_object, \"predictors\", true)),\n IsObserved(getListElement(\n r_bsts_object, \"original.series\", true)));\n }\n\n void SSRMF::AddDataFromList(SEXP r_data_list) {\n AddData(ToBoomVector(getListElement(r_data_list, \"response\", true)),\n ToBoomMatrix(getListElement(r_data_list, \"predictors\", true)),\n ToVectorBool(getListElement(r_data_list,\n \"response.is.observed\", true)));\n }\n\n int SSRMF::UnpackForecastData(SEXP r_prediction_data) {\n forecast_predictors_ = ToBoomMatrix(getListElement(\n r_prediction_data, \"predictors\"));\n UnpackForecastTimestamps(r_prediction_data);\n return forecast_predictors_.nrow();\n }\n\n Vector SSRMF::SimulateForecast(const Vector &final_state) {\n if (ForecastTimestamps().empty()) {\n return model_->simulate_forecast(\n rng(), forecast_predictors_, final_state);\n } else {\n return model_->simulate_multiplex_forecast(rng(),\n forecast_predictors_,\n final_state,\n ForecastTimestamps());\n }\n }\n\n void SSRMF::SetRegressionSampler(SEXP r_regression_prior,\n SEXP r_options) {\n \/\/ If either the prior object or the bma method is NULL then take\n \/\/ that as a signal the model is not being specified for the\n \/\/ purposes of MCMC, and bail out.\n if (Rf_isNull(r_regression_prior)\n || Rf_isNull(r_options)\n || Rf_isNull(getListElement(r_options, \"bma.method\"))) {\n return;\n }\n std::string bma_method = BOOM::ToString(getListElement(\n r_options, \"bma.method\"));\n if (bma_method == \"SSVS\") {\n SetSsvsRegressionSampler(r_regression_prior);\n } else if (bma_method == \"ODA\") {\n SetOdaRegressionSampler(r_regression_prior, r_options);\n } else {\n std::ostringstream err;\n err << \"Unrecognized value of bma_method: \" << bma_method;\n BOOM::report_error(err.str());\n }\n }\n\n void SSRMF::SetSsvsRegressionSampler(SEXP r_regression_prior) {\n BOOM::RInterface::RegressionConjugateSpikeSlabPrior prior(\n r_regression_prior, model_->regression_model()->Sigsq_prm());\n DropUnforcedCoefficients(model_->regression_model(),\n prior.prior_inclusion_probabilities());\n Ptr sampler(new BregVsSampler(\n model_->regression_model().get(),\n prior.slab(),\n prior.siginv_prior(),\n prior.spike()));\n sampler->set_sigma_upper_limit(prior.sigma_upper_limit());\n int max_flips = prior.max_flips();\n if (max_flips > 0) {\n sampler->limit_model_selection(max_flips);\n }\n model_->regression_model()->set_method(sampler);\n }\n\n void SSRMF::SetOdaRegressionSampler(SEXP r_regression_prior,\n SEXP r_options) {\n SEXP r_oda_options = getListElement(r_options, \"oda.options\");\n BOOM::RInterface::IndependentRegressionSpikeSlabPrior prior(\n r_regression_prior, model_->regression_model()->Sigsq_prm());\n double eigenvalue_fudge_factor = 0.001;\n double fallback_probability = 0.0;\n if (!Rf_isNull(r_oda_options)) {\n eigenvalue_fudge_factor = Rf_asReal(\n getListElement(r_oda_options, \"eigenvalue.fudge.factor\"));\n fallback_probability = Rf_asReal(\n getListElement(r_oda_options, \"fallback.probability\"));\n }\n Ptr sampler(\n new SpikeSlabDaRegressionSampler(\n model_->regression_model().get(),\n prior.slab(),\n prior.siginv_prior(),\n prior.prior_inclusion_probabilities(),\n eigenvalue_fudge_factor,\n fallback_probability));\n sampler->set_sigma_upper_limit(prior.sigma_upper_limit());\n DropUnforcedCoefficients(model_->regression_model(),\n prior.prior_inclusion_probabilities());\n model_->regression_model()->set_method(sampler);\n }\n\n void StateSpaceRegressionModelManager::SetPredictorDimension(int xdim) {\n predictor_dimension_ = xdim;\n }\n\n void StateSpaceRegressionModelManager::AddData(\n const Vector &response,\n const Matrix &predictors,\n const std::vector &response_is_observed) {\n if (nrow(predictors) != response.size()\n || response_is_observed.size() != response.size()) {\n std::ostringstream err;\n err << \"Argument sizes do not match in \"\n << \"StateSpaceRegressionModelManager::AddData\" << endl\n << \"nrow(predictors) = \" << nrow(predictors) << endl\n << \"response.size() = \" << response.size() << endl\n << \"observed.size() = \" << response_is_observed.size();\n report_error(err.str());\n }\n\n for (int i = 0; i < response.size(); ++i) {\n Ptr dp(new RegressionData(\n response[i], predictors.row(i)));\n if (!response_is_observed[i]) {\n dp->set_missing_status(Data::partly_missing);\n }\n model_->add_regression_data(dp);\n }\n }\n\n namespace {\n typedef StateSpaceRegressionHoldoutErrorSampler ErrorSampler;\n } \/\/ namespace\n\n void ErrorSampler::sample_holdout_prediction_errors() {\n model_->sample_posterior();\n errors_->resize(\n niter_, model_->time_dimension() + holdout_responses_.size());\n for (int i = 0; i < niter_; ++i) {\n model_->sample_posterior();\n Vector all_errors = model_->one_step_prediction_errors(standardize_);\n all_errors.concat(model_->one_step_holdout_prediction_errors(\n holdout_predictors_,\n holdout_responses_,\n model_->final_state(),\n standardize_));\n errors_->row(i) = all_errors;\n }\n }\n\n HoldoutErrorSampler StateSpaceRegressionModelManager::CreateHoldoutSampler(\n SEXP r_bsts_object,\n int cutpoint,\n bool standardize,\n Matrix *prediction_error_output) {\n RListIoManager io_manager;\n Ptr model =\n static_cast(CreateModel(\n R_NilValue,\n getListElement(r_bsts_object, \"state.specification\"),\n getListElement(r_bsts_object, \"prior\"),\n getListElement(r_bsts_object, \"model.options\"),\n &io_manager));\n AddDataFromBstsObject(r_bsts_object);\n\n std::vector> data(\n model->dat());\n model->clear_data();\n for (int i = 0; i <= cutpoint; ++i) {\n model->add_multiplexed_data(data[i]);\n }\n int holdout_sample_size = 0;\n for (int i = cutpoint + 1; i < data.size(); ++i) {\n holdout_sample_size += data[i]->total_sample_size();\n }\n Matrix holdout_predictors(holdout_sample_size,\n model->observation_model()->xdim());\n Vector holdout_response(holdout_sample_size);\n int index = 0;\n for (int i = cutpoint + 1; i < data.size(); ++i) {\n for (int j = 0; j < data[i]->total_sample_size(); ++j) {\n holdout_predictors.row(index) = data[i]->regression_data(j).x();\n holdout_response[index] = data[i]->regression_data(j).y();\n ++index;\n }\n }\n return HoldoutErrorSampler(new ErrorSampler(\n model, holdout_response, holdout_predictors,\n Rf_asInteger(getListElement(r_bsts_object, \"niter\")),\n standardize,\n prediction_error_output));\n }\n\n } \/\/ namespace bsts\n} \/\/ namespace BOOM\n<|endoftext|>"} {"text":"#ifndef CPPEVOLVE_TREE_H_\n#define CPPEVOLVE_TREE_H_\n\n#include \"cppEvolve\/utils.hpp\"\n\nnamespace evolve\n{\n namespace Tree\n {\n\n template\n class BaseNode\n {\n public:\n virtual ~BaseNode(){};\n virtual rtype eval()=0;\n\n std::vector*>& getChildren() {\n return children;\n }\n\n virtual unsigned int getNumChildren() const =0;\n\n const std::string& getName() const {return name;}\n\n template\n friend std::ostream& operator<< (std::ostream &out, const BaseNode& node);\n\n protected:\n BaseNode(const std::string& _name) :\n name(_name){}\n std::vector*> children;\n const std::string name;\n };\n\n\n template\n class Node : public BaseNode\n {\n public:\n Node(genome g, const std::string& _name) :\n BaseNode(_name),\n val(g)\n {\n }\n\n virtual ~Node(){}\n\n virtual typename genome::result_type eval() override\n {\n std::vector results;\n\n std::for_each(this->children.begin(), this->children.end(),\n [&](BaseNode* child){results.push_back(child->eval());});\n\n return unpack_caller::eval(val, results);\n }\n\n virtual unsigned int getNumChildren() const override\n {\n return count_args::value;\n }\n\n private:\n genome val;\n };\n\n\n template\n class Terminator: public BaseNode\n {\n public:\n static_assert(count_args::value == 0, \"The number of arguments for a terminator must be 0\");\n\n Terminator(genome g, const std::string& _name) :\n BaseNode(_name),\n val(g){}\n\n virtual ~Terminator(){}\n\n virtual typename genome::result_type eval() override {\n return val();\n }\n\n virtual unsigned int getNumChildren() const override {\n return 0;\n }\n\n private:\n genome val;\n };\n\n\n template\n class Tree\n {\n public:\n Tree(BaseNode* _root) :\n root(_root){}\n\n rType eval() const {\n return root->eval();\n }\n\n template\n friend std::ostream& operator<< (std::ostream &out, const Tree& tree);\n\n BaseNode* root;\n protected:\n\n };\n\n template\n std::ostream& operator<< (std::ostream &out, const Tree& tree)\n {\n out << *tree.root;\n return out;\n }\n\n\n template\n std::ostream& operator<< (std::ostream &out, const BaseNode& node)\n {\n out << node.name;\n\n if (!node.children.empty()) {\n out << \"(\";\n for (unsigned int i=0; i < node.children.size()-1; ++i)\n out << *(node.children[i]) << \", \";\n\n out << *node.children[node.children.size()-1];\n out << \")\";\n }\n return out;\n }\n\n\n template\n class TreeFactory\n {\n public:\n TreeFactory(){}\n\n template\n void addNode(rType(*f)(T...), const std::string& name)\n {\n static_assert(sizeof...(T) > 0, \"Node function with 0 arguments should be terminator\");\n\n std::function*()> func = [=]() {\n return new Node>(f, name);\n };\n nodes.push_back(func);\n }\n\n void addTerminator(rType(*f)(), const std::string& name)\n {\n std::function*()> func = [=]() {\n return new Terminator>(f, name);\n };\n terminators.push_back(func);\n }\n\n Tree* make()\n {\n assert(!terminators.empty());\n auto tree = new Tree(createRandomNode());\n\n for (unsigned int i=0; i < tree->root->getNumChildren(); ++i)\n {\n BaseNode* node = createRandomNode();\n tree->root->getChildren().push_back(node);\n for (unsigned int i=0; i < node->getNumChildren(); ++i)\n {\n node->getChildren().push_back(createRandomTerminator());\n }\n }\n\n return tree;\n }\n\n protected:\n std::vector*()>> nodes;\n std::vector*()>> terminators;\n\n BaseNode* createRandomNode() const {\n return nodes[rand() % nodes.size()]();\n }\n\n BaseNode* createRandomTerminator() const {\n return terminators[rand() % terminators.size()]();\n }\n\n };\n }\n}\n\n\n#endif\nConverted node storage to map of ID to function#ifndef CPPEVOLVE_TREE_H_\n#define CPPEVOLVE_TREE_H_\n\n#include \"cppEvolve\/utils.hpp\"\n#include \n\nnamespace evolve\n{\n namespace Tree\n {\n\n template\n class BaseNode\n {\n public:\n virtual ~BaseNode(){};\n virtual rtype eval()=0;\n\n std::vector*>& getChildren() {\n return children;\n }\n\n virtual unsigned int getNumChildren() const =0;\n\n const std::string& getName() const {return name;}\n\n unsigned int getID() const {return ID;}\n\n template\n friend std::ostream& operator<< (std::ostream &out, const BaseNode& node);\n\n protected:\n BaseNode(const std::string& _name, unsigned int _ID) :\n name(_name),\n ID(_ID){}\n std::vector*> children;\n const std::string name;\n const unsigned int ID;\n };\n\n\n template\n class Node : public BaseNode\n {\n public:\n Node(genome g, const std::string& _name, unsigned int _ID) :\n BaseNode(_name, _ID),\n val(g)\n {\n }\n\n virtual ~Node(){}\n\n virtual typename genome::result_type eval() override\n {\n std::vector results;\n\n std::for_each(this->children.begin(), this->children.end(),\n [&](BaseNode* child){results.push_back(child->eval());});\n\n return unpack_caller::eval(val, results);\n }\n\n virtual unsigned int getNumChildren() const override\n {\n return count_args::value;\n }\n\n private:\n genome val;\n };\n\n\n template\n class Terminator: public BaseNode\n {\n public:\n static_assert(count_args::value == 0, \"The number of arguments for a terminator must be 0\");\n\n Terminator(genome g, const std::string& _name, unsigned int _ID) :\n BaseNode(_name, _ID),\n val(g){}\n\n virtual ~Terminator(){}\n\n virtual typename genome::result_type eval() override {\n return val();\n }\n\n virtual unsigned int getNumChildren() const override {\n return 0;\n }\n\n private:\n genome val;\n };\n\n\n template\n class Tree\n {\n public:\n Tree(BaseNode* _root) :\n root(_root){}\n\n rType eval() const {\n return root->eval();\n }\n\n template\n friend std::ostream& operator<< (std::ostream &out, const Tree& tree);\n\n BaseNode* root;\n protected:\n\n };\n\n template\n std::ostream& operator<< (std::ostream &out, const Tree& tree)\n {\n out << *tree.root;\n return out;\n }\n\n\n template\n std::ostream& operator<< (std::ostream &out, const BaseNode& node)\n {\n out << node.name;\n\n if (!node.children.empty()) {\n out << \"(\";\n for (unsigned int i=0; i < node.children.size()-1; ++i)\n out << *(node.children[i]) << \", \";\n\n out << *node.children[node.children.size()-1] << \")\";\n }\n return out;\n }\n\n\n template\n class TreeFactory\n {\n public:\n TreeFactory() :\n currentID(0){}\n\n template\n void addNode(rType(*f)(T...), const std::string& name)\n {\n static_assert(sizeof...(T) > 0, \"Node function with 0 arguments should be terminator\");\n\n std::function*()> func = [=]() {\n return new Node>(f, name, currentID);\n };\n nodes[currentID++] = func;\n }\n\n void addTerminator(rType(*f)(), const std::string& name)\n {\n std::function*()> func = [=]() {\n return new Terminator>(f, name, currentID);\n };\n terminators[currentID++] = func;\n }\n\n Tree* make()\n {\n assert(!terminators.empty());\n auto tree = new Tree(createRandomNode());\n\n for (unsigned int i=0; i < tree->root->getNumChildren(); ++i)\n {\n BaseNode* node = createRandomNode();\n tree->root->getChildren().push_back(node);\n for (unsigned int i=0; i < node->getNumChildren(); ++i)\n {\n node->getChildren().push_back(createRandomTerminator());\n }\n }\n\n return tree;\n }\n\n\n BaseNode* copyNode(const BaseNode* node) {\n if (nodes.find(node->getID()) != nodes.end())\n {\n return nodes[node->getID()]();\n }\n else\n {\n return terminators[node->getID()]();\n }\n }\n\n protected:\n unsigned int currentID;\n std::map*()>> nodes;\n std::map*()>> terminators;\n\n BaseNode* createRandomNode() const {\n auto loc = nodes.begin();\n std::advance(loc, rand() % nodes.size());\n return ((*loc).second)();\n }\n\n BaseNode* createRandomTerminator() const {\n auto loc = terminators.begin();\n std::advance(loc, rand() % terminators.size());\n return ((*loc).second)();\n }\n\n };\n }\n}\n\n\n#endif\n<|endoftext|>"} {"text":"\/\/! Libs: -lLLVM-3.1svn -lclangFrontend -lclangParse -lclangDriver -lclangSerialization -lclangSema -lclangEdit -lclangAnalysis -lclangAST -lclangLex -lclangBasic\n\n#include \nusing namespace std;\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace clang;\nusing llvm::dyn_cast;\nusing clang::driver::Arg;\nusing clang::driver::InputArgList;\nusing clang::driver::DerivedArgList;\nusing clang::CompilerInstance;\nusing llvm::sys::getDefaultTargetTriple;\nusing llvm::sys::Path;\nusing llvm::ArrayRef;\nusing clang::driver::Driver;\nusing clang::driver::Compilation;\nusing clang::driver::Command;\nusing clang::driver::ActionList;\nusing clang::driver::Action;\nusing clang::driver::InputAction;\nusing clang::driver::Job;\nusing clang::driver::JobList;\nusing clang::driver::Tool;\n\n\nstatic llvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes);\nint ExecuteCompilation(const Driver* that, const Compilation &C,\n const Command *&FailingCommand);\nint ExecuteCommand(const Compilation* that, const Command &C,\n const Command *&FailingCommand);\nint ExecuteJob(const Compilation* that, const Job &J,\n const Command *&FailingCommand);\n\n\nint main(int argc, char* argv[])\n{\n if (argc < 2) {\n cerr << \"Usage: \" << argv[0] << \" [clang-options] source.cpp\" << endl;\n cerr << \"Any clang option is usable, source files may be listed among in no particular order.\" << endl;\n return EXIT_FAILURE;\n }\n\n CompilerInstance ci;\n ci.createDiagnostics(argc, argv + 1);\n\n Path path = GetExecutablePath(argv[0], true);\n Driver driver (path.str(), getDefaultTargetTriple(), \"a.out\", true, ci.getDiagnostics());\n driver.CCCIsCPP = true; \/\/ only preprocess\n OwningPtr compil (driver.BuildCompilation(llvm::ArrayRef(argv, argc)));\n if (!compil) {\n cerr << \"Could not build a Compilation!\" << endl;\n return EXIT_FAILURE;\n }\n\n driver.PrintActions(*compil);\n\n {\n const ActionList& actions = compil->getActions();\n cout << \"Actions: (\" << actions.size() << \")\" << endl;\n for (ActionList::const_iterator it = actions.begin(), end = actions.end() ; it != end ; ++it) {\n const Action& a = *(*it);\n cout << \" - \" << a.getClassName() << \" inputs(\" << a.getInputs().size() << \") -> \" << clang::driver::types::getTypeName(a.getType()) << endl;\n for (ActionList::const_iterator it2 = a.begin(), end2 = a.end() ; it2 != end2 ; ++it2) {\n const Action& a2 = *(*it2);\n const InputAction* ia = dyn_cast(&a2);\n if (ia) {\n cout << \" - \" << a2.getClassName() << \" {\";\n const Arg& inputs = ia->getInputArg();\n for (unsigned i = 0, n = inputs.getNumValues() ; i < n ; ++i) {\n cout << \"\\\"\" << inputs.getValue(compil->getArgs(), i) << \"\\\"\";\n if (i+1 < n) cout << \", \";\n }\n cout << \"} -> \" << clang::driver::types::getTypeName(a2.getType()) << endl;\n } else\n cout << \" - \" << a2.getClassName() << \" inputs(\" << a2.getInputs().size() << \") -> \" << clang::driver::types::getTypeName(a2.getType()) << endl;\n }\n }\n }\n\n cout << endl;\n\n \/\/!\\\\ The following doesn't quite work\n \/\/!\\\\ Tip: Use -### to print commands instead of executing them.\n \/\/!\\\\ ExecuteCompilation exec()s the this same program, with extra arguments.\n \/\/!\\\\ We should take advantage of the parsing done, and do the preprocess ourselves.\n\n int Res = 0;\n const Command *FailingCommand = 0;\n Res = ExecuteCompilation(&driver, *compil, FailingCommand);\n\n \/\/ If result status is < 0, then the driver command signalled an error.\n \/\/ In this case, generate additional diagnostic information if possible.\n if (Res < 0)\n driver.generateCompilationDiagnostics(*compil, FailingCommand);\n\n return EXIT_SUCCESS;\n}\n\n\n\/\/\/ Copied from tools\/driver\/driver.cpp, where it was a static (local) function.\n\/\/\/ Turns argv[0] into the executable path.\nllvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes)\n{\n if (!CanonicalPrefixes)\n return llvm::sys::Path(Argv0);\n\n \/\/ symbol just needs to be some symbol in the binary\n void *symbol = (void*) (intptr_t) GetExecutablePath; \/\/ can't take ::main() address, use the current function instead\n return llvm::sys::Path::GetMainExecutable(Argv0, symbol);\n}\n\n\n\/\/ Some necessary includes for the following 3 functions\n#include \n#include \n#include \n\n\/\/\/ Copied from Driver::ExecuteCompilation().\n\/\/\/ Modified to call the modified ExecuteJob().\nint ExecuteCompilation(const Driver* that, const Compilation &C,\n const Command *&FailingCommand) {\n \/\/ Just print if -### was present.\n if (C.getArgs().hasArg(clang::driver::options::OPT__HASH_HASH_HASH)) {\n C.PrintJob(llvm::errs(), C.getJobs(), \"\\n\", true);\n return 0;\n }\n\n \/\/ If there were errors building the compilation, quit now.\n if (that->getDiags().hasErrorOccurred())\n return 1;\n\n int Res = ExecuteJob(&C, C.getJobs(), FailingCommand);\n\n \/\/ Remove temp files.\n C.CleanupFileList(C.getTempFiles());\n\n \/\/ If the command succeeded, we are done.\n if (Res == 0)\n return Res;\n\n \/\/ Otherwise, remove result files as well.\n if (!C.getArgs().hasArg(clang::driver::options::OPT_save_temps)) {\n C.CleanupFileList(C.getResultFiles(), true);\n\n \/\/ Failure result files are valid unless we crashed.\n if (Res < 0) {\n C.CleanupFileList(C.getFailureResultFiles(), true);\n#ifdef _WIN32\n \/\/ Exit status should not be negative on Win32,\n \/\/ unless abnormal termination.\n Res = 1;\n#endif\n }\n }\n\n \/\/ Print extra information about abnormal failures, if possible.\n \/\/\n \/\/ This is ad-hoc, but we don't want to be excessively noisy. If the result\n \/\/ status was 1, assume the command failed normally. In particular, if it was\n \/\/ the compiler then assume it gave a reasonable error code. Failures in other\n \/\/ tools are less common, and they generally have worse diagnostics, so always\n \/\/ print the diagnostic there.\n const Tool &FailingTool = FailingCommand->getCreator();\n\n if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {\n \/\/ FIXME: See FIXME above regarding result code interpretation.\n if (Res < 0)\n that->Diag(clang::diag::err_drv_command_signalled)\n << FailingTool.getShortName();\n else\n that->Diag(clang::diag::err_drv_command_failed)\n << FailingTool.getShortName() << Res;\n }\n\n return Res;\n}\n\n\/\/\/ Copied from Compilation::ExecuteCommand().\n\/\/\/ Changed to print command options, and not execute anything.\nint ExecuteCommand(const Compilation* that, const Command &C,\n const Command *&FailingCommand) {\n llvm::sys::Path Prog(C.getExecutable());\n const char **Argv = new const char*[C.getArguments().size() + 2];\n Argv[0] = C.getExecutable();\n std::copy(C.getArguments().begin(), C.getArguments().end(), Argv+1);\n Argv[C.getArguments().size() + 1] = 0;\n\n if ((that->getDriver().CCCEcho || that->getDriver().CCPrintOptions ||\n that->getArgs().hasArg(clang::driver::options::OPT_v)) && !that->getDriver().CCGenDiagnostics) {\n raw_ostream *OS = &llvm::errs();\n\n \/\/ Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the\n \/\/ output stream.\n if (that->getDriver().CCPrintOptions && that->getDriver().CCPrintOptionsFilename) {\n std::string Error;\n OS = new llvm::raw_fd_ostream(that->getDriver().CCPrintOptionsFilename,\n Error,\n llvm::raw_fd_ostream::F_Append);\n if (!Error.empty()) {\n that->getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)\n << Error;\n FailingCommand = &C;\n delete OS;\n return 1;\n }\n }\n\n if (that->getDriver().CCPrintOptions)\n *OS << \"[Logging clang options]\";\n\n that->PrintJob(*OS, C, \"\\n\", \/*Quote=*\/that->getDriver().CCPrintOptions);\n\n if (OS != &llvm::errs())\n delete OS;\n }\n\n for (const char** i = Argv ; *i ; ++i)\n cout << \"\\\"\" << *i << \"\\\" \";\n cout << endl;\n\n std::string Error;\n int Res = 0;\n \/\/ Do not execute\n \/\/ Res = llvm::sys::Program::ExecuteAndWait(Prog, Argv,\n \/\/ \/*env*\/0, \/*that->Redirects (unfortunately private and inacessible)*\/0,\n \/\/ \/*secondsToWait*\/0, \/*memoryLimit*\/0,\n \/\/ &Error);\n if (!Error.empty()) {\n assert(Res && \"Error string set with 0 result code!\");\n that->getDriver().Diag(clang::diag::err_drv_command_failure) << Error;\n }\n\n if (Res)\n FailingCommand = &C;\n\n delete[] Argv;\n return Res;\n}\n\n\/\/\/ Copied from Compilation::ExecuteJob().\n\/\/\/ changed in order to call the modified ExecuteCommand().\nint ExecuteJob(const Compilation* that, const Job &J,\n const Command *&FailingCommand) {\n if (const Command *C = dyn_cast(&J)) {\n return ExecuteCommand(that, *C, FailingCommand);\n } else {\n const JobList *Jobs = cast(&J);\n for (JobList::const_iterator\n it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it) {\n if (int Res = ExecuteJob(that, **it, FailingCommand))\n return Res;\n }\n return 0;\n }\n}\nUse the same process to run Commands\/\/! Libs: -lLLVM-3.1svn -lclangFrontend -lclangParse -lclangDriver -lclangSerialization -lclangSema -lclangEdit -lclangAnalysis -lclangAST -lclangLex -lclangBasic\n\n#include \nusing namespace std;\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace clang;\nusing llvm::dyn_cast;\nusing clang::driver::Arg;\nusing clang::driver::InputArgList;\nusing clang::driver::DerivedArgList;\nusing clang::CompilerInstance;\nusing llvm::sys::getDefaultTargetTriple;\nusing llvm::sys::Path;\nusing llvm::ArrayRef;\nusing clang::driver::Driver;\nusing clang::driver::Compilation;\nusing clang::driver::Command;\nusing clang::driver::ArgStringList;\nusing clang::driver::ActionList;\nusing clang::driver::Action;\nusing clang::driver::InputAction;\nusing clang::driver::PreprocessJobAction;\nusing clang::driver::Job;\nusing clang::driver::JobAction;\nusing clang::driver::JobList;\nusing clang::driver::Tool;\nusing clang::driver::ToolChain;\n\n\nint parseArgsAndProceed(int argc, const char* argv[]);\n\nstatic llvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes);\nint ExecuteCompilation(const Driver* that, const Compilation &C,\n const Command *&FailingCommand);\nint ExecuteCommand(const Compilation* that, const Command &C,\n const Command *&FailingCommand);\nint ExecuteJob(const Compilation* that, const Job &J,\n const Command *&FailingCommand);\n\n\nint main(int argc, const char* argv[])\n{\n if (argc < 2) {\n cerr << \"Usage: \" << argv[0] << \" [clang-options] source.cpp\" << endl;\n cerr << \"Any clang option is usable, source files may be listed among in no particular order.\" << endl;\n return EXIT_FAILURE;\n }\n\n return parseArgsAndProceed(argc, argv);\n}\n\nint parseArgsAndProceed(int argc, const char* argv[]) {\n CompilerInstance ci;\n ci.createDiagnostics(argc, argv);\n\n Path path = GetExecutablePath(argv[0], true);\n Driver driver (path.str(), getDefaultTargetTriple(), \"a.out\", true, ci.getDiagnostics());\n driver.CCCIsCPP = true; \/\/ only preprocess\n OwningPtr compil (driver.BuildCompilation(llvm::ArrayRef(argv, argc)));\n if (!compil) {\n cerr << \"Cannot build the compilation.\" << endl;\n return EXIT_FAILURE;\n }\n if (driver.getDiags().hasErrorOccurred()) {\n cerr << \"Error occurred building the compilation.\" << endl;\n \/\/ We must provide a Command that failed to use Driver::generateCompilationDiagnostics()\n \/\/ That Command will only be used as follows: ``if (FailingCommand->getCreator().isLinkJob()) return;''\n \/\/ Hence we'll have to create a fake command with a tool that will answer no to isLinkJob(),\n \/\/ As we only have PreprocessorJobActions, the first generated action will do.\n JobAction& fakeAction = *dyn_cast(*compil->getActions().begin());\n Tool& fakeCreator = compil->getDefaultToolChain().SelectTool(*compil, fakeAction, fakeAction.getInputs());\n Command fakeCommand (fakeAction, fakeCreator, \/*Executable*\/NULL, ArgStringList());\n cerr << \"DIAGNOSTIC:\" << endl;\n driver.generateCompilationDiagnostics(*compil, &fakeCommand);\n cerr << \"END OF DIAGNOSTIC\" << endl;\n return EXIT_FAILURE;\n }\n\n driver.PrintActions(*compil);\n\n {\n const ActionList& actions = compil->getActions();\n cout << \"Actions: (\" << actions.size() << \")\" << endl;\n for (ActionList::const_iterator it = actions.begin(), end = actions.end() ; it != end ; ++it) {\n const Action& a = *(*it);\n cout << \" - \" << a.getClassName() << \" inputs(\" << a.getInputs().size() << \") -> \" << clang::driver::types::getTypeName(a.getType()) << endl;\n for (ActionList::const_iterator it2 = a.begin(), end2 = a.end() ; it2 != end2 ; ++it2) {\n const Action& a2 = *(*it2);\n const InputAction* ia = dyn_cast(&a2);\n if (ia) {\n cout << \" - \" << a2.getClassName() << \" {\";\n const Arg& inputs = ia->getInputArg();\n for (unsigned i = 0, n = inputs.getNumValues() ; i < n ; ++i) {\n cout << \"\\\"\" << inputs.getValue(compil->getArgs(), i) << \"\\\"\";\n if (i+1 < n) cout << \", \";\n }\n cout << \"} -> \" << clang::driver::types::getTypeName(a2.getType()) << endl;\n } else\n cout << \" - \" << a2.getClassName() << \" inputs(\" << a2.getInputs().size() << \") -> \" << clang::driver::types::getTypeName(a2.getType()) << endl;\n }\n }\n }\n\n cout << endl;\n\n \/\/!\\\\ The following doesn't quite work\n \/\/!\\\\ Tip: Use -### to print commands instead of executing them.\n \/\/!\\\\ ExecuteCompilation exec()s the this same program, with extra arguments.\n \/\/!\\\\ We should take advantage of the parsing done, and do the preprocess ourselves.\n\n int Res = 0;\n const Command *FailingCommand = 0;\n Res = ExecuteCompilation(&driver, *compil, FailingCommand);\n\n \/\/ If result status is < 0, then the driver command signalled an error.\n \/\/ In this case, generate additional diagnostic information if possible.\n if (Res < 0)\n driver.generateCompilationDiagnostics(*compil, FailingCommand);\n\n return EXIT_SUCCESS;\n}\n\n\n\/\/\/ Copied from tools\/driver\/driver.cpp, where it was a static (local) function.\n\/\/\/ Turns argv[0] into the executable path.\nllvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes)\n{\n if (!CanonicalPrefixes)\n return llvm::sys::Path(Argv0);\n\n \/\/ symbol just needs to be some symbol in the binary\n void *symbol = (void*) (intptr_t) GetExecutablePath; \/\/ can't take ::main() address, use the current function instead\n return llvm::sys::Path::GetMainExecutable(Argv0, symbol);\n}\n\n\n\/\/ Some necessary includes for the following 3 functions\n#include \n#include \n#include \n\n\/\/\/ Copied from Driver::ExecuteCompilation().\n\/\/\/ Modified to call the modified ExecuteJob().\nint ExecuteCompilation(const Driver* that, const Compilation &C,\n const Command *&FailingCommand) {\n \/\/ Just print if -### was present.\n if (C.getArgs().hasArg(clang::driver::options::OPT__HASH_HASH_HASH)) {\n C.PrintJob(llvm::errs(), C.getJobs(), \"\\n\", true);\n return 0;\n }\n\n \/\/ If there were errors building the compilation, quit now.\n if (that->getDiags().hasErrorOccurred())\n return 1;\n\n int Res = ExecuteJob(&C, C.getJobs(), FailingCommand);\n\n \/\/ If the command succeeded, we are done.\n if (Res == 0)\n return Res;\n\n \/\/ Print extra information about abnormal failures, if possible.\n \/\/\n \/\/ This is ad-hoc, but we don't want to be excessively noisy. If the result\n \/\/ status was 1, assume the command failed normally. In particular, if it was\n \/\/ the compiler then assume it gave a reasonable error code. Failures in other\n \/\/ tools are less common, and they generally have worse diagnostics, so always\n \/\/ print the diagnostic there.\n const Tool &FailingTool = FailingCommand->getCreator();\n\n if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {\n \/\/ FIXME: See FIXME above regarding result code interpretation.\n if (Res < 0)\n that->Diag(clang::diag::err_drv_command_signalled)\n << FailingTool.getShortName();\n else\n that->Diag(clang::diag::err_drv_command_failed)\n << FailingTool.getShortName() << Res;\n }\n\n return Res;\n}\n\n\/\/\/ Copied from Compilation::ExecuteCommand().\n\/\/\/ Changed to print command options, and not execute anything.\nint ExecuteCommand(const Compilation* that, const Command &C,\n const Command *&FailingCommand) {\n if ((that->getDriver().CCCEcho || that->getDriver().CCPrintOptions ||\n that->getArgs().hasArg(clang::driver::options::OPT_v)) && !that->getDriver().CCGenDiagnostics) {\n raw_ostream *OS = &llvm::errs();\n\n \/\/ Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the\n \/\/ output stream.\n if (that->getDriver().CCPrintOptions && that->getDriver().CCPrintOptionsFilename) {\n std::string Error;\n OS = new llvm::raw_fd_ostream(that->getDriver().CCPrintOptionsFilename,\n Error,\n llvm::raw_fd_ostream::F_Append);\n if (!Error.empty()) {\n that->getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)\n << Error;\n FailingCommand = &C;\n delete OS;\n return 1;\n }\n }\n\n if (that->getDriver().CCPrintOptions)\n *OS << \"[Logging clang options]\";\n\n that->PrintJob(*OS, C, \"\\n\", \/*Quote=*\/that->getDriver().CCPrintOptions);\n\n if (OS != &llvm::errs())\n delete OS;\n }\n\n int argc = C.getArguments().size();\n const char* *argv = new const char* [argc+1];\n argv[0] = C.getExecutable();\n std::copy(C.getArguments().begin(), C.getArguments().end(), argv+1);\n int Res = 0;\n Res = parseArgsAndProceed(argc, argv);\n\n if (Res)\n FailingCommand = &C;\n\n return Res;\n}\n\n\/\/\/ Copied from Compilation::ExecuteJob().\n\/\/\/ changed in order to call the modified ExecuteCommand().\nint ExecuteJob(const Compilation* that, const Job &J,\n const Command *&FailingCommand) {\n if (const Command *C = dyn_cast(&J)) {\n return ExecuteCommand(that, *C, FailingCommand);\n } else {\n const JobList *Jobs = cast(&J);\n for (JobList::const_iterator\n it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it) {\n if (int Res = ExecuteJob(that, **it, FailingCommand))\n return Res;\n }\n return 0;\n }\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Implementation of oscillations of neutrinos in matter in a\n\/\/ three-neutrino framework with decoherence.\n\/\/\n\/\/ This class inherits from the PMNS_Fast class\n\/\/\n\/\/ jcoelho@apc.in2p3.fr\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n\n#include \"PMNS_Deco.h\"\n\nusing namespace OscProb;\n\nusing namespace std;\n\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Constructor. \\sa PMNS_Base::PMNS_Base\n\/\/\/\n\/\/\/ This class is restricted to 3 neutrino flavours.\n\/\/\/\nPMNS_Deco::PMNS_Deco() : PMNS_Fast(), fGamma(),\nfRho(3, row(3,0))\n{\n SetStdPath();\n SetGamma(2,0);\n SetGamma(3,0);\n SetDecoAngle(0);\n}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Nothing to clean.\n\/\/\/\nPMNS_Deco::~PMNS_Deco(){}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Set the decoherence parameter \\f$\\Gamma_{j1}\\f$.\n\/\/\/\n\/\/\/ This will check if value is changing to keep track of whether\n\/\/\/ the eigensystem needs to be recomputed.\n\/\/\/\n\/\/\/ Requires that j = 2 or 3. Will notify you if input is wrong.\n\/\/\/\n\/\/\/ @param j - The first mass index\n\/\/\/ @param val - The absolute value of the parameter\n\/\/\/\nvoid PMNS_Deco::SetGamma(int j, double val){\n\n if(j < 2 || j > 3){\n cout << \"Gamma_\" << j << 1 << \" not valid for \" << fNumNus;\n cout << \" neutrinos. Doing nothing.\" << endl;\n return;\n }\n\n fGotES *= (fGamma[j-1] == val);\n \n fGamma[j-1] = val;\n \n}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Set the decoherence angle. This will define the relationship:\n\/\/\/\n\/\/\/ \\f$ \n\/\/\/ \\Gamma_{32} = \\Gamma_{31} + \\Gamma_{21} \\cos^2\\theta - \n\/\/\/ \\cos\\theta \\sqrt{\\Gamma_{21} (4\\Gamma_{31} - \\Gamma_{21} (1 - \\cos^2\\theta))} \n\/\/\/ \\f$\n\/\/\/\n\/\/\/ This will check if value is changing to keep track of whether\n\/\/\/ the eigensystem needs to be recomputed.\n\/\/\/\n\/\/\/ @param th - decoherence angle\n\/\/\/\nvoid PMNS_Deco::SetDecoAngle(double th)\n{\n\n double cosTh = cos(th);\n\n fGotES *= (fGamma[0] == cosTh);\n\n fGamma[0] = cosTh;\n \n}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Get any given decoherence parameter.\n\/\/\/\n\/\/\/ Requires that i > j. Will notify you if input is wrong.\n\/\/\/ If i < j, will assume reverse order and swap i and j.\n\/\/\/\n\/\/\/ @param i - The first mass index\n\/\/\/ @param j - The second mass index\n\/\/\/\ndouble PMNS_Deco::GetGamma(int i, int j)\n{\n\n if(i < j){\n cout << \"First argument should be larger than second argument\" << endl;\n cout << \"Setting reverse order (Gamma_\" << j << i << \"). \" << endl;\n int temp = i;\n i = j;\n j = temp;\n }\n if(i<1 || i>3 || i <= j || j < 1){\n cout << \"Gamma_\" << i << j << \" not valid for \" << fNumNus;\n cout << \" neutrinos. Returning 0.\" << endl;\n return 0;\n }\n\n if(j == 1){ \n return fGamma[i-1];\n }\n else {\n \/\/ Combine Gamma31, Gamma21 and an angle (fGamma[0] = cos(th)) to make Gamma32\n double arg = fGamma[1] * ( 4*fGamma[2] - fGamma[1]*(1 - pow(fGamma[0],2)) );\n\n return fGamma[2] + fGamma[1]*pow(fGamma[0],2) - fGamma[0] * sqrt(arg);\n\n }\n\n}\n\n\/\/.....................................................................\n\/\/\/ Dot product of two matrices.\n\/\/\/\n\/\/\/ @param A - input matrix A\n\/\/\/ @param B - input matrix B\n\/\/\/\n\/\/\/ @return - matrix A.B\n\/\/\/\nPMNS_Deco::matrix PMNS_Deco::Dot(matrix A, matrix B)\n{\n\n matrix out(3, row(3,0));\n \n for(int i=0; i<3; i++){\n for(int j=0; j<3; j++){\n for(int k=0; k<3; k++){\n\n out[i][j] += A[i][k] * B[k][j];\n\n }}}\n \n return out;\n\n}\n\n\/\/.....................................................................\n\/\/\/ Product of elements of two matrices.\n\/\/\/\n\/\/\/ @param A - input matrix A\n\/\/\/ @param B - input matrix B\n\/\/\/\n\/\/\/ @return - matrix A * B\n\/\/\/\nPMNS_Deco::matrix PMNS_Deco::Mult(matrix A, matrix B)\n{\n\n matrix out(3, row(3,0));\n \n for(int i=0; i<3; i++){\n for(int j=0; j<3; j++){\n \n out[i][j] += A[i][j] * B[i][j];\n\n }}\n \n return out;\n\n}\n\n\/\/.....................................................................\n\/\/\/ Conjugate transpose matrix.\n\/\/\/\n\/\/\/ @param A - input matrix A\n\/\/\/\n\/\/\/ @return - \\f$A^{\\dagger}\\f$\n\/\/\/\nPMNS_Deco::matrix PMNS_Deco::CTransp(matrix A)\n{\n\n matrix out(3, row(3,0));\n \n for(int i=0; i<3; i++){\n for(int j=0; j<3; j++){\n \n out[i][j] += conj(A[j][i]);\n\n }}\n \n return out;\n\n}\n\n\/\/.....................................................................\n\/\/\/\n\/\/\/ Propagate the current neutrino state through a given path\n\/\/\/\n\/\/\/ @param p - A neutrino path segment\n\/\/\/\nvoid PMNS_Deco::PropagatePath(NuPath p)\n{\n\n \/\/ Set the neutrino path\n SetCurPath(p);\n\n \/\/ Solve for eigensystem\n SolveHam();\n \n \/\/ The code below is not pretty or optimised at all. Lots of matrix\n \/\/ multiplications are going on which could be otpimised due to \n \/\/ symmetry. The index sorting is also terrible. Needs improving.\n\n \/\/ Store rotation matrices\n matrix U = fEvec;\n matrix Ut = CTransp(fEvec);\n\n \/\/ Rotate to effective mass basis\n fRho = Dot(Ut, Dot(fRho, U));\n \n \/\/ Compute evolution matrix\n matrix evolve(3, row(3,1));\n \n \/\/ Some ugly way of matching gamma and dmsqr indices\n int maxdm = 0; \n if(fDm[1] > fDm[maxdm]) maxdm = 1;\n if(fDm[2] > fDm[maxdm]) maxdm = 2;\n\n int mindm = 0; \n if(fDm[1] < fDm[mindm]) mindm = 1;\n if(fDm[2] < fDm[mindm]) mindm = 2;\n\n int middm = 0;\n if(middm == maxdm || middm == mindm) middm = 1; \n if(middm == maxdm || middm == mindm) middm = 2; \n\n int maxev = 0; \n if(fEval[1] > fEval[maxev]) maxev = 1;\n if(fEval[2] > fEval[maxev]) maxev = 2;\n\n int minev = 0; \n if(fEval[1] < fEval[minev]) minev = 1;\n if(fEval[2] < fEval[minev]) minev = 2;\n\n int midev = 0;\n if(midev == maxev || midev == minev) midev = 1; \n if(midev == maxev || midev == minev) midev = 2; \n \n int idx[3];\n idx[minev] = mindm;\n idx[midev] = middm;\n idx[maxev] = maxdm;\n \n for(int j=0; j<3; j++){ \n for(int i=0; i\n\/\/\/ 0 = nue, 1 = numu, 2 = nutau\n\/\/\/ 3 = sterile_1, 4 = sterile_2, etc.\n\/\/\/ <\/pre>\n\/\/\/ @param flv - The neutrino starting flavour.\n\/\/\/\nvoid PMNS_Deco::ResetToFlavour(int flv)\n{\n assert(flv>=0 && flv\n\/\/\/ 0 = nue, 1 = numu, 2 = nutau\n\/\/\/ 3 = sterile_1, 4 = sterile_2, etc.\n\/\/\/ <\/pre>\n\/\/\/ @param flv - The neutrino final flavour.\n\/\/\/\n\/\/\/ @return Neutrino oscillation probability\n\/\/\/\ndouble PMNS_Deco::P(int flv)\n{\n assert(flv>=0 && flvUse std::abs for probability from density matrix\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Implementation of oscillations of neutrinos in matter in a\n\/\/ three-neutrino framework with decoherence.\n\/\/\n\/\/ This class inherits from the PMNS_Fast class\n\/\/\n\/\/ jcoelho@apc.in2p3.fr\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n\n#include \"PMNS_Deco.h\"\n\nusing namespace OscProb;\n\nusing namespace std;\n\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Constructor. \\sa PMNS_Base::PMNS_Base\n\/\/\/\n\/\/\/ This class is restricted to 3 neutrino flavours.\n\/\/\/\nPMNS_Deco::PMNS_Deco() : PMNS_Fast(), fGamma(),\nfRho(3, row(3,0))\n{\n SetStdPath();\n SetGamma(2,0);\n SetGamma(3,0);\n SetDecoAngle(0);\n}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Nothing to clean.\n\/\/\/\nPMNS_Deco::~PMNS_Deco(){}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Set the decoherence parameter \\f$\\Gamma_{j1}\\f$.\n\/\/\/\n\/\/\/ This will check if value is changing to keep track of whether\n\/\/\/ the eigensystem needs to be recomputed.\n\/\/\/\n\/\/\/ Requires that j = 2 or 3. Will notify you if input is wrong.\n\/\/\/\n\/\/\/ @param j - The first mass index\n\/\/\/ @param val - The absolute value of the parameter\n\/\/\/\nvoid PMNS_Deco::SetGamma(int j, double val){\n\n if(j < 2 || j > 3){\n cout << \"Gamma_\" << j << 1 << \" not valid for \" << fNumNus;\n cout << \" neutrinos. Doing nothing.\" << endl;\n return;\n }\n\n fGotES *= (fGamma[j-1] == val);\n \n fGamma[j-1] = val;\n \n}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Set the decoherence angle. This will define the relationship:\n\/\/\/\n\/\/\/ \\f$ \n\/\/\/ \\Gamma_{32} = \\Gamma_{31} + \\Gamma_{21} \\cos^2\\theta - \n\/\/\/ \\cos\\theta \\sqrt{\\Gamma_{21} (4\\Gamma_{31} - \\Gamma_{21} (1 - \\cos^2\\theta))} \n\/\/\/ \\f$\n\/\/\/\n\/\/\/ This will check if value is changing to keep track of whether\n\/\/\/ the eigensystem needs to be recomputed.\n\/\/\/\n\/\/\/ @param th - decoherence angle\n\/\/\/\nvoid PMNS_Deco::SetDecoAngle(double th)\n{\n\n double cosTh = cos(th);\n\n fGotES *= (fGamma[0] == cosTh);\n\n fGamma[0] = cosTh;\n \n}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Get any given decoherence parameter.\n\/\/\/\n\/\/\/ Requires that i > j. Will notify you if input is wrong.\n\/\/\/ If i < j, will assume reverse order and swap i and j.\n\/\/\/\n\/\/\/ @param i - The first mass index\n\/\/\/ @param j - The second mass index\n\/\/\/\ndouble PMNS_Deco::GetGamma(int i, int j)\n{\n\n if(i < j){\n cout << \"First argument should be larger than second argument\" << endl;\n cout << \"Setting reverse order (Gamma_\" << j << i << \"). \" << endl;\n int temp = i;\n i = j;\n j = temp;\n }\n if(i<1 || i>3 || i <= j || j < 1){\n cout << \"Gamma_\" << i << j << \" not valid for \" << fNumNus;\n cout << \" neutrinos. Returning 0.\" << endl;\n return 0;\n }\n\n if(j == 1){ \n return fGamma[i-1];\n }\n else {\n \/\/ Combine Gamma31, Gamma21 and an angle (fGamma[0] = cos(th)) to make Gamma32\n double arg = fGamma[1] * ( 4*fGamma[2] - fGamma[1]*(1 - pow(fGamma[0],2)) );\n\n return fGamma[2] + fGamma[1]*pow(fGamma[0],2) - fGamma[0] * sqrt(arg);\n\n }\n\n}\n\n\/\/.....................................................................\n\/\/\/ Dot product of two matrices.\n\/\/\/\n\/\/\/ @param A - input matrix A\n\/\/\/ @param B - input matrix B\n\/\/\/\n\/\/\/ @return - matrix A.B\n\/\/\/\nPMNS_Deco::matrix PMNS_Deco::Dot(matrix A, matrix B)\n{\n\n matrix out(3, row(3,0));\n \n for(int i=0; i<3; i++){\n for(int j=0; j<3; j++){\n for(int k=0; k<3; k++){\n\n out[i][j] += A[i][k] * B[k][j];\n\n }}}\n \n return out;\n\n}\n\n\/\/.....................................................................\n\/\/\/ Product of elements of two matrices.\n\/\/\/\n\/\/\/ @param A - input matrix A\n\/\/\/ @param B - input matrix B\n\/\/\/\n\/\/\/ @return - matrix A * B\n\/\/\/\nPMNS_Deco::matrix PMNS_Deco::Mult(matrix A, matrix B)\n{\n\n matrix out(3, row(3,0));\n \n for(int i=0; i<3; i++){\n for(int j=0; j<3; j++){\n \n out[i][j] += A[i][j] * B[i][j];\n\n }}\n \n return out;\n\n}\n\n\/\/.....................................................................\n\/\/\/ Conjugate transpose matrix.\n\/\/\/\n\/\/\/ @param A - input matrix A\n\/\/\/\n\/\/\/ @return - \\f$A^{\\dagger}\\f$\n\/\/\/\nPMNS_Deco::matrix PMNS_Deco::CTransp(matrix A)\n{\n\n matrix out(3, row(3,0));\n \n for(int i=0; i<3; i++){\n for(int j=0; j<3; j++){\n \n out[i][j] += conj(A[j][i]);\n\n }}\n \n return out;\n\n}\n\n\/\/.....................................................................\n\/\/\/\n\/\/\/ Propagate the current neutrino state through a given path\n\/\/\/\n\/\/\/ @param p - A neutrino path segment\n\/\/\/\nvoid PMNS_Deco::PropagatePath(NuPath p)\n{\n\n \/\/ Set the neutrino path\n SetCurPath(p);\n\n \/\/ Solve for eigensystem\n SolveHam();\n \n \/\/ The code below is not pretty or optimised at all. Lots of matrix\n \/\/ multiplications are going on which could be otpimised due to \n \/\/ symmetry. The index sorting is also terrible. Needs improving.\n\n \/\/ Store rotation matrices\n matrix U = fEvec;\n matrix Ut = CTransp(fEvec);\n\n \/\/ Rotate to effective mass basis\n fRho = Dot(Ut, Dot(fRho, U));\n \n \/\/ Compute evolution matrix\n matrix evolve(3, row(3,1));\n \n \/\/ Some ugly way of matching gamma and dmsqr indices\n int maxdm = 0; \n if(fDm[1] > fDm[maxdm]) maxdm = 1;\n if(fDm[2] > fDm[maxdm]) maxdm = 2;\n\n int mindm = 0; \n if(fDm[1] < fDm[mindm]) mindm = 1;\n if(fDm[2] < fDm[mindm]) mindm = 2;\n\n int middm = 0;\n if(middm == maxdm || middm == mindm) middm = 1; \n if(middm == maxdm || middm == mindm) middm = 2; \n\n int maxev = 0; \n if(fEval[1] > fEval[maxev]) maxev = 1;\n if(fEval[2] > fEval[maxev]) maxev = 2;\n\n int minev = 0; \n if(fEval[1] < fEval[minev]) minev = 1;\n if(fEval[2] < fEval[minev]) minev = 2;\n\n int midev = 0;\n if(midev == maxev || midev == minev) midev = 1; \n if(midev == maxev || midev == minev) midev = 2; \n \n int idx[3];\n idx[minev] = mindm;\n idx[midev] = middm;\n idx[maxev] = maxdm;\n \n for(int j=0; j<3; j++){ \n for(int i=0; i\n\/\/\/ 0 = nue, 1 = numu, 2 = nutau\n\/\/\/ 3 = sterile_1, 4 = sterile_2, etc.\n\/\/\/ <\/pre>\n\/\/\/ @param flv - The neutrino starting flavour.\n\/\/\/\nvoid PMNS_Deco::ResetToFlavour(int flv)\n{\n assert(flv>=0 && flv\n\/\/\/ 0 = nue, 1 = numu, 2 = nutau\n\/\/\/ 3 = sterile_1, 4 = sterile_2, etc.\n\/\/\/ <\/pre>\n\/\/\/ @param flv - The neutrino final flavour.\n\/\/\/\n\/\/\/ @return Neutrino oscillation probability\n\/\/\/\ndouble PMNS_Deco::P(int flv)\n{\n assert(flv>=0 && flv"} {"text":"\/*************************************************************************\n *\n * $RCSfile: drdefuno.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2001-09-18 15:15:52 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_DRDEFUNO_HXX\n#define SC_DRDEFUNO_HXX\n\n#ifndef _SVX_UNOPOOL_HXX_\n#include \n#endif\n\n#ifndef _SFXLSTNER_HXX\n#include \n#endif\n\nclass ScDocShell;\n\nclass ScDrawDefaultsObj : public SvxUnoDrawPool, public SfxListener\n{\nprivate:\n ScDocShell* pDocShell;\n\npublic:\n ScDrawDefaultsObj(ScDocShell* pDocSh);\n virtual ~ScDrawDefaultsObj() throw ();\n\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n \/\/ from SvxUnoDrawPool\n virtual SfxItemPool* getModelPool( sal_Bool bReadOnly ) throw();\n};\n\n#endif\n\nINTEGRATION: CWS ooo19126 (1.2.920); FILE MERGED 2005\/09\/05 15:00:45 rt 1.2.920.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: drdefuno.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 17:37:36 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_DRDEFUNO_HXX\n#define SC_DRDEFUNO_HXX\n\n#ifndef _SVX_UNOPOOL_HXX_\n#include \n#endif\n\n#ifndef _SFXLSTNER_HXX\n#include \n#endif\n\nclass ScDocShell;\n\nclass ScDrawDefaultsObj : public SvxUnoDrawPool, public SfxListener\n{\nprivate:\n ScDocShell* pDocShell;\n\npublic:\n ScDrawDefaultsObj(ScDocShell* pDocSh);\n virtual ~ScDrawDefaultsObj() throw ();\n\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n \/\/ from SvxUnoDrawPool\n virtual SfxItemPool* getModelPool( sal_Bool bReadOnly ) throw();\n};\n\n#endif\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: XMLTextListItemContext.hxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 17:07:06 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _XMLTEXTLISTITEMCONTEXT_HXX\n#define _XMLTEXTLISTITEMCONTEXT_HXX\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \"xmlictxt.hxx\"\n#endif\n\nclass XMLTextImportHelper;\n\nclass XMLTextListItemContext : public SvXMLImportContext\n{\n XMLTextImportHelper& rTxtImport;\n\n sal_Int16 nStartValue;\n\n\/\/ SwXMLImport& GetSwImport() { return (SwXMLImport&)GetImport(); }\n\npublic:\n\n TYPEINFO();\n\n XMLTextListItemContext(\n SvXMLImport& rImport,\n XMLTextImportHelper& rTxtImp, sal_uInt16 nPrfx,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList,\n sal_Bool bIsHeader = sal_False );\n virtual ~XMLTextListItemContext();\n\n virtual void EndElement();\n\n SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList );\n\n sal_Bool HasStartValue() const { return -1 != nStartValue; }\n sal_Int16 GetStartValue() const { return nStartValue; }\n};\n\n\n#endif\nINTEGRATION: CWS ooo19126 (1.1.1.1.654); FILE MERGED 2005\/09\/05 14:40:04 rt 1.1.1.1.654.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: XMLTextListItemContext.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 15:23:08 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _XMLTEXTLISTITEMCONTEXT_HXX\n#define _XMLTEXTLISTITEMCONTEXT_HXX\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \"xmlictxt.hxx\"\n#endif\n\nclass XMLTextImportHelper;\n\nclass XMLTextListItemContext : public SvXMLImportContext\n{\n XMLTextImportHelper& rTxtImport;\n\n sal_Int16 nStartValue;\n\n\/\/ SwXMLImport& GetSwImport() { return (SwXMLImport&)GetImport(); }\n\npublic:\n\n TYPEINFO();\n\n XMLTextListItemContext(\n SvXMLImport& rImport,\n XMLTextImportHelper& rTxtImp, sal_uInt16 nPrfx,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList,\n sal_Bool bIsHeader = sal_False );\n virtual ~XMLTextListItemContext();\n\n virtual void EndElement();\n\n SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList );\n\n sal_Bool HasStartValue() const { return -1 != nStartValue; }\n sal_Int16 GetStartValue() const { return nStartValue; }\n};\n\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"BenchTimer.h\"\n#include \"LazyDecodeBitmap.h\"\n#include \"PictureBenchmark.h\"\n#include \"PictureRenderer.h\"\n#include \"SkBenchmark.h\"\n#include \"SkForceLinking.h\"\n#include \"SkGraphics.h\"\n#include \"SkStream.h\"\n#include \"SkString.h\"\n#include \"SkTArray.h\"\n#include \"TimerData.h\"\n\nstatic const int kNumNormalRecordings = SkBENCHLOOP(10);\nstatic const int kNumRTreeRecordings = SkBENCHLOOP(10);\nstatic const int kNumPlaybacks = SkBENCHLOOP(4);\nstatic const size_t kNumBaseBenchmarks = 3;\nstatic const size_t kNumTileSizes = 3;\nstatic const size_t kNumBbhPlaybackBenchmarks = 3;\nstatic const size_t kNumBenchmarks = kNumBaseBenchmarks + kNumBbhPlaybackBenchmarks;\n\nenum BenchmarkType {\n kNormal_BenchmarkType = 0,\n kRTree_BenchmarkType,\n};\n\nstruct Histogram {\n Histogram() {\n \/\/ Make fCpuTime negative so that we don't mess with stats:\n fCpuTime = SkIntToScalar(-1);\n }\n SkScalar fCpuTime;\n SkString fPath;\n};\n\ntypedef void (*BenchmarkFunction)\n (BenchmarkType, const SkISize&, const SkString&, SkPicture*, BenchTimer*);\n\n\/\/ Defined below.\nstatic void benchmark_playback(\n BenchmarkType, const SkISize&, const SkString&, SkPicture*, BenchTimer*);\nstatic void benchmark_recording(\n BenchmarkType, const SkISize&, const SkString&, SkPicture*, BenchTimer*);\n\n\/**\n * Acts as a POD containing information needed to run a benchmark.\n * Provides static methods to poll benchmark info from an index.\n *\/\nstruct BenchmarkControl {\n SkISize fTileSize;\n BenchmarkType fType;\n BenchmarkFunction fFunction;\n SkString fName;\n\n \/**\n * Will construct a BenchmarkControl instance from an index between 0 an kNumBenchmarks.\n *\/\n static BenchmarkControl Make(size_t i) {\n SkASSERT(kNumBenchmarks > i);\n BenchmarkControl benchControl;\n benchControl.fTileSize = getTileSize(i);\n benchControl.fType = getBenchmarkType(i);\n benchControl.fFunction = getBenchmarkFunc(i);\n benchControl.fName = getBenchmarkName(i);\n return benchControl;\n }\n\n enum BaseBenchmarks {\n kNormalRecord = 0,\n kRTreeRecord,\n kNormalPlayback,\n };\n\n static SkISize fTileSizes[kNumTileSizes];\n\n static SkISize getTileSize(size_t i) {\n \/\/ Two of the base benchmarks don't need a tile size. But to maintain simplicity\n \/\/ down the pipeline we have to let a couple of values unused.\n if (i < kNumBaseBenchmarks) {\n return SkISize::Make(256, 256);\n }\n if (i >= kNumBaseBenchmarks && i < kNumBenchmarks) {\n return fTileSizes[i - kNumBaseBenchmarks];\n }\n SkASSERT(0);\n return SkISize::Make(0, 0);\n }\n\n static BenchmarkType getBenchmarkType(size_t i) {\n if (i < kNumBaseBenchmarks) {\n switch (i) {\n case kNormalRecord:\n return kNormal_BenchmarkType;\n case kNormalPlayback:\n return kNormal_BenchmarkType;\n case kRTreeRecord:\n return kRTree_BenchmarkType;\n }\n }\n if (i < kNumBenchmarks) {\n return kRTree_BenchmarkType;\n }\n SkASSERT(0);\n return kRTree_BenchmarkType;\n }\n\n static BenchmarkFunction getBenchmarkFunc(size_t i) {\n \/\/ Base functions.\n switch (i) {\n case kNormalRecord:\n return benchmark_recording;\n case kNormalPlayback:\n return benchmark_playback;\n case kRTreeRecord:\n return benchmark_recording;\n }\n \/\/ RTree playbacks\n if (i < kNumBenchmarks) {\n return benchmark_playback;\n }\n SkASSERT(0);\n return NULL;\n }\n\n static SkString getBenchmarkName(size_t i) {\n \/\/ Base benchmark names\n switch (i) {\n case kNormalRecord:\n return SkString(\"normal_recording\");\n case kNormalPlayback:\n return SkString(\"normal_playback\");\n case kRTreeRecord:\n return SkString(\"rtree_recording\");\n }\n \/\/ RTree benchmark names.\n if (i < kNumBenchmarks) {\n SkASSERT(i >= kNumBaseBenchmarks);\n SkString name;\n name.printf(\"rtree_playback_%dx%d\",\n fTileSizes[i - kNumBaseBenchmarks].fWidth,\n fTileSizes[i - kNumBaseBenchmarks].fHeight);\n return name;\n\n } else {\n SkASSERT(0);\n }\n return SkString(\"\");\n }\n\n};\n\nSkISize BenchmarkControl::fTileSizes[kNumTileSizes] = {\n SkISize::Make(256, 256),\n SkISize::Make(512, 512),\n SkISize::Make(1024, 1024),\n};\n\nstatic SkPicture* pic_from_path(const char path[]) {\n SkFILEStream stream(path);\n if (!stream.isValid()) {\n SkDebugf(\"-- Can't open '%s'\\n\", path);\n return NULL;\n }\n return SkPicture::CreateFromStream(&stream, &sk_tools::LazyDecodeBitmap);\n}\n\n\/**\n * This function is the sink to which all work ends up going.\n * Renders the picture into the renderer. It may or may not use an RTree.\n * The renderer is chosen upstream. If we want to measure recording, we will\n * use a RecordPictureRenderer. If we want to measure rendering, we eill use a\n * TiledPictureRenderer.\n *\/\nstatic void do_benchmark_work(sk_tools::PictureRenderer* renderer,\n int benchmarkType, const SkString& path, SkPicture* pic,\n const int numRepeats, const char *msg, BenchTimer* timer) {\n SkString msgPrefix;\n\n switch (benchmarkType){\n case kNormal_BenchmarkType:\n msgPrefix.set(\"Normal\");\n renderer->setBBoxHierarchyType(sk_tools::PictureRenderer::kNone_BBoxHierarchyType);\n break;\n case kRTree_BenchmarkType:\n msgPrefix.set(\"RTree\");\n renderer->setBBoxHierarchyType(sk_tools::PictureRenderer::kRTree_BBoxHierarchyType);\n break;\n default:\n SkASSERT(0);\n break;\n }\n\n renderer->init(pic);\n\n \/**\n * If the renderer is not tiled, assume we are measuring recording.\n *\/\n bool isPlayback = (NULL != renderer->getTiledRenderer());\n\n SkDebugf(\"%s %s %s %d times...\\n\", msgPrefix.c_str(), msg, path.c_str(), numRepeats);\n for (int i = 0; i < numRepeats; ++i) {\n renderer->setup();\n \/\/ Render once to fill caches.\n renderer->render(NULL);\n \/\/ Render again to measure\n timer->start();\n bool result = renderer->render(NULL);\n timer->end();\n \/\/ We only care about a false result on playback. RecordPictureRenderer::render will always\n \/\/ return false because we are passing a NULL file name on purpose; which is fine.\n if(isPlayback && !result) {\n SkDebugf(\"Error rendering during playback.\\n\");\n }\n }\n renderer->end();\n}\n\n\/**\n * Call do_benchmark_work with a tiled renderer using the default tile dimensions.\n *\/\nstatic void benchmark_playback(\n BenchmarkType benchmarkType, const SkISize& tileSize,\n const SkString& path, SkPicture* pic, BenchTimer* timer) {\n sk_tools::TiledPictureRenderer renderer;\n\n SkString message(\"tiled_playback\");\n message.appendf(\"_%dx%d\", tileSize.fWidth, tileSize.fHeight);\n do_benchmark_work(&renderer, benchmarkType,\n path, pic, kNumPlaybacks, message.c_str(), timer);\n}\n\n\/**\n * Call do_benchmark_work with a RecordPictureRenderer.\n *\/\nstatic void benchmark_recording(\n BenchmarkType benchmarkType, const SkISize& tileSize,\n const SkString& path, SkPicture* pic, BenchTimer* timer) {\n sk_tools::RecordPictureRenderer renderer;\n int numRecordings = 0;\n switch(benchmarkType) {\n case kRTree_BenchmarkType:\n numRecordings = kNumRTreeRecordings;\n break;\n case kNormal_BenchmarkType:\n numRecordings = kNumNormalRecordings;\n break;\n }\n do_benchmark_work(&renderer, benchmarkType, path, pic, numRecordings, \"recording\", timer);\n}\n\n\/**\n * Takes argc,argv along with one of the benchmark functions defined above.\n * Will loop along all skp files and perform measurments.\n *\n * Returns a SkScalar representing CPU time taken during benchmark.\n * As a side effect, it spits the timer result to stdout.\n * Will return -1.0 on error.\n *\/\nstatic bool benchmark_loop(\n int argc,\n char **argv,\n const BenchmarkControl& benchControl,\n SkTArray& histogram) {\n static const SkString timeFormat(\"%f\");\n TimerData timerData(argc - 1);\n for (int index = 1; index < argc; ++index) {\n BenchTimer timer;\n SkString path(argv[index]);\n SkAutoTUnref pic(pic_from_path(path.c_str()));\n if (NULL == pic) {\n SkDebugf(\"Couldn't create picture. Ignoring path: %s\\n\", path.c_str());\n continue;\n }\n benchControl.fFunction(benchControl.fType, benchControl.fTileSize, path, pic, &timer);\n SkAssertResult(timerData.appendTimes(&timer));\n\n histogram[index - 1].fPath = path;\n histogram[index - 1].fCpuTime = SkDoubleToScalar(timer.fCpu);\n }\n\n const SkString timerResult = timerData.getResult(\n \/*doubleFormat = *\/ timeFormat.c_str(),\n \/*result = *\/ TimerData::kAvg_Result,\n \/*configName = *\/ benchControl.fName.c_str(),\n \/*timerFlags = *\/ TimerData::kCpu_Flag);\n\n const char findStr[] = \"= \";\n int pos = timerResult.find(findStr);\n if (-1 == pos) {\n SkDebugf(\"Unexpected output from TimerData::getResult(...). Unable to parse.\");\n return false;\n }\n\n SkScalar cpuTime = SkDoubleToScalar(atof(timerResult.c_str() + pos + sizeof(findStr) - 1));\n if (cpuTime == 0) { \/\/ atof returns 0.0 on error.\n SkDebugf(\"Unable to read value from timer result.\\n\");\n return false;\n }\n return true;\n}\n\nint tool_main(int argc, char** argv);\nint tool_main(int argc, char** argv) {\n SkAutoGraphics ag;\n SkString usage;\n usage.printf(\"Usage: filename [filename]*\\n\");\n\n if (argc < 2) {\n SkDebugf(\"%s\\n\", usage.c_str());\n return -1;\n }\n\n SkTArray histograms[kNumBenchmarks];\n\n for (size_t i = 0; i < kNumBenchmarks; ++i) {\n histograms[i].reset(argc - 1);\n bool success = benchmark_loop(\n argc, argv,\n BenchmarkControl::Make(i),\n histograms[i]);\n if (!success) {\n SkDebugf(\"benchmark_loop failed at index %d\", i);\n }\n }\n\n \/\/ Output gnuplot readable histogram data..\n const char* pbTitle = \"bbh_shootout_playback.dat\";\n const char* recTitle = \"bbh_shootout_record.dat\";\n SkFILEWStream playbackOut(pbTitle);\n SkFILEWStream recordOut(recTitle);\n recordOut.writeText(\"# \");\n playbackOut.writeText(\"# \");\n for (size_t i = 0; i < kNumBenchmarks; ++i) {\n SkString out;\n out.printf(\"%s \", BenchmarkControl::getBenchmarkName(i).c_str());\n if (BenchmarkControl::getBenchmarkFunc(i) == &benchmark_recording) {\n recordOut.writeText(out.c_str());\n }\n if (BenchmarkControl::getBenchmarkFunc(i) == &benchmark_playback) {\n playbackOut.writeText(out.c_str());\n }\n }\n recordOut.writeText(\"\\n\");\n playbackOut.writeText(\"\\n\");\n\n for (int i = 0; i < argc - 1; ++i) {\n SkString pbLine;\n SkString recLine;\n \/\/ ==== Write record info\n recLine.printf(\"%d \", i);\n recLine.appendf(\"%f \", histograms[0][i].fCpuTime); \/\/ Append normal_record time\n recLine.appendf(\"%f\", histograms[1][i].fCpuTime); \/\/ Append rtree_record time\n\n \/\/ ==== Write playback info\n pbLine.printf(\"%d \", i);\n pbLine.appendf(\"%f \", histograms[2][i].fCpuTime); \/\/ Start with normal playback time.\n \/\/ Append all playback benchmark times.\n for (size_t j = kNumBbhPlaybackBenchmarks; j < kNumBenchmarks; ++j) {\n pbLine.appendf(\"%f \", histograms[j][i].fCpuTime);\n }\n pbLine.remove(pbLine.size() - 1, 1); \/\/ Remove trailing space from line.\n pbLine.appendf(\"\\n\");\n recLine.appendf(\"\\n\");\n playbackOut.writeText(pbLine.c_str());\n recordOut.writeText(recLine.c_str());\n }\n SkDebugf(\"\\nWrote data to gnuplot-readable files: %s %s\\n\", pbTitle, recTitle);\n\n return 0;\n}\n\n#if !defined(SK_BUILD_FOR_IOS) && !defined(SK_BUILD_FOR_NACL)\nint main(int argc, char** argv) {\n return tool_main(argc, argv);\n}\n#endif\nAdd correctness test to bbh_shootout.\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"BenchTimer.h\"\n#include \"LazyDecodeBitmap.h\"\n#include \"PictureBenchmark.h\"\n#include \"PictureRenderer.h\"\n#include \"SkBenchmark.h\"\n#include \"SkForceLinking.h\"\n#include \"SkGraphics.h\"\n#include \"SkStream.h\"\n#include \"SkString.h\"\n#include \"SkTArray.h\"\n#include \"TimerData.h\"\n\nstatic const int kNumNormalRecordings = SkBENCHLOOP(10);\nstatic const int kNumRTreeRecordings = SkBENCHLOOP(10);\nstatic const int kNumPlaybacks = SkBENCHLOOP(1);\nstatic const size_t kNumBaseBenchmarks = 3;\nstatic const size_t kNumTileSizes = 3;\nstatic const size_t kNumBbhPlaybackBenchmarks = 3;\nstatic const size_t kNumBenchmarks = kNumBaseBenchmarks + kNumBbhPlaybackBenchmarks;\n\nenum BenchmarkType {\n kNormal_BenchmarkType = 0,\n kRTree_BenchmarkType,\n};\n\nstruct Histogram {\n Histogram() {\n \/\/ Make fCpuTime negative so that we don't mess with stats:\n fCpuTime = SkIntToScalar(-1);\n }\n SkScalar fCpuTime;\n SkString fPath;\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Defined below.\nstruct BenchmarkControl;\n\ntypedef void (*BenchmarkFunction)\n (const BenchmarkControl&, const SkString&, SkPicture*, BenchTimer*);\n\nstatic void benchmark_playback(\n const BenchmarkControl&, const SkString&, SkPicture*, BenchTimer*);\nstatic void benchmark_recording(\n const BenchmarkControl&, const SkString&, SkPicture*, BenchTimer*);\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/**\n * Acts as a POD containing information needed to run a benchmark.\n * Provides static methods to poll benchmark info from an index.\n *\/\nstruct BenchmarkControl {\n SkISize fTileSize;\n BenchmarkType fType;\n BenchmarkFunction fFunction;\n SkString fName;\n\n \/**\n * Will construct a BenchmarkControl instance from an index between 0 an kNumBenchmarks.\n *\/\n static BenchmarkControl Make(size_t i) {\n SkASSERT(kNumBenchmarks > i);\n BenchmarkControl benchControl;\n benchControl.fTileSize = GetTileSize(i);\n benchControl.fType = GetBenchmarkType(i);\n benchControl.fFunction = GetBenchmarkFunc(i);\n benchControl.fName = GetBenchmarkName(i);\n return benchControl;\n }\n\n enum BaseBenchmarks {\n kNormalRecord = 0,\n kRTreeRecord,\n kNormalPlayback,\n };\n\n static SkISize fTileSizes[kNumTileSizes];\n\n static SkISize GetTileSize(size_t i) {\n \/\/ Two of the base benchmarks don't need a tile size. But to maintain simplicity\n \/\/ down the pipeline we have to let a couple of values unused.\n if (i < kNumBaseBenchmarks) {\n return SkISize::Make(256, 256);\n }\n if (i >= kNumBaseBenchmarks && i < kNumBenchmarks) {\n return fTileSizes[i - kNumBaseBenchmarks];\n }\n SkASSERT(0);\n return SkISize::Make(0, 0);\n }\n\n static BenchmarkType GetBenchmarkType(size_t i) {\n if (i < kNumBaseBenchmarks) {\n switch (i) {\n case kNormalRecord:\n return kNormal_BenchmarkType;\n case kNormalPlayback:\n return kNormal_BenchmarkType;\n case kRTreeRecord:\n return kRTree_BenchmarkType;\n }\n }\n if (i < kNumBenchmarks) {\n return kRTree_BenchmarkType;\n }\n SkASSERT(0);\n return kRTree_BenchmarkType;\n }\n\n static BenchmarkFunction GetBenchmarkFunc(size_t i) {\n \/\/ Base functions.\n switch (i) {\n case kNormalRecord:\n return benchmark_recording;\n case kNormalPlayback:\n return benchmark_playback;\n case kRTreeRecord:\n return benchmark_recording;\n }\n \/\/ RTree playbacks\n if (i < kNumBenchmarks) {\n return benchmark_playback;\n }\n SkASSERT(0);\n return NULL;\n }\n\n static SkString GetBenchmarkName(size_t i) {\n \/\/ Base benchmark names\n switch (i) {\n case kNormalRecord:\n return SkString(\"normal_recording\");\n case kNormalPlayback:\n return SkString(\"normal_playback\");\n case kRTreeRecord:\n return SkString(\"rtree_recording\");\n }\n \/\/ RTree benchmark names.\n if (i < kNumBenchmarks) {\n SkASSERT(i >= kNumBaseBenchmarks);\n SkString name;\n name.printf(\"rtree_playback_%dx%d\",\n fTileSizes[i - kNumBaseBenchmarks].fWidth,\n fTileSizes[i - kNumBaseBenchmarks].fHeight);\n return name;\n\n } else {\n SkASSERT(0);\n }\n return SkString(\"\");\n }\n\n};\n\nSkISize BenchmarkControl::fTileSizes[kNumTileSizes] = {\n SkISize::Make(256, 256),\n SkISize::Make(512, 512),\n SkISize::Make(1024, 1024),\n};\n\nstatic SkPicture* pic_from_path(const char path[]) {\n SkFILEStream stream(path);\n if (!stream.isValid()) {\n SkDebugf(\"-- Can't open '%s'\\n\", path);\n return NULL;\n }\n return SkPicture::CreateFromStream(&stream, &sk_tools::LazyDecodeBitmap);\n}\n\n\/**\n * Returns true when a tiled renderer with no bounding box hierarchy produces the given bitmap.\n *\/\nstatic bool compare_picture(const SkString& path, const SkBitmap& inBitmap, SkPicture* pic) {\n SkBitmap* bitmap;\n sk_tools::TiledPictureRenderer renderer;\n renderer.setBBoxHierarchyType(sk_tools::PictureRenderer::kNone_BBoxHierarchyType);\n renderer.init(pic);\n renderer.setup();\n renderer.render(&path, &bitmap);\n SkAutoTDelete bmDeleter(bitmap);\n renderer.end();\n\n if (bitmap->getSize() != inBitmap.getSize()) {\n return false;\n }\n return !memcmp(bitmap->getPixels(), inBitmap.getPixels(), bitmap->getSize());\n}\n\n\/**\n * This function is the sink to which all work ends up going.\n * Renders the picture into the renderer. It may or may not use an RTree.\n * The renderer is chosen upstream. If we want to measure recording, we will\n * use a RecordPictureRenderer. If we want to measure rendering, we will use a\n * TiledPictureRenderer.\n *\/\nstatic void do_benchmark_work(sk_tools::PictureRenderer* renderer,\n int benchmarkType, const SkString& path, SkPicture* pic,\n const int numRepeats, const char *msg, BenchTimer* timer) {\n SkString msgPrefix;\n\n switch (benchmarkType){\n case kNormal_BenchmarkType:\n msgPrefix.set(\"Normal\");\n renderer->setBBoxHierarchyType(sk_tools::PictureRenderer::kNone_BBoxHierarchyType);\n break;\n case kRTree_BenchmarkType:\n msgPrefix.set(\"RTree\");\n renderer->setBBoxHierarchyType(sk_tools::PictureRenderer::kRTree_BBoxHierarchyType);\n break;\n default:\n SkASSERT(0);\n break;\n }\n\n renderer->init(pic);\n\n \/**\n * If the renderer is not tiled, assume we are measuring recording.\n *\/\n bool isPlayback = (NULL != renderer->getTiledRenderer());\n \/\/ Will be non-null during RTree picture playback. For correctness test.\n SkBitmap* bitmap = NULL;\n\n SkDebugf(\"%s %s %s %d times...\\n\", msgPrefix.c_str(), msg, path.c_str(), numRepeats);\n for (int i = 0; i < numRepeats; ++i) {\n \/\/ Set up the bitmap.\n SkBitmap** out = NULL;\n if (i == 0 && kRTree_BenchmarkType == benchmarkType && isPlayback) {\n out = &bitmap;\n }\n\n renderer->setup();\n \/\/ Render once to fill caches.\n renderer->render(NULL);\n \/\/ Render again to measure\n timer->start();\n bool result = renderer->render(NULL, out);\n timer->end();\n\n \/\/ We only care about a false result on playback. RecordPictureRenderer::render will always\n \/\/ return false because we are passing a NULL file name on purpose; which is fine.\n if (isPlayback && !result) {\n SkDebugf(\"Error rendering during playback.\\n\");\n }\n }\n if (bitmap) {\n SkAutoTDelete bmDeleter(bitmap);\n if (!compare_picture(path, *bitmap, pic)) {\n SkDebugf(\"Error: RTree produced different bitmap\\n\");\n }\n }\n}\n\n\/**\n * Call do_benchmark_work with a tiled renderer using the default tile dimensions.\n *\/\nstatic void benchmark_playback(\n const BenchmarkControl& benchControl,\n const SkString& path, SkPicture* pic, BenchTimer* timer) {\n sk_tools::TiledPictureRenderer renderer;\n\n SkString message(\"tiled_playback\");\n message.appendf(\"_%dx%d\", benchControl.fTileSize.fWidth, benchControl.fTileSize.fHeight);\n do_benchmark_work(&renderer, benchControl.fType,\n path, pic, kNumPlaybacks, message.c_str(), timer);\n}\n\n\/**\n * Call do_benchmark_work with a RecordPictureRenderer.\n *\/\nstatic void benchmark_recording(\n const BenchmarkControl& benchControl,\n const SkString& path, SkPicture* pic, BenchTimer* timer) {\n sk_tools::RecordPictureRenderer renderer;\n int numRecordings = 0;\n switch(benchControl.fType) {\n case kRTree_BenchmarkType:\n numRecordings = kNumRTreeRecordings;\n break;\n case kNormal_BenchmarkType:\n numRecordings = kNumNormalRecordings;\n break;\n }\n do_benchmark_work(&renderer, benchControl.fType,\n path, pic, numRecordings, \"recording\", timer);\n}\n\n\/**\n * Takes argc,argv along with one of the benchmark functions defined above.\n * Will loop along all skp files and perform measurments.\n *\n * Returns a SkScalar representing CPU time taken during benchmark.\n * As a side effect, it spits the timer result to stdout.\n * Will return -1.0 on error.\n *\/\nstatic bool benchmark_loop(\n int argc,\n char **argv,\n const BenchmarkControl& benchControl,\n SkTArray& histogram) {\n static const SkString timeFormat(\"%f\");\n TimerData timerData(argc - 1);\n for (int index = 1; index < argc; ++index) {\n BenchTimer timer;\n SkString path(argv[index]);\n SkAutoTUnref pic(pic_from_path(path.c_str()));\n if (NULL == pic) {\n SkDebugf(\"Couldn't create picture. Ignoring path: %s\\n\", path.c_str());\n continue;\n }\n benchControl.fFunction(benchControl, path, pic, &timer);\n\n histogram[index - 1].fPath = path;\n histogram[index - 1].fCpuTime = SkDoubleToScalar(timer.fCpu);\n }\n\n const SkString timerResult = timerData.getResult(\n \/*doubleFormat = *\/ timeFormat.c_str(),\n \/*result = *\/ TimerData::kAvg_Result,\n \/*configName = *\/ benchControl.fName.c_str(),\n \/*timerFlags = *\/ TimerData::kCpu_Flag);\n\n const char findStr[] = \"= \";\n int pos = timerResult.find(findStr);\n if (-1 == pos) {\n SkDebugf(\"Unexpected output from TimerData::getResult(...). Unable to parse.\\n\");\n return false;\n }\n\n SkScalar cpuTime = SkDoubleToScalar(atof(timerResult.c_str() + pos + sizeof(findStr) - 1));\n if (cpuTime == 0) { \/\/ atof returns 0.0 on error.\n SkDebugf(\"Unable to read value from timer result.\\n\");\n return false;\n }\n return true;\n}\n\nint tool_main(int argc, char** argv);\nint tool_main(int argc, char** argv) {\n SkAutoGraphics ag;\n SkString usage;\n usage.printf(\"Usage: filename [filename]*\\n\");\n\n if (argc < 2) {\n SkDebugf(\"%s\\n\", usage.c_str());\n return -1;\n }\n\n SkTArray histograms[kNumBenchmarks];\n\n for (size_t i = 0; i < kNumBenchmarks; ++i) {\n histograms[i].reset(argc - 1);\n bool success = benchmark_loop(\n argc, argv,\n BenchmarkControl::Make(i),\n histograms[i]);\n if (!success) {\n SkDebugf(\"benchmark_loop failed at index %d\\n\", i);\n }\n }\n\n \/\/ Output gnuplot readable histogram data..\n const char* pbTitle = \"bbh_shootout_playback.dat\";\n const char* recTitle = \"bbh_shootout_record.dat\";\n SkFILEWStream playbackOut(pbTitle);\n SkFILEWStream recordOut(recTitle);\n recordOut.writeText(\"# \");\n playbackOut.writeText(\"# \");\n for (size_t i = 0; i < kNumBenchmarks; ++i) {\n SkString out;\n out.printf(\"%s \", BenchmarkControl::GetBenchmarkName(i).c_str());\n if (BenchmarkControl::GetBenchmarkFunc(i) == &benchmark_recording) {\n recordOut.writeText(out.c_str());\n }\n if (BenchmarkControl::GetBenchmarkFunc(i) == &benchmark_playback) {\n playbackOut.writeText(out.c_str());\n }\n }\n recordOut.writeText(\"\\n\");\n playbackOut.writeText(\"\\n\");\n \/\/ Write to file, and save recording averages.\n SkScalar avgRecord = SkIntToScalar(0);\n SkScalar avgRecordRTree = SkIntToScalar(0);\n for (int i = 0; i < argc - 1; ++i) {\n SkString pbLine;\n SkString recLine;\n \/\/ ==== Write record info\n recLine.printf(\"%d \", i);\n SkScalar cpuTime = histograms[BenchmarkControl::kNormalRecord][i].fCpuTime;\n recLine.appendf(\"%f \", cpuTime);\n avgRecord += cpuTime;\n cpuTime = histograms[BenchmarkControl::kRTreeRecord][i].fCpuTime;\n recLine.appendf(\"%f\", cpuTime);\n avgRecordRTree += cpuTime;\n\n \/\/ ==== Write playback info\n pbLine.printf(\"%d \", i);\n pbLine.appendf(\"%f \", histograms[2][i].fCpuTime); \/\/ Start with normal playback time.\n \/\/ Append all playback benchmark times.\n for (size_t j = kNumBbhPlaybackBenchmarks; j < kNumBenchmarks; ++j) {\n pbLine.appendf(\"%f \", histograms[j][i].fCpuTime);\n }\n pbLine.remove(pbLine.size() - 1, 1); \/\/ Remove trailing space from line.\n pbLine.appendf(\"\\n\");\n recLine.appendf(\"\\n\");\n playbackOut.writeText(pbLine.c_str());\n recordOut.writeText(recLine.c_str());\n }\n avgRecord \/= argc - 1;\n avgRecordRTree \/= argc - 1;\n SkDebugf(\"Average base recording time: %.3fms\\n\", avgRecord);\n SkDebugf(\"Average recording time with rtree: %.3fms\\n\", avgRecordRTree);\n SkDebugf(\"\\nWrote data to gnuplot-readable files: %s %s\\n\", pbTitle, recTitle);\n\n return 0;\n}\n\n#if !defined(SK_BUILD_FOR_IOS) && !defined(SK_BUILD_FOR_NACL)\nint main(int argc, char** argv) {\n return tool_main(argc, argv);\n}\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nqiLogCategory(\"qimessaging.jni.test\");\n\n\nint main(int argc, char** argv)\n{\n \/\/ Avoid making a qi::Application. Real Java apps cannot do it.\n qi::log::addFilter(\"qimessaging.jni\", qi::LogLevel_Debug);\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n\n\nclass QiJNI: public ::testing::Test\n{\nprotected:\n static void SetUpTestCase()\n {\n JavaVMOption options[1];\n JavaVMInitArgs vm_args;\n long status;\n\n char classPathDefinition[] = \"-Djava.class.path=.\";\n options[0].optionString = classPathDefinition;\n memset(&vm_args, 0, sizeof(vm_args));\n vm_args.version = JNI_VERSION_1_6;\n vm_args.nOptions = 1;\n vm_args.options = options;\n status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);\n\n if (status == JNI_ERR)\n throw std::runtime_error(\"Failed to set a JVM up\");\n jvm->AttachCurrentThread((void**)&env, nullptr);\n\n \/\/ Real Java apps will always call this when loading the library.\n JNI_OnLoad(jvm, nullptr);\n\n Java_com_aldebaran_qi_EmbeddedTools_initTypeSystem(env, jclass{});\n }\n\n static void TearDownTestCase()\n {\n if (jvm)\n jvm->DestroyJavaVM();\n }\n\n static JNIEnv* env;\n static JavaVM* jvm;\n};\n\nJNIEnv* QiJNI::env = nullptr;\nJavaVM* QiJNI::jvm = nullptr;\n\ntemplate \nqi::AnyObject makeObjectWithProperty(const std::string& propertyName, qi::Property& property)\n{\n qi::DynamicObjectBuilder objectBuilder;\n objectBuilder.advertiseProperty(propertyName, &property);\n return objectBuilder.object();\n}\n\nTEST_F(QiJNI, setProperty)\n{\n const int initialValue = 12;\n const int newValue = 42;\n qi::Property property{initialValue};\n\n const std::string propertyName = \"serendipity\";\n auto object = makeObjectWithProperty(propertyName, property);\n auto objectPtr = &object;\n\n qi::jni::JNIAttach attach{env};\n auto futureAddress = Java_com_aldebaran_qi_AnyObject_setProperty(\n env, jobject{},\n reinterpret_cast(objectPtr),\n qi::jni::toJstring(propertyName),\n JObject_from_AnyValue(qi::AnyValue{newValue}.asReference()));\n\n auto future = reinterpret_cast*>(futureAddress);\n auto status = future->waitFor(qi::MilliSeconds{200});\n ASSERT_EQ(qi::FutureState_FinishedWithValue, status);\n ASSERT_EQ(newValue, object.property(propertyName).value());\n}\n\nTEST_F(QiJNI, futureErrorIfSetPropertyThrows)\n{\n using CustomException = std::exception;\n const int initialValue = 12;\n const int newValue = 42;\n qi::Property property{initialValue, qi::Property::Getter{}, [this](int&, const int&)->bool\n {\n throw CustomException{};\n }};\n\n const std::string propertyName = \"serendipity\";\n auto object = makeObjectWithProperty(propertyName, property);\n auto objectPtr = &object;\n\n qi::jni::JNIAttach attach{env};\n auto futureAddress = Java_com_aldebaran_qi_AnyObject_setProperty(\n env, jobject{},\n reinterpret_cast(objectPtr),\n qi::jni::toJstring(propertyName),\n JObject_from_AnyValue(qi::AnyValue{newValue}.asReference()));\n\n auto future = reinterpret_cast*>(futureAddress);\n auto status = future->waitFor(qi::MilliSeconds{200});\n ASSERT_EQ(qi::FutureState_FinishedWithError, status);\n ASSERT_EQ(initialValue, object.property(propertyName).value());\n}\nJNI: new test demonstrates a simple use of DynamicObject.advertiseMethod#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nqiLogCategory(\"qimessaging.jni.test\");\n\n\nint main(int argc, char** argv)\n{\n \/\/ Avoid making a qi::Application. Real Java apps cannot do it.\n qi::log::addFilter(\"qimessaging.jni\", qi::LogLevel_Debug);\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n\n\nclass QiJNI: public ::testing::Test\n{\nprotected:\n static void SetUpTestCase()\n {\n JavaVMOption options[1];\n JavaVMInitArgs vm_args;\n long status;\n\n char classPathDefinition[] = \"-Djava.class.path=.\";\n options[0].optionString = classPathDefinition;\n memset(&vm_args, 0, sizeof(vm_args));\n vm_args.version = JNI_VERSION_1_6;\n vm_args.nOptions = 1;\n vm_args.options = options;\n status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);\n\n if (status == JNI_ERR)\n throw std::runtime_error(\"Failed to set a JVM up\");\n jvm->AttachCurrentThread((void**)&env, nullptr);\n\n \/\/ Real Java apps will always call this when loading the library.\n JNI_OnLoad(jvm, nullptr);\n\n Java_com_aldebaran_qi_EmbeddedTools_initTypeSystem(env, jclass{});\n }\n\n static void TearDownTestCase()\n {\n if (jvm)\n jvm->DestroyJavaVM();\n }\n\n static JNIEnv* env;\n static JavaVM* jvm;\n};\n\nJNIEnv* QiJNI::env = nullptr;\nJavaVM* QiJNI::jvm = nullptr;\n\ntemplate \nqi::AnyObject makeObjectWithProperty(const std::string& propertyName, qi::Property& property)\n{\n qi::DynamicObjectBuilder objectBuilder;\n objectBuilder.advertiseProperty(propertyName, &property);\n return objectBuilder.object();\n}\n\nTEST_F(QiJNI, setProperty)\n{\n const int initialValue = 12;\n const int newValue = 42;\n qi::Property property{initialValue};\n\n const std::string propertyName = \"serendipity\";\n auto object = makeObjectWithProperty(propertyName, property);\n auto objectPtr = &object;\n\n qi::jni::JNIAttach attach{env};\n auto futureAddress = Java_com_aldebaran_qi_AnyObject_setProperty(\n env, jobject{},\n reinterpret_cast(objectPtr),\n qi::jni::toJstring(propertyName),\n JObject_from_AnyValue(qi::AnyValue{newValue}.asReference()));\n\n auto future = reinterpret_cast*>(futureAddress);\n auto status = future->waitFor(qi::MilliSeconds{200});\n ASSERT_EQ(qi::FutureState_FinishedWithValue, status);\n ASSERT_EQ(newValue, object.property(propertyName).value());\n}\n\nTEST_F(QiJNI, futureErrorIfSetPropertyThrows)\n{\n using CustomException = std::exception;\n const int initialValue = 12;\n const int newValue = 42;\n qi::Property property{initialValue, qi::Property::Getter{}, [this](int&, const int&)->bool\n {\n throw CustomException{};\n }};\n\n const std::string propertyName = \"serendipity\";\n auto object = makeObjectWithProperty(propertyName, property);\n auto objectPtr = &object;\n\n qi::jni::JNIAttach attach{env};\n auto futureAddress = Java_com_aldebaran_qi_AnyObject_setProperty(\n env, jobject{},\n reinterpret_cast(objectPtr),\n qi::jni::toJstring(propertyName),\n JObject_from_AnyValue(qi::AnyValue{newValue}.asReference()));\n\n auto future = reinterpret_cast*>(futureAddress);\n auto status = future->waitFor(qi::MilliSeconds{200});\n ASSERT_EQ(qi::FutureState_FinishedWithError, status);\n ASSERT_EQ(initialValue, object.property(propertyName).value());\n}\n\n\nTEST_F(QiJNI, dynamicObjectBuilderAdvertiseMethodVoidVoid)\n{\n \/\/ Object.notify() is a typical example of function taking and returning nothing.\n const auto javaObjectClassName = \"java\/lang\/Object\";\n const auto javaObjectClass = env->FindClass(javaObjectClassName);\n const auto javaObjectConstructor = env->GetMethodID(javaObjectClass, \"\", \"()V\");\n const auto javaObject = env->NewObject(javaObjectClass, javaObjectConstructor);\n\n \/\/ Let's make a Qi Object calling that method.\n const auto objectBuilderAddress = Java_com_aldebaran_qi_DynamicObjectBuilder_create(env, nullptr);\n env->ExceptionClear();\n Java_com_aldebaran_qi_DynamicObjectBuilder_advertiseMethod(\n env, jobject{},\n objectBuilderAddress,\n qi::jni::toJstring(\"notify::v()\"), javaObject, \/\/ 'v' stands for \"void\"\n qi::jni::toJstring(javaObjectClassName),\n qi::jni::toJstring(\"Whatever\"));\n ASSERT_FALSE(env->ExceptionCheck());\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SC_MATRIX_HXX\n#define SC_MATRIX_HXX\n\n#include \"global.hxx\"\n#include \"formula\/intruref.hxx\"\n#include \"formula\/errorcodes.hxx\"\n#include \n#include \"scdllapi.h\"\n\nclass SvStream;\nclass ScInterpreter;\nclass SvNumberFormatter;\nclass ScMatrixImpl;\n\ntypedef BYTE ScMatValType;\nconst ScMatValType SC_MATVAL_VALUE = 0x00;\nconst ScMatValType SC_MATVAL_BOOLEAN = 0x01;\nconst ScMatValType SC_MATVAL_STRING = 0x02;\nconst ScMatValType SC_MATVAL_EMPTY = SC_MATVAL_STRING | 0x04; \/\/ STRING plus flag\nconst ScMatValType SC_MATVAL_EMPTYPATH = SC_MATVAL_EMPTY | 0x08; \/\/ EMPTY plus flag\nconst ScMatValType SC_MATVAL_NONVALUE = SC_MATVAL_EMPTYPATH; \/\/ mask of all non-value bits\n\nstruct ScMatrixValue\n{\n union {\n double fVal;\n const String* pS;\n };\n ScMatValType nType;\n\n \/\/\/ Only valid if ScMatrix methods indicate so!\n const String& GetString() const { return pS ? *pS : EMPTY_STRING; }\n\n \/\/\/ Only valid if ScMatrix methods indicate that this is no string!\n USHORT GetError() const { return GetDoubleErrorValue( fVal); }\n\n \/\/\/ Only valid if ScMatrix methods indicate that this is a boolean\n bool GetBoolean() const { return fVal != 0.0; }\n\n ScMatrixValue() : pS(NULL), nType(SC_MATVAL_EMPTY) {}\n\n ScMatrixValue(const ScMatrixValue& r) : nType(r.nType)\n {\n switch (nType)\n {\n case SC_MATVAL_VALUE:\n case SC_MATVAL_BOOLEAN:\n fVal = r.fVal;\n break;\n default:\n pS = r.pS;\n }\n }\n\n bool operator== (const ScMatrixValue& r) const\n {\n if (nType != r.nType)\n return false;\n\n switch (nType)\n {\n case SC_MATVAL_VALUE:\n case SC_MATVAL_BOOLEAN:\n return fVal == r.fVal;\n break;\n default:\n ;\n }\n if (!pS)\n return r.pS == NULL;\n\n return GetString().Equals(r.GetString());\n }\n\n bool operator!= (const ScMatrixValue& r) const\n {\n return !operator==(r);\n }\n\n ScMatrixValue& operator= (const ScMatrixValue& r)\n {\n nType = r.nType;\n switch (nType)\n {\n case SC_MATVAL_VALUE:\n case SC_MATVAL_BOOLEAN:\n fVal = r.fVal;\n break;\n default:\n pS = r.pS;\n }\n return *this;\n }\n};\n\n\/** Matrix representation of double values and strings.\n\n @ATTENTION: optimized for speed and double values.\n\n

Matrix elements are NOT initialized after construction!\n\n

All methods using an SCSIZE nIndex parameter and all Is...() methods do\n NOT check the range for validity! However, the Put...() and Get...()\n methods using nCol\/nRow parameters do check the range.\n\n

Methods using nCol\/nRow parameters do replicate a single row vector if\n nRow > 0 and nCol < nColCount, respectively a column vector if nCol\n > 0 and nRow < nRowCount.\n\n

GetString( SCSIZE nIndex ) does not check if there really is a string,\n do this with IsString() first. GetString( SCSIZE nC, SCSIZE nR ) does check\n it and returns and empty string if there is no string. Both GetDouble()\n methods don't check for a string, do this with IsNumeric() or IsString() or\n IsValue() first.\n\n

The GetString( SvNumberFormatter&, ...) methods return the matrix\n element's string if one is present, otherwise the numerical value is\n formatted as a string, or in case of an error the error string is returned.\n\n

PutDouble() does not reset an eventual string! Use\n PutDoubleAndResetString() if that is wanted. Also the FillDouble...()\n methods don't reset strings. As a consequence memory leaks may occur if\n used wrong.\n *\/\nclass SC_DLLPUBLIC ScMatrix\n{\n ScMatrixImpl* pImpl;\n mutable ULONG nRefCnt; \/\/ reference count\n\n \/\/ only delete via Delete()\n ~ScMatrix();\n\n \/\/ not implemented, prevent usage\n ScMatrix( const ScMatrix& );\n ScMatrix& operator=( const ScMatrix&);\n\npublic:\n enum DensityType\n {\n FILLED_ZERO,\n FILLED_EMPTY,\n SPARSE_ZERO,\n SPARSE_EMPTY\n };\n\n \/\/\/ The maximum number of elements a matrix may have at runtime.\n inline static size_t GetElementsMax()\n {\n \/\/ Roughly 125MB in total, divided by 8+1 per element => 14M elements.\n const size_t nMemMax = 0x08000000 \/ (sizeof(ScMatrixValue) + sizeof(ScMatValType));\n \/\/ With MAXROWCOUNT==65536 and 128 columns => 8M elements ~72MB.\n const size_t nArbitraryLimit = (size_t)MAXROWCOUNT * 128;\n \/\/ Stuffed with a million rows would limit this to 14 columns.\n return nMemMax < nArbitraryLimit ? nMemMax : nArbitraryLimit;\n }\n\n \/\/\/ Value or boolean.\n inline static bool IsValueType( ScMatValType nType )\n {\n return nType <= SC_MATVAL_BOOLEAN;\n }\n\n \/\/\/ Boolean.\n inline static bool IsBooleanType( ScMatValType nType )\n {\n return nType == SC_MATVAL_BOOLEAN;\n }\n\n \/\/\/ String, empty or empty path, but not value nor boolean.\n inline static bool IsNonValueType( ScMatValType nType )\n {\n return (nType & SC_MATVAL_NONVALUE) != 0;\n }\n\n \/** String, but not empty or empty path or any other type.\n Not named IsStringType to prevent confusion because previously\n IsNonValueType was named IsStringType. *\/\n inline static bool IsRealStringType( ScMatValType nType )\n {\n return (nType & SC_MATVAL_NONVALUE) == SC_MATVAL_STRING;\n }\n\n \/\/\/ Empty, but not empty path or any other type.\n inline static bool IsEmptyType( ScMatValType nType )\n {\n return (nType & SC_MATVAL_NONVALUE) == SC_MATVAL_EMPTY;\n }\n\n \/\/\/ Empty path, but not empty or any other type.\n inline static bool IsEmptyPathType( ScMatValType nType )\n {\n return (nType & SC_MATVAL_NONVALUE) == SC_MATVAL_EMPTYPATH;\n }\n\n \/** If nC*nR results in more than GetElementsMax() entries, a 1x1 matrix is\n created instead and a double error value (errStackOverflow) is set.\n Compare nC and nR with a GetDimensions() call to check. *\/\n ScMatrix( SCSIZE nC, SCSIZE nR, DensityType eType = FILLED_ZERO);\n\n \/** Clone the matrix. *\/\n ScMatrix* Clone() const;\n ScMatrix* Clone( DensityType eType) const;\n\n \/** Clone the matrix if mbCloneIfConst (immutable) is set, otherwise\n return _this_ matrix, to be assigned to a ScMatrixRef. *\/\n ScMatrix* CloneIfConst();\n\n \/** Set the matrix to (im)mutable for CloneIfConst(), only the interpreter\n should do this and know the consequences. *\/\n void SetImmutable( bool bVal );\n\n \/**\n * Resize the matrix to specified new dimension. Note that this operation\n * clears all stored values.\n *\/\n void Resize( SCSIZE nC, SCSIZE nR);\n\n \/** Clone the matrix and extend it to the new size. nNewCols and nNewRows\n MUST be at least of the size of the original matrix. *\/\n ScMatrix* CloneAndExtend( SCSIZE nNewCols, SCSIZE nNewRows, DensityType eType) const;\n\n \/\/\/ Disable refcounting forever, may only be deleted via Delete() afterwards.\n inline void SetEternalRef() { nRefCnt = ULONG_MAX; }\n inline bool IsEternalRef() const { return nRefCnt == ULONG_MAX; }\n inline void IncRef() const\n {\n if ( !IsEternalRef() )\n ++nRefCnt;\n }\n inline void DecRef() const\n {\n if ( nRefCnt > 0 && !IsEternalRef() )\n if ( --nRefCnt == 0 )\n delete this;\n }\n inline void Delete()\n {\n if ( nRefCnt == 0 || IsEternalRef() )\n delete this;\n else\n --nRefCnt;\n }\n\n DensityType GetDensityType() const;\n void SetErrorInterpreter( ScInterpreter* p);\n void GetDimensions( SCSIZE& rC, SCSIZE& rR) const;\n SCSIZE GetElementCount() const;\n bool ValidColRow( SCSIZE nC, SCSIZE nR) const;\n SCSIZE CalcOffset( SCSIZE nC, SCSIZE nR) const;\n\n \/** For a row vector or column vector, if the position does not point into\n the vector but is a valid column or row offset it is adapted such that\n it points to an element to be replicated, same column row 0 for a row\n vector, same row column 0 for a column vector. Else, for a 2D matrix,\n returns false.\n *\/\n bool ValidColRowReplicated( SCSIZE & rC, SCSIZE & rR ) const;\n\n \/** Checks if the matrix position is within the matrix. If it is not, for a\n row vector or column vector the position is adapted such that it points\n to an element to be replicated, same column row 0 for a row vector,\n same row column 0 for a column vector. Else, for a 2D matrix and\n position not within matrix, returns false.\n *\/\n bool ValidColRowOrReplicated( SCSIZE & rC, SCSIZE & rR ) const;\n\n void PutDouble( double fVal, SCSIZE nC, SCSIZE nR);\n void PutDouble( double fVal, SCSIZE nIndex);\n void PutString( const String& rStr, SCSIZE nC, SCSIZE nR);\n void PutString( const String& rStr, SCSIZE nIndex);\n void PutEmpty( SCSIZE nC, SCSIZE nR);\n \/\/\/ Jump FALSE without path\n void PutEmptyPath( SCSIZE nC, SCSIZE nR);\n void PutError( USHORT nErrorCode, SCSIZE nC, SCSIZE nR );\n void PutBoolean( bool bVal, SCSIZE nC, SCSIZE nR);\n\n void FillDouble( double fVal,\n SCSIZE nC1, SCSIZE nR1, SCSIZE nC2, SCSIZE nR2 );\n\n \/** May be used before obtaining the double value of an element to avoid\n passing its NAN around.\n @ATTENTION: MUST NOT be used if the element is a string!\n Use GetErrorIfNotString() instead if not sure.\n @returns 0 if no error, else one of err... constants *\/\n USHORT GetError( SCSIZE nC, SCSIZE nR) const;\n\n \/** Use in ScInterpreter to obtain the error code, if any.\n @returns 0 if no error or string element, else one of err... constants *\/\n USHORT GetErrorIfNotString( SCSIZE nC, SCSIZE nR) const\n { return IsValue( nC, nR) ? GetError( nC, nR) : 0; }\n\n \/\/\/ @return 0.0 if empty or empty path, else value or DoubleError.\n double GetDouble( SCSIZE nC, SCSIZE nR) const;\n \/\/\/ @return 0.0 if empty or empty path, else value or DoubleError.\n double GetDouble( SCSIZE nIndex) const;\n\n \/\/\/ @return empty string if empty or empty path, else string content.\n const String& GetString( SCSIZE nC, SCSIZE nR) const;\n \/\/\/ @return empty string if empty or empty path, else string content.\n const String& GetString( SCSIZE nIndex) const;\n\n \/** @returns the matrix element's string if one is present, otherwise the\n numerical value formatted as string, or in case of an error the error\n string is returned; an empty string for empty, a \"FALSE\" string for\n empty path. *\/\n String GetString( SvNumberFormatter& rFormatter, SCSIZE nC, SCSIZE nR) const;\n\n \/\/\/ @ATTENTION: If bString the ScMatrixValue->pS may still be NULL to indicate\n \/\/\/ an empty string!\n ScMatrixValue Get( SCSIZE nC, SCSIZE nR) const;\n\n \/\/\/ @return if string or empty or empty path, in fact non-value.\n BOOL IsString( SCSIZE nIndex ) const;\n\n \/\/\/ @return if string or empty or empty path, in fact non-value.\n BOOL IsString( SCSIZE nC, SCSIZE nR ) const;\n\n \/\/\/ @return if empty or empty path.\n BOOL IsEmpty( SCSIZE nC, SCSIZE nR ) const;\n\n \/\/\/ @return if empty path.\n BOOL IsEmptyPath( SCSIZE nC, SCSIZE nR ) const;\n\n \/\/\/ @return if value or boolean.\n BOOL IsValue( SCSIZE nIndex ) const;\n\n \/\/\/ @return if value or boolean.\n BOOL IsValue( SCSIZE nC, SCSIZE nR ) const;\n\n \/\/\/ @return if value or boolean or empty or empty path.\n BOOL IsValueOrEmpty( SCSIZE nC, SCSIZE nR ) const;\n\n \/\/\/ @return if boolean.\n BOOL IsBoolean( SCSIZE nC, SCSIZE nR ) const;\n\n \/\/\/ @return if entire matrix is numeric, including booleans, with no strings or empties\n BOOL IsNumeric() const;\n\n void MatTrans( ScMatrix& mRes) const;\n void MatCopy ( ScMatrix& mRes) const;\n\n \/\/ Convert ScInterpreter::CompareMat values (-1,0,1) to boolean values\n void CompareEqual();\n void CompareNotEqual();\n void CompareLess();\n void CompareGreater();\n void CompareLessEqual();\n void CompareGreaterEqual();\n\n double And(); \/\/ logical AND of all matrix values, or NAN\n double Or(); \/\/ logical OR of all matrix values, or NAN\n\n \/\/ All other matrix functions MatMult, MInv, ... are in ScInterpreter\n \/\/ to be numerically safe.\n};\n\n\ntypedef formula::SimpleIntrusiveReference< class ScMatrix > ScMatrixRef;\ntypedef formula::SimpleIntrusiveReference< const class ScMatrix > ScConstMatrixRef;\n\n\n#endif \/\/ SC_MATRIX_HXX\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nRe-wrote header description for ScMatrix.\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SC_MATRIX_HXX\n#define SC_MATRIX_HXX\n\n#include \"global.hxx\"\n#include \"formula\/intruref.hxx\"\n#include \"formula\/errorcodes.hxx\"\n#include \n#include \"scdllapi.h\"\n\nclass SvStream;\nclass ScInterpreter;\nclass SvNumberFormatter;\nclass ScMatrixImpl;\n\ntypedef BYTE ScMatValType;\nconst ScMatValType SC_MATVAL_VALUE = 0x00;\nconst ScMatValType SC_MATVAL_BOOLEAN = 0x01;\nconst ScMatValType SC_MATVAL_STRING = 0x02;\nconst ScMatValType SC_MATVAL_EMPTY = SC_MATVAL_STRING | 0x04; \/\/ STRING plus flag\nconst ScMatValType SC_MATVAL_EMPTYPATH = SC_MATVAL_EMPTY | 0x08; \/\/ EMPTY plus flag\nconst ScMatValType SC_MATVAL_NONVALUE = SC_MATVAL_EMPTYPATH; \/\/ mask of all non-value bits\n\nstruct ScMatrixValue\n{\n union {\n double fVal;\n const String* pS;\n };\n ScMatValType nType;\n\n \/\/\/ Only valid if ScMatrix methods indicate so!\n const String& GetString() const { return pS ? *pS : EMPTY_STRING; }\n\n \/\/\/ Only valid if ScMatrix methods indicate that this is no string!\n USHORT GetError() const { return GetDoubleErrorValue( fVal); }\n\n \/\/\/ Only valid if ScMatrix methods indicate that this is a boolean\n bool GetBoolean() const { return fVal != 0.0; }\n\n ScMatrixValue() : pS(NULL), nType(SC_MATVAL_EMPTY) {}\n\n ScMatrixValue(const ScMatrixValue& r) : nType(r.nType)\n {\n switch (nType)\n {\n case SC_MATVAL_VALUE:\n case SC_MATVAL_BOOLEAN:\n fVal = r.fVal;\n break;\n default:\n pS = r.pS;\n }\n }\n\n bool operator== (const ScMatrixValue& r) const\n {\n if (nType != r.nType)\n return false;\n\n switch (nType)\n {\n case SC_MATVAL_VALUE:\n case SC_MATVAL_BOOLEAN:\n return fVal == r.fVal;\n break;\n default:\n ;\n }\n if (!pS)\n return r.pS == NULL;\n\n return GetString().Equals(r.GetString());\n }\n\n bool operator!= (const ScMatrixValue& r) const\n {\n return !operator==(r);\n }\n\n ScMatrixValue& operator= (const ScMatrixValue& r)\n {\n nType = r.nType;\n switch (nType)\n {\n case SC_MATVAL_VALUE:\n case SC_MATVAL_BOOLEAN:\n fVal = r.fVal;\n break;\n default:\n pS = r.pS;\n }\n return *this;\n }\n};\n\n\/**\n * Matrix data type that can store values of mixed types. Each element can\n * be one of the following types: numeric, string, boolean, empty, and empty\n * path.\n *\n * This class also supports four different density types: filled zero,\n * filled empty, sparse zero, and sparse empty. The filled density type\n * allocates memory for every single element at all times, whereas the\n * sparse density types allocates memory only for non-default elements.\n *\/\nclass SC_DLLPUBLIC ScMatrix\n{\n ScMatrixImpl* pImpl;\n mutable ULONG nRefCnt; \/\/ reference count\n\n \/\/ only delete via Delete()\n ~ScMatrix();\n\n \/\/ not implemented, prevent usage\n ScMatrix( const ScMatrix& );\n ScMatrix& operator=( const ScMatrix&);\n\npublic:\n enum DensityType\n {\n FILLED_ZERO,\n FILLED_EMPTY,\n SPARSE_ZERO,\n SPARSE_EMPTY\n };\n\n \/\/\/ The maximum number of elements a matrix may have at runtime.\n inline static size_t GetElementsMax()\n {\n \/\/ Roughly 125MB in total, divided by 8+1 per element => 14M elements.\n const size_t nMemMax = 0x08000000 \/ (sizeof(ScMatrixValue) + sizeof(ScMatValType));\n \/\/ With MAXROWCOUNT==65536 and 128 columns => 8M elements ~72MB.\n const size_t nArbitraryLimit = (size_t)MAXROWCOUNT * 128;\n \/\/ Stuffed with a million rows would limit this to 14 columns.\n return nMemMax < nArbitraryLimit ? nMemMax : nArbitraryLimit;\n }\n\n \/\/\/ Value or boolean.\n inline static bool IsValueType( ScMatValType nType )\n {\n return nType <= SC_MATVAL_BOOLEAN;\n }\n\n \/\/\/ Boolean.\n inline static bool IsBooleanType( ScMatValType nType )\n {\n return nType == SC_MATVAL_BOOLEAN;\n }\n\n \/\/\/ String, empty or empty path, but not value nor boolean.\n inline static bool IsNonValueType( ScMatValType nType )\n {\n return (nType & SC_MATVAL_NONVALUE) != 0;\n }\n\n \/** String, but not empty or empty path or any other type.\n Not named IsStringType to prevent confusion because previously\n IsNonValueType was named IsStringType. *\/\n inline static bool IsRealStringType( ScMatValType nType )\n {\n return (nType & SC_MATVAL_NONVALUE) == SC_MATVAL_STRING;\n }\n\n \/\/\/ Empty, but not empty path or any other type.\n inline static bool IsEmptyType( ScMatValType nType )\n {\n return (nType & SC_MATVAL_NONVALUE) == SC_MATVAL_EMPTY;\n }\n\n \/\/\/ Empty path, but not empty or any other type.\n inline static bool IsEmptyPathType( ScMatValType nType )\n {\n return (nType & SC_MATVAL_NONVALUE) == SC_MATVAL_EMPTYPATH;\n }\n\n \/** If nC*nR results in more than GetElementsMax() entries, a 1x1 matrix is\n created instead and a double error value (errStackOverflow) is set.\n Compare nC and nR with a GetDimensions() call to check. *\/\n ScMatrix( SCSIZE nC, SCSIZE nR, DensityType eType = FILLED_ZERO);\n\n \/** Clone the matrix. *\/\n ScMatrix* Clone() const;\n ScMatrix* Clone( DensityType eType) const;\n\n \/** Clone the matrix if mbCloneIfConst (immutable) is set, otherwise\n return _this_ matrix, to be assigned to a ScMatrixRef. *\/\n ScMatrix* CloneIfConst();\n\n \/** Set the matrix to (im)mutable for CloneIfConst(), only the interpreter\n should do this and know the consequences. *\/\n void SetImmutable( bool bVal );\n\n \/**\n * Resize the matrix to specified new dimension. Note that this operation\n * clears all stored values.\n *\/\n void Resize( SCSIZE nC, SCSIZE nR);\n\n \/** Clone the matrix and extend it to the new size. nNewCols and nNewRows\n MUST be at least of the size of the original matrix. *\/\n ScMatrix* CloneAndExtend( SCSIZE nNewCols, SCSIZE nNewRows, DensityType eType) const;\n\n \/\/\/ Disable refcounting forever, may only be deleted via Delete() afterwards.\n inline void SetEternalRef() { nRefCnt = ULONG_MAX; }\n inline bool IsEternalRef() const { return nRefCnt == ULONG_MAX; }\n inline void IncRef() const\n {\n if ( !IsEternalRef() )\n ++nRefCnt;\n }\n inline void DecRef() const\n {\n if ( nRefCnt > 0 && !IsEternalRef() )\n if ( --nRefCnt == 0 )\n delete this;\n }\n inline void Delete()\n {\n if ( nRefCnt == 0 || IsEternalRef() )\n delete this;\n else\n --nRefCnt;\n }\n\n DensityType GetDensityType() const;\n void SetErrorInterpreter( ScInterpreter* p);\n void GetDimensions( SCSIZE& rC, SCSIZE& rR) const;\n SCSIZE GetElementCount() const;\n bool ValidColRow( SCSIZE nC, SCSIZE nR) const;\n SCSIZE CalcOffset( SCSIZE nC, SCSIZE nR) const;\n\n \/** For a row vector or column vector, if the position does not point into\n the vector but is a valid column or row offset it is adapted such that\n it points to an element to be replicated, same column row 0 for a row\n vector, same row column 0 for a column vector. Else, for a 2D matrix,\n returns false.\n *\/\n bool ValidColRowReplicated( SCSIZE & rC, SCSIZE & rR ) const;\n\n \/** Checks if the matrix position is within the matrix. If it is not, for a\n row vector or column vector the position is adapted such that it points\n to an element to be replicated, same column row 0 for a row vector,\n same row column 0 for a column vector. Else, for a 2D matrix and\n position not within matrix, returns false.\n *\/\n bool ValidColRowOrReplicated( SCSIZE & rC, SCSIZE & rR ) const;\n\n void PutDouble( double fVal, SCSIZE nC, SCSIZE nR);\n void PutDouble( double fVal, SCSIZE nIndex);\n void PutString( const String& rStr, SCSIZE nC, SCSIZE nR);\n void PutString( const String& rStr, SCSIZE nIndex);\n void PutEmpty( SCSIZE nC, SCSIZE nR);\n \/\/\/ Jump FALSE without path\n void PutEmptyPath( SCSIZE nC, SCSIZE nR);\n void PutError( USHORT nErrorCode, SCSIZE nC, SCSIZE nR );\n void PutBoolean( bool bVal, SCSIZE nC, SCSIZE nR);\n\n void FillDouble( double fVal,\n SCSIZE nC1, SCSIZE nR1, SCSIZE nC2, SCSIZE nR2 );\n\n \/** May be used before obtaining the double value of an element to avoid\n passing its NAN around.\n @ATTENTION: MUST NOT be used if the element is a string!\n Use GetErrorIfNotString() instead if not sure.\n @returns 0 if no error, else one of err... constants *\/\n USHORT GetError( SCSIZE nC, SCSIZE nR) const;\n\n \/** Use in ScInterpreter to obtain the error code, if any.\n @returns 0 if no error or string element, else one of err... constants *\/\n USHORT GetErrorIfNotString( SCSIZE nC, SCSIZE nR) const\n { return IsValue( nC, nR) ? GetError( nC, nR) : 0; }\n\n \/\/\/ @return 0.0 if empty or empty path, else value or DoubleError.\n double GetDouble( SCSIZE nC, SCSIZE nR) const;\n \/\/\/ @return 0.0 if empty or empty path, else value or DoubleError.\n double GetDouble( SCSIZE nIndex) const;\n\n \/\/\/ @return empty string if empty or empty path, else string content.\n const String& GetString( SCSIZE nC, SCSIZE nR) const;\n \/\/\/ @return empty string if empty or empty path, else string content.\n const String& GetString( SCSIZE nIndex) const;\n\n \/** @returns the matrix element's string if one is present, otherwise the\n numerical value formatted as string, or in case of an error the error\n string is returned; an empty string for empty, a \"FALSE\" string for\n empty path. *\/\n String GetString( SvNumberFormatter& rFormatter, SCSIZE nC, SCSIZE nR) const;\n\n \/\/\/ @ATTENTION: If bString the ScMatrixValue->pS may still be NULL to indicate\n \/\/\/ an empty string!\n ScMatrixValue Get( SCSIZE nC, SCSIZE nR) const;\n\n \/\/\/ @return if string or empty or empty path, in fact non-value.\n BOOL IsString( SCSIZE nIndex ) const;\n\n \/\/\/ @return if string or empty or empty path, in fact non-value.\n BOOL IsString( SCSIZE nC, SCSIZE nR ) const;\n\n \/\/\/ @return if empty or empty path.\n BOOL IsEmpty( SCSIZE nC, SCSIZE nR ) const;\n\n \/\/\/ @return if empty path.\n BOOL IsEmptyPath( SCSIZE nC, SCSIZE nR ) const;\n\n \/\/\/ @return if value or boolean.\n BOOL IsValue( SCSIZE nIndex ) const;\n\n \/\/\/ @return if value or boolean.\n BOOL IsValue( SCSIZE nC, SCSIZE nR ) const;\n\n \/\/\/ @return if value or boolean or empty or empty path.\n BOOL IsValueOrEmpty( SCSIZE nC, SCSIZE nR ) const;\n\n \/\/\/ @return if boolean.\n BOOL IsBoolean( SCSIZE nC, SCSIZE nR ) const;\n\n \/\/\/ @return if entire matrix is numeric, including booleans, with no strings or empties\n BOOL IsNumeric() const;\n\n void MatTrans( ScMatrix& mRes) const;\n void MatCopy ( ScMatrix& mRes) const;\n\n \/\/ Convert ScInterpreter::CompareMat values (-1,0,1) to boolean values\n void CompareEqual();\n void CompareNotEqual();\n void CompareLess();\n void CompareGreater();\n void CompareLessEqual();\n void CompareGreaterEqual();\n\n double And(); \/\/ logical AND of all matrix values, or NAN\n double Or(); \/\/ logical OR of all matrix values, or NAN\n\n \/\/ All other matrix functions MatMult, MInv, ... are in ScInterpreter\n \/\/ to be numerically safe.\n};\n\n\ntypedef formula::SimpleIntrusiveReference< class ScMatrix > ScMatrixRef;\ntypedef formula::SimpleIntrusiveReference< const class ScMatrix > ScConstMatrixRef;\n\n\n#endif \/\/ SC_MATRIX_HXX\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"WebMediaPlayerClientImpl.h\"\n\n#if ENABLE(VIDEO)\n\n#include \"TemporaryGlue.h\"\n#include \"WebCanvas.h\"\n#include \"WebCString.h\"\n#include \"WebKit.h\"\n#include \"WebKitClient.h\"\n#include \"WebMediaPlayer.h\"\n#include \"WebMimeRegistry.h\"\n#include \"WebRect.h\"\n#include \"WebSize.h\"\n#include \"WebString.h\"\n#include \"WebURL.h\"\n\n#include \"CString.h\"\n#include \"Frame.h\"\n#include \"GraphicsContext.h\"\n#include \"HTMLMediaElement.h\"\n#include \"IntSize.h\"\n#include \"KURL.h\"\n#include \"MediaPlayer.h\"\n#include \"NotImplemented.h\"\n#include \n\n#if WEBKIT_USING_SKIA\n#include \"PlatformContextSkia.h\"\n#endif\n\nusing namespace WebCore;\n\nnamespace WebKit {\n\nstatic bool s_isEnabled = false;\n\nvoid WebMediaPlayerClientImpl::setIsEnabled(bool isEnabled)\n{\n s_isEnabled = isEnabled;\n}\n\nvoid WebMediaPlayerClientImpl::registerSelf(MediaEngineRegistrar registrar)\n{\n if (s_isEnabled) {\n registrar(WebMediaPlayerClientImpl::create,\n WebMediaPlayerClientImpl::getSupportedTypes,\n WebMediaPlayerClientImpl::supportsType);\n }\n}\n\n\n\/\/ WebMediaPlayerClient --------------------------------------------------------\n\nvoid WebMediaPlayerClientImpl::networkStateChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->networkStateChanged();\n}\n\nvoid WebMediaPlayerClientImpl::readyStateChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->readyStateChanged();\n}\n\nvoid WebMediaPlayerClientImpl::volumeChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->volumeChanged();\n}\n\nvoid WebMediaPlayerClientImpl::timeChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->timeChanged();\n}\n\nvoid WebMediaPlayerClientImpl::repaint()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->repaint();\n}\n\nvoid WebMediaPlayerClientImpl::durationChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->durationChanged();\n}\n\nvoid WebMediaPlayerClientImpl::rateChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->rateChanged();\n}\n\nvoid WebMediaPlayerClientImpl::sizeChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->sizeChanged();\n}\n\nvoid WebMediaPlayerClientImpl::sawUnsupportedTracks()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->mediaPlayerClient()->mediaPlayerSawUnsupportedTracks(m_mediaPlayer);\n}\n\n\/\/ MediaPlayerPrivateInterface -------------------------------------------------\n\nvoid WebMediaPlayerClientImpl::load(const String& url)\n{\n Frame* frame = static_cast(\n m_mediaPlayer->mediaPlayerClient())->document()->frame();\n m_webMediaPlayer.set(TemporaryGlue::createWebMediaPlayer(this, frame));\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->load(KURL(ParsedURLString, url));\n}\n\nvoid WebMediaPlayerClientImpl::cancelLoad()\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->cancelLoad();\n}\n\nvoid WebMediaPlayerClientImpl::play()\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->play();\n}\n\nvoid WebMediaPlayerClientImpl::pause()\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->pause();\n}\n\nIntSize WebMediaPlayerClientImpl::naturalSize() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->naturalSize();\n return IntSize();\n}\n\nbool WebMediaPlayerClientImpl::hasVideo() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->hasVideo();\n return false;\n}\n\nbool WebMediaPlayerClientImpl::hasAudio() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->hasAudio();\n return false;\n}\n\nvoid WebMediaPlayerClientImpl::setVisible(bool visible)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setVisible(visible);\n}\n\nfloat WebMediaPlayerClientImpl::duration() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->duration();\n return 0.0f;\n}\n\nfloat WebMediaPlayerClientImpl::currentTime() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->currentTime();\n return 0.0f;\n}\n\nvoid WebMediaPlayerClientImpl::seek(float time)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->seek(time);\n}\n\nbool WebMediaPlayerClientImpl::seeking() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->seeking();\n return false;\n}\n\nvoid WebMediaPlayerClientImpl::setEndTime(float time)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setEndTime(time);\n}\n\nvoid WebMediaPlayerClientImpl::setRate(float rate)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setRate(rate);\n}\n\nbool WebMediaPlayerClientImpl::paused() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->paused();\n return false;\n}\n\nbool WebMediaPlayerClientImpl::supportsFullscreen() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->supportsFullscreen();\n return false;\n}\n\nbool WebMediaPlayerClientImpl::supportsSave() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->supportsSave();\n return false;\n}\n\nvoid WebMediaPlayerClientImpl::setVolume(float volume)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setVolume(volume);\n}\n\nMediaPlayer::NetworkState WebMediaPlayerClientImpl::networkState() const\n{\n COMPILE_ASSERT(\n int(WebMediaPlayer::Empty) == int(MediaPlayer::Empty), Empty);\n COMPILE_ASSERT(\n int(WebMediaPlayer::Idle) == int(MediaPlayer::Idle), Idle);\n COMPILE_ASSERT(\n int(WebMediaPlayer::Loading) == int(MediaPlayer::Loading), Loading);\n COMPILE_ASSERT(\n int(WebMediaPlayer::Loaded) == int(MediaPlayer::Loaded), Loaded);\n COMPILE_ASSERT(\n int(WebMediaPlayer::FormatError) == int(MediaPlayer::FormatError),\n FormatError);\n COMPILE_ASSERT(\n int(WebMediaPlayer::NetworkError) == int(MediaPlayer::NetworkError),\n NetworkError);\n COMPILE_ASSERT(\n int(WebMediaPlayer::DecodeError) == int(MediaPlayer::DecodeError),\n DecodeError);\n\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->networkState());\n return MediaPlayer::Empty;\n}\n\nMediaPlayer::ReadyState WebMediaPlayerClientImpl::readyState() const\n{\n COMPILE_ASSERT(\n int(WebMediaPlayer::HaveNothing) == int(MediaPlayer::HaveNothing),\n HaveNothing);\n COMPILE_ASSERT(\n int(WebMediaPlayer::HaveMetadata) == int(MediaPlayer::HaveMetadata),\n HaveMetadata);\n COMPILE_ASSERT(\n int(WebMediaPlayer::HaveCurrentData) == int(MediaPlayer::HaveCurrentData),\n HaveCurrentData);\n COMPILE_ASSERT(\n int(WebMediaPlayer::HaveFutureData) == int(MediaPlayer::HaveFutureData),\n HaveFutureData);\n COMPILE_ASSERT(\n int(WebMediaPlayer::HaveEnoughData) == int(MediaPlayer::HaveEnoughData),\n HaveEnoughData);\n\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->readyState());\n return MediaPlayer::HaveNothing;\n}\n\nfloat WebMediaPlayerClientImpl::maxTimeSeekable() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->maxTimeSeekable();\n return 0.0f;\n}\n\nfloat WebMediaPlayerClientImpl::maxTimeBuffered() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->maxTimeBuffered();\n return 0.0f;\n}\n\nint WebMediaPlayerClientImpl::dataRate() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->dataRate();\n return 0;\n}\n\nbool WebMediaPlayerClientImpl::totalBytesKnown() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->totalBytesKnown();\n return false;\n}\n\nunsigned WebMediaPlayerClientImpl::totalBytes() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->totalBytes());\n return 0;\n}\n\nunsigned WebMediaPlayerClientImpl::bytesLoaded() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->bytesLoaded());\n return 0;\n}\n\nvoid WebMediaPlayerClientImpl::setSize(const IntSize& size)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setSize(WebSize(size.width(), size.height()));\n}\n\nvoid WebMediaPlayerClientImpl::paint(GraphicsContext* context, const IntRect& rect)\n{\n if (m_webMediaPlayer.get()) {\n#if WEBKIT_USING_SKIA\n m_webMediaPlayer->paint(context->platformContext()->canvas(), rect);\n#elif WEBKIT_USING_CG\n m_webMediaPlayer->paint(context->platformContext(), rect);\n#else\n notImplemented();\n#endif\n }\n}\n\nvoid WebMediaPlayerClientImpl::setAutobuffer(bool autoBuffer)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setAutoBuffer(autoBuffer);\n}\n\nbool WebMediaPlayerClientImpl::hasSingleSecurityOrigin() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->hasSingleSecurityOrigin();\n return false;\n}\n\nMediaPlayer::MovieLoadType WebMediaPlayerClientImpl::movieLoadType() const\n{\n COMPILE_ASSERT(\n int(WebMediaPlayer::Unknown) == int(MediaPlayer::Unknown),\n Unknown);\n COMPILE_ASSERT(\n int(WebMediaPlayer::Download) == int(MediaPlayer::Download),\n Download);\n COMPILE_ASSERT(\n int(WebMediaPlayer::StoredStream) == int(MediaPlayer::StoredStream),\n StoredStream);\n COMPILE_ASSERT(\n int(WebMediaPlayer::LiveStream) == int(MediaPlayer::LiveStream),\n LiveStream);\n\n if (m_webMediaPlayer.get())\n return static_cast(\n m_webMediaPlayer->movieLoadType());\n return MediaPlayer::Unknown;\n}\n\nMediaPlayerPrivateInterface* WebMediaPlayerClientImpl::create(MediaPlayer* player)\n{\n WebMediaPlayerClientImpl* client = new WebMediaPlayerClientImpl();\n client->m_mediaPlayer = player;\n return client;\n}\n\nvoid WebMediaPlayerClientImpl::getSupportedTypes(HashSet& supportedTypes)\n{\n \/\/ FIXME: integrate this list with WebMediaPlayerClientImpl::supportsType.\n notImplemented();\n}\n\nMediaPlayer::SupportsType WebMediaPlayerClientImpl::supportsType(const String& type,\n const String& codecs)\n{\n WebMimeRegistry::SupportsType supportsType =\n webKitClient()->mimeRegistry()->supportsMediaMIMEType(type, codecs);\n\n switch (supportsType) {\n default:\n ASSERT_NOT_REACHED();\n case WebMimeRegistry::IsNotSupported:\n return MediaPlayer::IsNotSupported;\n case WebMimeRegistry::IsSupported:\n return MediaPlayer::IsSupported;\n case WebMimeRegistry::MayBeSupported:\n return MediaPlayer::MayBeSupported;\n }\n}\n\nWebMediaPlayerClientImpl::WebMediaPlayerClientImpl()\n : m_mediaPlayer(0)\n{\n}\n\n} \/\/ namespace WebKit\n\n#endif \/\/ ENABLE(VIDEO)\nFixes crash when switching to new tabs containing audio\/video elements.\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"WebMediaPlayerClientImpl.h\"\n\n#if ENABLE(VIDEO)\n\n#include \"TemporaryGlue.h\"\n#include \"WebCanvas.h\"\n#include \"WebCString.h\"\n#include \"WebKit.h\"\n#include \"WebKitClient.h\"\n#include \"WebMediaPlayer.h\"\n#include \"WebMimeRegistry.h\"\n#include \"WebRect.h\"\n#include \"WebSize.h\"\n#include \"WebString.h\"\n#include \"WebURL.h\"\n\n#include \"CString.h\"\n#include \"Frame.h\"\n#include \"GraphicsContext.h\"\n#include \"HTMLMediaElement.h\"\n#include \"IntSize.h\"\n#include \"KURL.h\"\n#include \"MediaPlayer.h\"\n#include \"NotImplemented.h\"\n#include \n\n#if WEBKIT_USING_SKIA\n#include \"PlatformContextSkia.h\"\n#endif\n\nusing namespace WebCore;\n\nnamespace WebKit {\n\nstatic bool s_isEnabled = false;\n\nvoid WebMediaPlayerClientImpl::setIsEnabled(bool isEnabled)\n{\n s_isEnabled = isEnabled;\n}\n\nvoid WebMediaPlayerClientImpl::registerSelf(MediaEngineRegistrar registrar)\n{\n if (s_isEnabled) {\n registrar(WebMediaPlayerClientImpl::create,\n WebMediaPlayerClientImpl::getSupportedTypes,\n WebMediaPlayerClientImpl::supportsType);\n }\n}\n\n\n\/\/ WebMediaPlayerClient --------------------------------------------------------\n\nvoid WebMediaPlayerClientImpl::networkStateChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->networkStateChanged();\n}\n\nvoid WebMediaPlayerClientImpl::readyStateChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->readyStateChanged();\n}\n\nvoid WebMediaPlayerClientImpl::volumeChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->volumeChanged();\n}\n\nvoid WebMediaPlayerClientImpl::timeChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->timeChanged();\n}\n\nvoid WebMediaPlayerClientImpl::repaint()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->repaint();\n}\n\nvoid WebMediaPlayerClientImpl::durationChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->durationChanged();\n}\n\nvoid WebMediaPlayerClientImpl::rateChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->rateChanged();\n}\n\nvoid WebMediaPlayerClientImpl::sizeChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->sizeChanged();\n}\n\nvoid WebMediaPlayerClientImpl::sawUnsupportedTracks()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->mediaPlayerClient()->mediaPlayerSawUnsupportedTracks(m_mediaPlayer);\n}\n\n\/\/ MediaPlayerPrivateInterface -------------------------------------------------\n\nvoid WebMediaPlayerClientImpl::load(const String& url)\n{\n Frame* frame = static_cast(\n m_mediaPlayer->mediaPlayerClient())->document()->frame();\n m_webMediaPlayer.set(TemporaryGlue::createWebMediaPlayer(this, frame));\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->load(KURL(ParsedURLString, url));\n}\n\nvoid WebMediaPlayerClientImpl::cancelLoad()\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->cancelLoad();\n}\n\nvoid WebMediaPlayerClientImpl::play()\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->play();\n}\n\nvoid WebMediaPlayerClientImpl::pause()\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->pause();\n}\n\nIntSize WebMediaPlayerClientImpl::naturalSize() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->naturalSize();\n return IntSize();\n}\n\nbool WebMediaPlayerClientImpl::hasVideo() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->hasVideo();\n return false;\n}\n\nbool WebMediaPlayerClientImpl::hasAudio() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->hasAudio();\n return false;\n}\n\nvoid WebMediaPlayerClientImpl::setVisible(bool visible)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setVisible(visible);\n}\n\nfloat WebMediaPlayerClientImpl::duration() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->duration();\n return 0.0f;\n}\n\nfloat WebMediaPlayerClientImpl::currentTime() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->currentTime();\n return 0.0f;\n}\n\nvoid WebMediaPlayerClientImpl::seek(float time)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->seek(time);\n}\n\nbool WebMediaPlayerClientImpl::seeking() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->seeking();\n return false;\n}\n\nvoid WebMediaPlayerClientImpl::setEndTime(float time)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setEndTime(time);\n}\n\nvoid WebMediaPlayerClientImpl::setRate(float rate)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setRate(rate);\n}\n\nbool WebMediaPlayerClientImpl::paused() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->paused();\n return false;\n}\n\nbool WebMediaPlayerClientImpl::supportsFullscreen() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->supportsFullscreen();\n return false;\n}\n\nbool WebMediaPlayerClientImpl::supportsSave() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->supportsSave();\n return false;\n}\n\nvoid WebMediaPlayerClientImpl::setVolume(float volume)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setVolume(volume);\n}\n\nMediaPlayer::NetworkState WebMediaPlayerClientImpl::networkState() const\n{\n COMPILE_ASSERT(\n int(WebMediaPlayer::Empty) == int(MediaPlayer::Empty), Empty);\n COMPILE_ASSERT(\n int(WebMediaPlayer::Idle) == int(MediaPlayer::Idle), Idle);\n COMPILE_ASSERT(\n int(WebMediaPlayer::Loading) == int(MediaPlayer::Loading), Loading);\n COMPILE_ASSERT(\n int(WebMediaPlayer::Loaded) == int(MediaPlayer::Loaded), Loaded);\n COMPILE_ASSERT(\n int(WebMediaPlayer::FormatError) == int(MediaPlayer::FormatError),\n FormatError);\n COMPILE_ASSERT(\n int(WebMediaPlayer::NetworkError) == int(MediaPlayer::NetworkError),\n NetworkError);\n COMPILE_ASSERT(\n int(WebMediaPlayer::DecodeError) == int(MediaPlayer::DecodeError),\n DecodeError);\n\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->networkState());\n return MediaPlayer::Empty;\n}\n\nMediaPlayer::ReadyState WebMediaPlayerClientImpl::readyState() const\n{\n COMPILE_ASSERT(\n int(WebMediaPlayer::HaveNothing) == int(MediaPlayer::HaveNothing),\n HaveNothing);\n COMPILE_ASSERT(\n int(WebMediaPlayer::HaveMetadata) == int(MediaPlayer::HaveMetadata),\n HaveMetadata);\n COMPILE_ASSERT(\n int(WebMediaPlayer::HaveCurrentData) == int(MediaPlayer::HaveCurrentData),\n HaveCurrentData);\n COMPILE_ASSERT(\n int(WebMediaPlayer::HaveFutureData) == int(MediaPlayer::HaveFutureData),\n HaveFutureData);\n COMPILE_ASSERT(\n int(WebMediaPlayer::HaveEnoughData) == int(MediaPlayer::HaveEnoughData),\n HaveEnoughData);\n\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->readyState());\n return MediaPlayer::HaveNothing;\n}\n\nfloat WebMediaPlayerClientImpl::maxTimeSeekable() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->maxTimeSeekable();\n return 0.0f;\n}\n\nfloat WebMediaPlayerClientImpl::maxTimeBuffered() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->maxTimeBuffered();\n return 0.0f;\n}\n\nint WebMediaPlayerClientImpl::dataRate() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->dataRate();\n return 0;\n}\n\nbool WebMediaPlayerClientImpl::totalBytesKnown() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->totalBytesKnown();\n return false;\n}\n\nunsigned WebMediaPlayerClientImpl::totalBytes() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->totalBytes());\n return 0;\n}\n\nunsigned WebMediaPlayerClientImpl::bytesLoaded() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->bytesLoaded());\n return 0;\n}\n\nvoid WebMediaPlayerClientImpl::setSize(const IntSize& size)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setSize(WebSize(size.width(), size.height()));\n}\n\nvoid WebMediaPlayerClientImpl::paint(GraphicsContext* context, const IntRect& rect)\n{\n \/\/ Normally GraphicsContext operations do nothing when painting is disabled.\n \/\/ Since we're accessing platformContext() directly we have to manually\n \/\/ check.\n if (m_webMediaPlayer.get() && !context->paintingDisabled()) {\n#if WEBKIT_USING_SKIA\n m_webMediaPlayer->paint(context->platformContext()->canvas(), rect);\n#elif WEBKIT_USING_CG\n m_webMediaPlayer->paint(context->platformContext(), rect);\n#else\n notImplemented();\n#endif\n }\n}\n\nvoid WebMediaPlayerClientImpl::setAutobuffer(bool autoBuffer)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setAutoBuffer(autoBuffer);\n}\n\nbool WebMediaPlayerClientImpl::hasSingleSecurityOrigin() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->hasSingleSecurityOrigin();\n return false;\n}\n\nMediaPlayer::MovieLoadType WebMediaPlayerClientImpl::movieLoadType() const\n{\n COMPILE_ASSERT(\n int(WebMediaPlayer::Unknown) == int(MediaPlayer::Unknown),\n Unknown);\n COMPILE_ASSERT(\n int(WebMediaPlayer::Download) == int(MediaPlayer::Download),\n Download);\n COMPILE_ASSERT(\n int(WebMediaPlayer::StoredStream) == int(MediaPlayer::StoredStream),\n StoredStream);\n COMPILE_ASSERT(\n int(WebMediaPlayer::LiveStream) == int(MediaPlayer::LiveStream),\n LiveStream);\n\n if (m_webMediaPlayer.get())\n return static_cast(\n m_webMediaPlayer->movieLoadType());\n return MediaPlayer::Unknown;\n}\n\nMediaPlayerPrivateInterface* WebMediaPlayerClientImpl::create(MediaPlayer* player)\n{\n WebMediaPlayerClientImpl* client = new WebMediaPlayerClientImpl();\n client->m_mediaPlayer = player;\n return client;\n}\n\nvoid WebMediaPlayerClientImpl::getSupportedTypes(HashSet& supportedTypes)\n{\n \/\/ FIXME: integrate this list with WebMediaPlayerClientImpl::supportsType.\n notImplemented();\n}\n\nMediaPlayer::SupportsType WebMediaPlayerClientImpl::supportsType(const String& type,\n const String& codecs)\n{\n WebMimeRegistry::SupportsType supportsType =\n webKitClient()->mimeRegistry()->supportsMediaMIMEType(type, codecs);\n\n switch (supportsType) {\n default:\n ASSERT_NOT_REACHED();\n case WebMimeRegistry::IsNotSupported:\n return MediaPlayer::IsNotSupported;\n case WebMimeRegistry::IsSupported:\n return MediaPlayer::IsSupported;\n case WebMimeRegistry::MayBeSupported:\n return MediaPlayer::MayBeSupported;\n }\n}\n\nWebMediaPlayerClientImpl::WebMediaPlayerClientImpl()\n : m_mediaPlayer(0)\n{\n}\n\n} \/\/ namespace WebKit\n\n#endif \/\/ ENABLE(VIDEO)\n<|endoftext|>"} {"text":"package = $config['package'];\n $this->exampleReporter = $config['exampleReporter'];\n }\n\n public function getPackage() : PackageSpecification\n {\n return $this->package;\n }\n\n public function getExampleReporter() : ExampleReporter\n {\n return $this->exampleReporter;\n }\n\n}\nfix typehintingpackage = $config['package'];\n $this->exampleReporter = $config['exampleReporter'];\n }\n\n public function getPackage() : PackageSpecification\n {\n return $this->package;\n }\n\n public function getExampleReporter() : ExampleReporter\n {\n return $this->exampleReporter;\n }\n\n}\n<|endoftext|>"} {"text":"#ifndef ENTITY_HPP\n#define ENTITY_HPP\n\n#include \"..\/MessageSystem\/Observable.hpp\"\n\n#include \n\n#include \"Component.hpp\"\n#include \"ComponentRegistry.hpp\"\n\nnamespace swift\n{\n\tclass Entity : public Observable\n\t{\n\t\tpublic:\n\t\t\tEntity()\n\t\t\t{\n\n\t\t\t}\n\n\t\t\tvirtual ~Entity()\n\t\t\t{\n\t\t\t\tfor(auto& c : components)\n\t\t\t\t\tdelete c.second;\n\t\t\t}\n\t\t\t\n\t\t\ttemplate\n\t\t\tbool add()\n\t\t\t{\n\t\t\t\tstatic_assert(std::is_base_of::value, \"C must be a child of swift::Component\");\n\t\t\t\t\n\t\t\t\tif(!has())\n\t\t\t\t{\n\t\t\t\t\tcomponents.emplace(C::getType(), new C);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tbool add(std::string c)\n\t\t\t{\n\t\t\t\tComponent* comp = ComponentRegistry::get(c);\n\t\t\t\t\n\t\t\t\tif(comp == nullptr || components.find(c) != components.end())\n\t\t\t\t\treturn false;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcomponents.emplace(c, comp);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\ttemplate\n\t\t\tbool remove()\n\t\t\t{\n\t\t\t\tstatic_assert(std::is_base_of::value, \"C must be a child of swift::Component\");\n\t\t\t\t\n\t\t\t\tif(has())\n\t\t\t\t{\n\t\t\t\t\tdelete components[C::getType()];\n\t\t\t\t\tcomponents.erase(C::getType());\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tbool remove(std::string c)\n\t\t\t{\n\t\t\t\tComponent* comp = ComponentRegistry::get(c);\n\t\t\t\t\n\t\t\t\tif(comp == nullptr || components.find(c) != components.end())\n\t\t\t\t\treturn false;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcomponents.emplace(c, comp);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\ttemplate\n\t\t\tC* get()\n\t\t\t{\n\t\t\t\tstatic_assert(std::is_base_of::value, \"C must be a child of swift::Component\");\n\t\t\t\t\n\t\t\t\tif(has())\n\t\t\t\t{\n\t\t\t\t\treturn static_cast(components[C::getType()]);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ overridden by a Component for it's own type\n\t\t\ttemplate\n\t\t\tC* get(std::string c)\n\t\t\t{\n\t\t\t\tif(has(c))\n\t\t\t\t{\n\t\t\t\t\treturn static_cast(components[c]);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t\t\n\t\t\ttemplate\n\t\t\tbool has() const\n\t\t\t{\n\t\t\t\tstatic_assert(std::is_base_of::value, \"C must be a child of swift::Component\");\n\t\t\t\t\n\t\t\t\treturn components.find(C::getType()) != components.end();\n\t\t\t}\n\t\t\t\n\t\t\tbool has(std::string c) const\n\t\t\t{\n\t\t\t\treturn components.find(c) != components.end();\n\t\t\t}\n\n\t\tprivate:\n\t\t\tstd::unordered_map components;\n\t};\n}\n\n\/\/ Entities can be designed via a simple text file with the following format:\n\/\/\tEntity\n\/\/\t\tComponent1\n\/\/\t\t\ttype Data\n\/\/\t\tComponent2\n\/\/\t\t\ttype Data1\n\/\/\t\t\ttype Data2\n\/\/ types =\n\/\/ \ts = string\n\/\/ \tr = rect\n\/\/\tf = float\n\/\/\ti = int\n\n\/* Example Entity file\n * Entity\n * \tDrawable\n * \t\ts .\/data\/textures\/guy.png\t# texture\n * \t\tr 0 0 0 0\t# texture rect, if all 0s, use size of texture\n * \tMovable\n * \t\tf 100\t# move velocity\n * \tPhysical\n * \t\ti 400\t# x position\n * \t\ti 300\t# y position\n *\/\n\n#endif \/\/ ENTITY_HPP\nCommented out get(std::string) as it is not actually needed.#ifndef ENTITY_HPP\n#define ENTITY_HPP\n\n#include \n\n#include \"Component.hpp\"\n#include \"ComponentRegistry.hpp\"\n\nnamespace swift\n{\n\tclass Entity\n\t{\n\t\tpublic:\n\t\t\tEntity()\n\t\t\t{\n\n\t\t\t}\n\n\t\t\t~Entity()\n\t\t\t{\n\t\t\t\tauto it = components.begin();\n\t\t\t\twhile(it != components.end())\n\t\t\t\t{\n\t\t\t\t\tif(it->second)\n\t\t\t\t\t\tdelete it->second;\n\t\t\t\t\tit = components.erase(it);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\ttemplate\n\t\t\tbool add()\n\t\t\t{\n\t\t\t\tstatic_assert(std::is_base_of::value, \"C must be a child of swift::Component\");\n\t\t\t\t\n\t\t\t\tif(!has())\n\t\t\t\t{\n\t\t\t\t\tcomponents.emplace(C::getType(), new C);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tbool add(std::string c)\n\t\t\t{\n\t\t\t\tif(components.find(c) != components.end())\n\t\t\t\t\treturn false;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tComponent* comp = ComponentRegistry::get(c);\n\t\t\t\t\n\t\t\t\t\tif(comp == nullptr)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t\n\t\t\t\t\tcomponents.emplace(c, comp);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\ttemplate\n\t\t\tbool remove()\n\t\t\t{\n\t\t\t\tstatic_assert(std::is_base_of::value, \"C must be a child of swift::Component\");\n\t\t\t\t\n\t\t\t\tif(has())\n\t\t\t\t{\n\t\t\t\t\tdelete components[C::getType()];\n\t\t\t\t\tcomponents.erase(C::getType());\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tbool remove(std::string c)\n\t\t\t{\n\t\t\t\tif(components.find(c) == components.end())\n\t\t\t\t\treturn false;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tComponent* comp = ComponentRegistry::get(c);\n\t\t\t\t\t\n\t\t\t\t\tif(comp == nullptr)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\n\t\t\t\t\tcomponents.emplace(c, comp);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\ttemplate\n\t\t\tC* get()\n\t\t\t{\n\t\t\t\tstatic_assert(std::is_base_of::value, \"C must be a child of swift::Component\");\n\t\t\t\t\n\t\t\t\tif(has())\n\t\t\t\t{\n\t\t\t\t\treturn static_cast(components[C::getType()]);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ Must be overridden by a Component for it's own type\n\t\t\t\/*template\n\t\t\tC* get(std::string c)\n\t\t\t{\n\t\t\t\tif(has(c))\n\t\t\t\t{\n\t\t\t\t\treturn static_cast(components[c]);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn nullptr;\n\t\t\t}*\/\n\t\t\t\/\/ not needed for binding\n\t\t\t\n\t\t\ttemplate\n\t\t\tbool has() const\n\t\t\t{\n\t\t\t\tstatic_assert(std::is_base_of::value, \"C must be a child of swift::Component\");\n\t\t\t\t\n\t\t\t\treturn components.find(C::getType()) != components.end();\n\t\t\t}\n\t\t\t\n\t\t\tbool has(std::string c) const\n\t\t\t{\n\t\t\t\treturn components.find(c) != components.end();\n\t\t\t}\n\n\t\tprivate:\n\t\t\tstd::unordered_map components;\n\t};\n}\n\n\/\/ Entities can be designed via a simple text file with the following format:\n\/\/\tEntity\n\/\/\t\tComponent1\n\/\/\t\t\ttype Data\n\/\/\t\tComponent2\n\/\/\t\t\ttype Data1\n\/\/\t\t\ttype Data2\n\/\/ types =\n\/\/ \ts = string\n\/\/ \tr = rect\n\/\/\tf = float\n\/\/\ti = int\n\n\/* Example Entity file\n * Entity\n * \tDrawable\n * \t\ts .\/data\/textures\/guy.png\t# texture\n * \t\tr 0 0 0 0\t# texture rect, if all 0s, use size of texture\n * \tMovable\n * \t\tf 100\t# move velocity\n * \tPhysical\n * \t\ti 400\t# x position\n * \t\ti 300\t# y position\n *\/\n\n#endif \/\/ ENTITY_HPP\n<|endoftext|>"} {"text":"#include \"SteamAudioIndirectRenderer.hpp\"\n\nSteamAudioIndirectRenderer::SteamAudioIndirectRenderer()\n{\n}\n\nSteamAudioIndirectRenderer::SteamAudioIndirectRenderer(IPLContext context, IPLhandle * environment)\n{\n}\n\nSteamAudioIndirectRenderer::~SteamAudioIndirectRenderer()\n{\n}\nPR fix#include \"SteamAudioIndirectRenderer.hpp\"\n\nSteamAudioIndirectRenderer::SteamAudioIndirectRenderer() {\n\n}\n\nSteamAudioIndirectRenderer::SteamAudioIndirectRenderer(IPLContext context, IPLhandle * environment) {\n\n}\n\nSteamAudioIndirectRenderer::~SteamAudioIndirectRenderer() {\n\n}\n<|endoftext|>"} {"text":"\/*\n * vtk2json\n *\n * The program is a PLY\/VTK file format to JSON file format converter for use\n * with three.js. The program uses the C++ libraries from the VTK toolkit\n * in order to read in a model file and convert it into the json file format\n * which can be recongnized by three.js for rendering in browser WebGL.\n *\n * Migara Liyanamage <>\n * Frank Zhao \n * June 2014\n *\n *\/\n\n\n\/\/ Import for VTK Libraries\n#include \n#include \n#include \n#include \n#include \n\n\/\/ Import for standard C++ libraries\n#include \n#include \n\n\/\/ Import program header\n#include \"vtk2json.h\"\n\nusing namespace std;\n\n\/*\n * Generate JSON Method\n *\n * This method calls the appropriate methods in the vtk toolkit and outputs the\n * JSON file to the output file name specified\n *\n *\/\nvoid vtk2json(bool preserveTopology, bool splitting, bool boundaryVertexDeletion, \n bool verbose, float decAmount, std::string inputFilename, std::string outputFilename) {\n \/\/ File stream for output file\n std::ofstream outputFile;\n outputFile.open(outputFilename.c_str());\n\n \/\/ begin the json file\n outputFile << \"{\\n\";\n\n \/\/ Reader to read in model\n vtkSmartPointer reader =\n vtkSmartPointer::New();\n\n \/\/ Specify filename\n reader->SetFileName ( inputFilename.c_str() );\n\n \/\/ Call vtk pipeline to read in the file\n reader->Update();\n\n \/\/ Variables for storing polygons and points\n vtkDataSet * data;\n vtkIdType vert;\n vtkPolyData * pdata;\n vtkCellArray * faces;\n vtkSmartPointer decimated;\n\n if (decAmount == 0.0) {\n \/\/ Get the output for vertices\n data = reader->GetPolyDataOutput();\n vert = data->GetNumberOfPoints();\n\n \/\/ Get the output for polygons\n pdata = reader->GetPolyDataOutput();\n faces = pdata->GetPolys();\n } else if (decAmount < 0.0) {\n cout << \"Invalid Decimate Amount, Program will now exit\" << endl;\n exit(EXIT_FAILURE);\n } else {\n \/\/ create decimator\n vtkSmartPointer decimate = vtkSmartPointer::New();\n\n \/\/ set decimator to the selected file\n decimate->SetInputData(reader->GetOutput());\n\n \/\/ set target to reduce to, and set topology to be preserved\n if (preserveTopology) {decimate->PreserveTopologyOn();} \n else {decimate->PreserveTopologyOff();}\n \n \/\/ splitting\n if (splitting) {decimate->SplittingOn();}\n else {decimate->SplittingOff();}\n \n \/\/ Boundary vertex deletion\n if (boundaryVertexDeletion) {decimate->BoundaryVertexDeletionOn();}\n else {decimate->BoundaryVertexDeletionOff();}\n \n decimate->SetTargetReduction(decAmount);\n\n \/\/ start decimation\n decimate->Update();\n\n decimated =\n vtkSmartPointer::New();\n decimated->ShallowCopy(decimate->GetOutput());\n\n \/\/ Get the outpuyt for vertices\n data = decimated;\n vert = decimated->GetNumberOfPoints();\n\n \/\/ Get the output for polygons\n faces = decimated->GetPolys();\n }\n\n vtkIdType numCells = faces->GetNumberOfCells();\n\n vtkIdType cellLocation = 0;\n\n \/\/ Write the standard format header for the json file\n outputFile << \"\\\"metadata\\\":{\\\"formatVersion\\\":3,\\\"vertices\\\":\" << vert << \",\\\"faces\\\":\" << numCells << \",\\\"materials\\\":1},\\n\";\n outputFile << \"\\\"scale\\\":1.0,\\n\\\"materials\\\":[{\\\"DbgColor\\\":15658734,\\\"DbgIndex\\\":0,\\\"DbgName\\\":\\\"default\\\",\\\"vertexColors\\\": false}],\\n\";\n\n \/\/ Begin writing vertices\n outputFile << \"\\\"vertices\\\":[\";\n\n \/\/ Iterate over all the points and print them to the file\n for(vtkIdType i = 0; i < vert; i++) {\n double p[3];\n data->GetPoint(i, p);\n outputFile << p[0] << \",\" << p[1] << \",\" << p[2];\n if (i != vert - 1) outputFile << \",\"; \/\/ Avoid putting comma before end bracket\n }\n \/\/ End the vertices section\n outputFile << \"],\\n\";\n\n \/\/ Begin writing faces\n outputFile << \"\\\"faces\\\":[\";\n\n \/\/ Iterate over the faces and print them to file\n for (vtkIdType i = 0; i < numCells; i++) {\n vtkIdType numIDs;\n vtkIdType * pointIds;\n\n faces->GetCell(cellLocation, numIDs, pointIds);\n cellLocation += 1 + numIDs; \/\/ increment to include already printed faces\n\n for (vtkIdType j = 0; j < numIDs; j++) {\n \/\/ print to the file\n \/\/ printing the zero is for the bit mask signifying face type\n if (j == 0) outputFile << 0 << \",\";\n outputFile << pointIds[j];\n if (i != numCells - 1) {\n outputFile << \",\";\n }\n else {\n if(j != numIDs - 1) outputFile << \",\"; \/\/ avoid additional comma at end\n }\n }\n }\n\n \/\/ end faces section\n outputFile << \"]\\n\";\n\n \/\/ end the json file\n outputFile << \"}\\n\";\n\n \/\/ flush the file stream\n outputFile.flush();\n\n \/\/ close file stream\n outputFile.close();\n}\nvtk surface area and volume\/*\n * vtk2json\n *\n * The program is a PLY\/VTK file format to JSON file format converter for use\n * with three.js. The program uses the C++ libraries from the VTK toolkit\n * in order to read in a model file and convert it into the json file format\n * which can be recongnized by three.js for rendering in browser WebGL.\n *\n * Migara Liyanamage <>\n * Frank Zhao \n * June 2014\n *\n *\/\n\n\n\/\/ Import for VTK Libraries\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Import for standard C++ libraries\n#include \n#include \n\n\/\/ Import program header\n#include \"vtk2json.h\"\n\nusing namespace std;\n\n\/*\n * Generate JSON Method\n *\n * This method calls the appropriate methods in the vtk toolkit and outputs the\n * JSON file to the output file name specified\n *\n *\/\nvoid vtk2json(bool preserveTopology, bool splitting, bool boundaryVertexDeletion, \n bool verbose, float decAmount, std::string inputFilename, std::string outputFilename) {\n \/\/ File stream for output file\n std::ofstream outputFile;\n outputFile.open(outputFilename.c_str());\n\n \/\/ begin the json file\n outputFile << \"{\\n\";\n\n \/\/ Reader to read in model\n vtkSmartPointer reader =\n vtkSmartPointer::New();\n\n \/\/ Specify filename\n reader->SetFileName ( inputFilename.c_str() );\n\n \/\/ Call vtk pipeline to read in the file\n reader->Update();\n\n \/\/ Variables for storing polygons and points\n vtkDataSet * data;\n vtkIdType vert;\n vtkPolyData * pdata;\n vtkCellArray * faces;\n vtkSmartPointer decimated;\n\n if (decAmount == 0.0) {\n \/\/ Get the output for vertices\n data = reader->GetPolyDataOutput();\n vert = data->GetNumberOfPoints();\n\n \/\/ Get the output for polygons\n pdata = reader->GetPolyDataOutput();\n faces = pdata->GetPolys();\n \n } else if (decAmount < 0.0) {\n cout << \"Invalid Decimate Amount, Program will now exit\" << endl;\n exit(EXIT_FAILURE);\n } else {\n \/\/ create decimator\n vtkSmartPointer decimate = vtkSmartPointer::New();\n\n \/\/ set decimator to the selected file\n decimate->SetInputData(reader->GetOutput());\n\n \/\/ set target to reduce to, and set topology to be preserved\n if (preserveTopology) {decimate->PreserveTopologyOn();} \n else {decimate->PreserveTopologyOff();}\n \n \/\/ splitting\n if (splitting) {decimate->SplittingOn();}\n else {decimate->SplittingOff();}\n \n \/\/ Boundary vertex deletion\n if (boundaryVertexDeletion) {decimate->BoundaryVertexDeletionOn();}\n else {decimate->BoundaryVertexDeletionOff();}\n \n decimate->SetTargetReduction(decAmount);\n\n \/\/ start decimation\n decimate->Update();\n\n decimated =\n vtkSmartPointer::New();\n decimated->ShallowCopy(decimate->GetOutput());\n\n \/\/ Get the output for vertices\n data = decimated;\n vert = decimated->GetNumberOfPoints();\n\n \/\/ Get the output for polygons\n faces = decimated->GetPolys();\n }\n \n \/\/ Calculate VTK model properties\n vtkSmartPointer mass = vtkMassProperties::New();\n mass->SetInputData(data);\n mass->Update();\n\n vtkIdType numCells = faces->GetNumberOfCells();\n\n vtkIdType cellLocation = 0;\n\n \/\/ Write the standard format header for the json file\n \n outputFile << \"\\\"metadata\\\":{\\\"formatVersion\\\":3,\\\"vertices\\\":\" << vert << \",\\\"faces\\\":\" << numCells << \",\\\"materials\\\":1,\\\"volume\\\":\" << mass->GetVolume() << \",\\\"surface_area\\\":\" << mass->GetSurfaceArea() << \"},\\n\";\n outputFile << \"\\\"scale\\\":1.0,\\n\\\"materials\\\":[{\\\"DbgColor\\\":15658734,\\\"DbgIndex\\\":0,\\\"DbgName\\\":\\\"default\\\",\\\"vertexColors\\\": false}],\\n\";\n\n \/\/ Begin writing vertices\n outputFile << \"\\\"vertices\\\":[\";\n\n \/\/ Iterate over all the points and print them to the file\n for(vtkIdType i = 0; i < vert; i++) {\n double p[3];\n data->GetPoint(i, p);\n outputFile << p[0] << \",\" << p[1] << \",\" << p[2];\n if (i != vert - 1) outputFile << \",\"; \/\/ Avoid putting comma before end bracket\n }\n \/\/ End the vertices section\n outputFile << \"],\\n\";\n\n \/\/ Begin writing faces\n outputFile << \"\\\"faces\\\":[\";\n\n \/\/ Iterate over the faces and print them to file\n for (vtkIdType i = 0; i < numCells; i++) {\n vtkIdType numIDs;\n vtkIdType * pointIds;\n\n faces->GetCell(cellLocation, numIDs, pointIds);\n cellLocation += 1 + numIDs; \/\/ increment to include already printed faces\n\n for (vtkIdType j = 0; j < numIDs; j++) {\n \/\/ print to the file\n \/\/ printing the zero is for the bit mask signifying face type\n if (j == 0) outputFile << 0 << \",\";\n outputFile << pointIds[j];\n if (i != numCells - 1) {\n outputFile << \",\";\n }\n else {\n if(j != numIDs - 1) outputFile << \",\"; \/\/ avoid additional comma at end\n }\n }\n }\n\n \/\/ end faces section\n outputFile << \"]\\n\";\n\n \/\/ end the json file\n outputFile << \"}\\n\";\n\n \/\/ flush the file stream\n outputFile.flush();\n\n \/\/ close file stream\n outputFile.close();\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2002-2005 The Apache Software Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * XSEC\n *\n * XSECPlatformUtils:= To support the platform we run in\n *\n * Author(s): Berin Lautenbach\n *\n * $Id$\n *\n *\/\n\n\/\/ XSEC\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"..\/xenc\/impl\/XENCCipherImpl.hpp\"\n\n#if defined(_WIN32)\n#include \n#endif\n\n#if defined (HAVE_OPENSSL)\n#\tinclude \n#endif\n\n#if defined (HAVE_WINCAPI)\n#\tinclude \n#endif\n\n\/\/ Static data used by all of XSEC\nint XSECPlatformUtils::initCount = 0;\nXSECCryptoProvider * XSECPlatformUtils::g_cryptoProvider = NULL;\n\n\/\/ Have a const copy for external usage\nconst XSECAlgorithmMapper * XSECPlatformUtils::g_algorithmMapper = NULL;\n\nXSECAlgorithmMapper * internalMapper = NULL;\n\n\/\/ Determine default crypto provider\n\n#if defined (HAVE_OPENSSL)\n#\tdefine XSEC_DEFAULT_PROVIDER\tOpenSSLCryptoProvider()\n#else\n#\tif defined (HAVE_WINCAPI)\n#\t\tdefine XSEC_DEFAULT_PROVIDER\tWinCAPICryptoProvider()\n#\tendif\n#endif\n\nvoid XSECPlatformUtils::Initialise(XSECCryptoProvider * p) {\n\n\tif (++initCount > 1)\n\t\treturn;\n\n\tif (p != NULL)\n\t\tg_cryptoProvider = p;\n\telse\n#if defined XSEC_DEFAULT_PROVIDER\n\t\tXSECnew(g_cryptoProvider, XSEC_DEFAULT_PROVIDER);\n#else\n\tthrow XSECException(XSECException::CryptoProviderError,\n\t\t\"XSECPlatformUtils::Initialise() called with NULL provider, but no default defined\");\n#endif\n\n\t\/\/ Set up necessary constants\n\tDSIGConstants::create();\n\tXKMSConstants::create();\n\n\t\/\/ Initialise the safeBuffer system\n\tsafeBuffer::init();\n\n\t\/\/ Initialise Algorithm Mapper\n\tXSECnew(internalMapper, XSECAlgorithmMapper);\n\tg_algorithmMapper = internalMapper;\n\n\t\/\/ Initialise the XENCCipherImpl class\n\tXENCCipherImpl::Initialise();\n\n\t\/\/ Initialise the DSIGSignature class\n\tDSIGSignature::Initialise();\n\n};\n\nvoid XSECPlatformUtils::SetCryptoProvider(XSECCryptoProvider * p) {\n\n\tif (g_cryptoProvider != NULL)\n\t\tdelete g_cryptoProvider;\n\n\tg_cryptoProvider = p;\n\n}\n\n\nvoid XSECPlatformUtils::Terminate(void) {\n\n\tif (--initCount > 0)\n\t\treturn;\n\n\t\/\/ Clean out the algorithm mapper\n\tdelete internalMapper;\n\n\tif (g_cryptoProvider != NULL)\n\t\tdelete g_cryptoProvider;\n\n\tDSIGConstants::destroy();\n\tXKMSConstants::destroy();\n\n\t\/\/ Destroy anything platform specific\n#if defined(_WIN32)\n\tXSECBinHTTPURIInputStream::Cleanup();\n#endif\n\n}\n\nvoid XSECPlatformUtils::registerAlgorithmHandler(\n\t\tconst XMLCh * uri, \n\t\tconst XSECAlgorithmHandler & handler) {\n\n\tinternalMapper->registerHandler(uri, handler);\n\n}\n\nAllow NSS as a default provider\/*\n * Copyright 2002-2005 The Apache Software Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * XSEC\n *\n * XSECPlatformUtils:= To support the platform we run in\n *\n * Author(s): Berin Lautenbach\n *\n * $Id$\n *\n *\/\n\n\/\/ XSEC\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"..\/xenc\/impl\/XENCCipherImpl.hpp\"\n\n#if defined(_WIN32)\n#include \n#endif\n\n#if defined (HAVE_OPENSSL)\n#\tinclude \n#endif\n\n#if defined (HAVE_WINCAPI)\n#\tinclude \n#endif\n\n#if defined (HAVE_NSS)\n#\tinclude \n#endif\n\n\/\/ Static data used by all of XSEC\nint XSECPlatformUtils::initCount = 0;\nXSECCryptoProvider * XSECPlatformUtils::g_cryptoProvider = NULL;\n\n\/\/ Have a const copy for external usage\nconst XSECAlgorithmMapper * XSECPlatformUtils::g_algorithmMapper = NULL;\n\nXSECAlgorithmMapper * internalMapper = NULL;\n\n\/\/ Determine default crypto provider\n\n#if defined (HAVE_OPENSSL)\n#\tdefine XSEC_DEFAULT_PROVIDER\tOpenSSLCryptoProvider()\n#else\n#\tif defined (HAVE_WINCAPI)\n#\t\tdefine XSEC_DEFAULT_PROVIDER\tWinCAPICryptoProvider()\n#\telse \n#\t\tif defined (HAVE_NSS)\n#\t\t\tdefine XSEC_DEFAULT_PROVIDER\tNSSCryptoProvider()\n#\t\tendif\n#\tendif\n#endif\n\nvoid XSECPlatformUtils::Initialise(XSECCryptoProvider * p) {\n\n\tif (++initCount > 1)\n\t\treturn;\n\n\tif (p != NULL)\n\t\tg_cryptoProvider = p;\n\telse\n#if defined XSEC_DEFAULT_PROVIDER\n\t\tXSECnew(g_cryptoProvider, XSEC_DEFAULT_PROVIDER);\n#else\n\tthrow XSECException(XSECException::CryptoProviderError,\n\t\t\"XSECPlatformUtils::Initialise() called with NULL provider, but no default defined\");\n#endif\n\n\t\/\/ Set up necessary constants\n\tDSIGConstants::create();\n\tXKMSConstants::create();\n\n\t\/\/ Initialise the safeBuffer system\n\tsafeBuffer::init();\n\n\t\/\/ Initialise Algorithm Mapper\n\tXSECnew(internalMapper, XSECAlgorithmMapper);\n\tg_algorithmMapper = internalMapper;\n\n\t\/\/ Initialise the XENCCipherImpl class\n\tXENCCipherImpl::Initialise();\n\n\t\/\/ Initialise the DSIGSignature class\n\tDSIGSignature::Initialise();\n\n};\n\nvoid XSECPlatformUtils::SetCryptoProvider(XSECCryptoProvider * p) {\n\n\tif (g_cryptoProvider != NULL)\n\t\tdelete g_cryptoProvider;\n\n\tg_cryptoProvider = p;\n\n}\n\n\nvoid XSECPlatformUtils::Terminate(void) {\n\n\tif (--initCount > 0)\n\t\treturn;\n\n\t\/\/ Clean out the algorithm mapper\n\tdelete internalMapper;\n\n\tif (g_cryptoProvider != NULL)\n\t\tdelete g_cryptoProvider;\n\n\tDSIGConstants::destroy();\n\tXKMSConstants::destroy();\n\n\t\/\/ Destroy anything platform specific\n#if defined(_WIN32)\n\tXSECBinHTTPURIInputStream::Cleanup();\n#endif\n\n}\n\nvoid XSECPlatformUtils::registerAlgorithmHandler(\n\t\tconst XMLCh * uri, \n\t\tconst XSECAlgorithmHandler & handler) {\n\n\tinternalMapper->registerHandler(uri, handler);\n\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"local_graph.hpp\"\n#include \"Hypercube.hpp\"\n\n\n\/\/ graph includes\n#include \"..\/graph500\/grappa\/graph.hpp\"\n#include \"..\/graph500\/generator\/make_graph.h\"\n#include \"..\/graph500\/generator\/utils.h\"\n#include \"..\/graph500\/prng.h\"\n\n#include \"..\/graph500\/grappa\/graph.hpp\"\n\nusing namespace Grappa;\n\n#define DIFFERENT_RELATIONS 0\n#define DEDUP_EDGES 1\n\n\/\/ Currently assumes an undirected graph implemented as a large directed graph!!\n\nDEFINE_uint64( scale, 7, \"Graph will have ~ 2^scale vertices\" );\nDEFINE_uint64( edgefactor, 16, \"Median degree; graph will have ~ 2*edgefactor*2^scale edges\" );\nDEFINE_uint64( progressInterval, 5, \"interval between progress updates\" );\n\nGRAPPA_DEFINE_STAT(SimpleStatistic, edges_transfered, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, total_edges, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, participating_cores, 0);\n\n\/\/ intermediate results counts\n\/\/ only care about min, max, totals\nGRAPPA_DEFINE_STAT(SimpleStatistic, ir1_count, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, ir2_count, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, ir3_count, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, ir4_count, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, ir5_count, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, ir6_count, 0);\n\nGRAPPA_DEFINE_STAT(SummarizingStatistic, ir1_final_count, 0);\nGRAPPA_DEFINE_STAT(SummarizingStatistic, ir2_final_count, 0);\nGRAPPA_DEFINE_STAT(SummarizingStatistic, ir3_final_count, 0);\nGRAPPA_DEFINE_STAT(SummarizingStatistic, ir4_final_count, 0);\nGRAPPA_DEFINE_STAT(SummarizingStatistic, ir5_final_count, 0);\nGRAPPA_DEFINE_STAT(SummarizingStatistic, ir6_final_count, 0);\n\n\n\/\/outputs\nGRAPPA_DEFINE_STAT(SimpleStatistic, results_count, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, query_runtime, 0);\n\ndouble generation_time;\ndouble construction_time;\n\nuint64_t count = 0;\nuint64_t edgesSent = 0;\n\nvoid emit(int64_t x, int64_t y, int64_t z, int64_t t) {\n\/\/ std::cout << x << \" \" << y << \" \" << z << std::endl;\n count++;\n}\n\n\nstd::vector localAssignedEdges_R1;\nstd::vector localAssignedEdges_R2;\nstd::vector localAssignedEdges_R3;\nstd::vector localAssignedEdges_R4;\n\n\/\/TODO\nstd::function makeHash( int64_t dim ) {\n \/\/ identity\n return [dim](int64_t x) { return x % dim; };\n}\n\nint64_t fourth_root(int64_t x) {\n \/\/ index pow 4\n std::vector powers = {0, 1, 16, 81, 256, 625, 1296, 2401};\n int64_t ind = powers.size() \/ 2;\n int64_t hi = powers.size()-1;\n int64_t lo = 0;\n while(true) {\n if (x == powers[ind]) {\n return ind;\n } else if (x > powers[ind]) {\n int64_t next = (ind+hi)\/2;\n if (next - ind == 0) {\n return ind;\n }\n lo = ind;\n ind = next;\n } else {\n int64_t next = (ind+lo)\/2;\n hi = ind;\n ind = next;\n }\n }\n}\n\n\/\/int64_t random_assignment(int64_t x) {\n\/\/ std::random_device rd;\n\/\/\n\/\/ \/\/ Choose a random mean between 1 and 6\n\/\/ std::default_random_engine e1(rd());\n\/\/ const int64_t root1 = fourth_root(x);\n\/\/ std::normal_distribution<> normal_dist1(root1, root1\/1.25);\n\/\/\n\/\/ const int64_t share1 = std::round(max(1, normal_dist1(e1)));\n\/\/ const int64_t left1 = x\/share1;\n\/\/ const int64_t root2 = std::round(cbrt(left));\n\/\/ std::normal_distribution<> normal_dist2(root2, root2\/1.25);\n\/\/ const int64_t share2 = std::round(max(1, normal_dist2(e1)));\n\/\/ const int64_t left2 = left1\/share2;\n\/\/\n \n \n\nvoid squares(GlobalAddress> g) {\n \n on_all_cores( [] { Grappa::Statistics::reset(); } );\n\n \/\/ arrange the processors in 4d\n auto sidelength = fourth_root(cores());\n LOG(INFO) << \"using \" << sidelength*sidelength*sidelength*sidelength << \" of \" << cores() << \" cores\";\n participating_cores = sidelength*sidelength*sidelength*sidelength;\n \n\n double start, end;\n start = Grappa_walltime(); \n \n \/\/ 1. Send edges to the partitions\n \/\/\n \/\/ really just care about local edges; we get to them\n \/\/ indirectly through local vertices at the moment.\n \/\/ This is sequential access since edgeslists and vertices are sorted the same\n forall_localized( g->vs, g->nv, [sidelength](int64_t i, Vertex& v) {\n \/\/ hash function\n auto hf = makeHash( sidelength );\n Hypercube h( { sidelength, sidelength, sidelength, sidelength } );\n\n for (auto& dest : v.adj_iter()) {\n\n total_edges += 4; \/\/ count 4 for 4 relations\n \n const int64_t src = i;\n const int64_t dst = dest;\n\n \/\/ a->b\n auto locs_ab = h.slice( {hf(src), hf(dst), HypercubeSlice::ALL, HypercubeSlice::ALL} );\n for (auto l : locs_ab) {\n Edge e(src, dst);\n delegate::call_async( l, [e] { \n localAssignedEdges_R1.push_back(e); \n });\n edgesSent++;\n }\n\n \/\/ b->c\n auto locs_bc = h.slice( {HypercubeSlice::ALL, hf(src), hf(dst), HypercubeSlice::ALL} );\n for (auto l : locs_bc) {\n Edge e(src, dst);\n delegate::call_async( l, [e] { \n localAssignedEdges_R2.push_back(e); \n });\n edgesSent++;\n }\n\n \/\/ c->d\n auto locs_cd = h.slice( {HypercubeSlice::ALL, HypercubeSlice::ALL, hf(src), hf(dst)} );\n for (auto l : locs_cd) {\n Edge e(src, dst);\n delegate::call_async( l, [e] { \n localAssignedEdges_R3.push_back(e); \n });\n edgesSent++;\n }\n\n \/\/ d->a\n auto locs_da = h.slice( {hf(dst), HypercubeSlice::ALL, HypercubeSlice::ALL, hf(src)} );\n for (auto l : locs_da) {\n Edge e(src, dst);\n delegate::call_async( l, [e] { \n localAssignedEdges_R4.push_back(e); \n });\n edgesSent++;\n }\n }\n });\n on_all_cores([] { \n LOG(INFO) << \"edges sent: \" << edgesSent;\n edges_transfered += edgesSent;\n });\n \n\n \/\/ 2. compute squares locally\n \/\/\n on_all_cores([] {\n\n LOG(INFO) << \"received (\" << localAssignedEdges_R1.size() << \", \" << localAssignedEdges_R2.size() << \", \" << localAssignedEdges_R3.size() << \", \" << localAssignedEdges_R4.size() << \") edges\";\n\n#ifdef DEDUP_EDGES\n \/\/ construct local graphs\n LOG(INFO) << \"dedup...\";\n std::unordered_set R1_dedup;\n std::unordered_set R2_dedup;\n std::unordered_set R3_dedup;\n std::unordered_set R4_dedup;\n for (auto e : localAssignedEdges_R1) { R1_dedup.insert( e ); }\n for (auto e : localAssignedEdges_R2) { R2_dedup.insert( e ); }\n for (auto e : localAssignedEdges_R3) { R3_dedup.insert( e ); }\n for (auto e : localAssignedEdges_R3) { R4_dedup.insert( e ); }\n \n LOG(INFO) << \"after dedup (\" << R1_dedup.size() << \", \" << R2_dedup.size() << \", \" << R3_dedup.size() << \", \" << R4_dedup.size() << \") edges\";\n\n localAssignedEdges_R1.resize(1);\n localAssignedEdges_R2.resize(1);\n localAssignedEdges_R3.resize(1);\n localAssignedEdges_R4.resize(1);\n\n\n LOG(INFO) << \"local graph construct...\";\n auto& R1 = *new LocalAdjListGraph(R1_dedup);\n auto& R2 = *new LocalAdjListGraph(R2_dedup);\n auto& R3 = *new LocalAdjListGraph(R3_dedup);\n auto& R4 = *new LocalMapGraph(R4_dedup);\n#else\n LOG(INFO) << \"local graph construct...\";\n auto& R1 = *new LocalAdjListGraph(localAssignedEdges_R1);\n auto& R2 = *new LocalAdjListGraph(localAssignedEdges_R2);\n auto& R3 = *new LocalAdjListGraph(localAssignedEdges_R3);\n auto& R4 = *new LocalMapGraph(localAssignedEdges_R4);\n#endif\n\n \/\/ use number of adjacencies (degree) as the ordering\n \/\/ EVAR: implementation of triangle count\n int64_t i=0;\n for (auto xy : R1.vertices()) {\n ir1_count++;\n int64_t x = xy.first;\n auto& xadj = xy.second;\n for (auto y : xadj) {\n ir2_count++;\n auto& yadj = R2.neighbors(y);\n if (xadj.size() < yadj.size()) { \n ir3_count++;\n for (auto z : yadj) {\n ir4_count++;\n auto& zadj = R3.neighbors(y);\n if (yadj.size() < zadj.size()) {\n ir5_count++;\n for (auto t : zadj) {\n ir6_count++;\n if (R4.inNeighborhood(t, x)) {\n emit( x,y,z,t );\n results_count++;\n } \/\/ end select t.dst=x\n } \/\/ end over t\n } \/\/ end select y < z\n } \/\/ end over z\n } \/\/ end select x < y\n } \/\/ end over y\n } \/\/ end over x\n\n LOG(INFO) << \"counted \" << count << \" squares\";\n\n\n \/\/ used to calculate max total over all cores\n ir1_final_count=ir1_count;\n ir2_final_count=ir2_count;\n ir3_final_count=ir3_count;\n ir4_final_count=ir4_count;\n ir5_final_count=ir5_count;\n ir6_final_count=ir6_count;\n\n });\n end = Grappa_walltime();\n query_runtime = end - start;\n\n \n Grappa::Statistics::merge_and_print();\n \n}\n\n\nvoid user_main( int * ignore ) {\n double t, start_time;\n start_time = walltime();\n \n\tint64_t nvtx_scale = ((int64_t)1)<(desired_nedge);\n \n LOG(INFO) << \"graph generation...\";\n t = walltime();\n make_graph( FLAGS_scale, desired_nedge, userseed, userseed, &tg.nedge, &tg.edges );\n generation_time = walltime() - t;\n LOG(INFO) << \"graph_generation: \" << generation_time;\n \n LOG(INFO) << \"graph construction...\";\n t = walltime();\n auto g = Graph::create(tg);\n construction_time = walltime() - t;\n LOG(INFO) << \"construction_time: \" << construction_time;\n\n LOG(INFO) << \"num edges: \" << g->nadj * 3; \/* 3 b\/c three copies*\/\n\n LOG(INFO) << \"query start...\";\n squares(g);\n}\n\n\nint main(int argc, char** argv) {\n Grappa_init(&argc, &argv);\n Grappa_activate();\n\n Grappa_run_user_main(&user_main, (int*)NULL);\n\n Grappa_finish(0);\n return 0;\n}\nfix intermediate result counting to include a last filter#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"local_graph.hpp\"\n#include \"Hypercube.hpp\"\n\n\n\/\/ graph includes\n#include \"..\/graph500\/grappa\/graph.hpp\"\n#include \"..\/graph500\/generator\/make_graph.h\"\n#include \"..\/graph500\/generator\/utils.h\"\n#include \"..\/graph500\/prng.h\"\n\n#include \"..\/graph500\/grappa\/graph.hpp\"\n\nusing namespace Grappa;\n\n#define DIFFERENT_RELATIONS 0\n#define DEDUP_EDGES 1\n\n\/\/ Currently assumes an undirected graph implemented as a large directed graph!!\n\nDEFINE_uint64( scale, 7, \"Graph will have ~ 2^scale vertices\" );\nDEFINE_uint64( edgefactor, 16, \"Median degree; graph will have ~ 2*edgefactor*2^scale edges\" );\nDEFINE_uint64( progressInterval, 5, \"interval between progress updates\" );\n\nGRAPPA_DEFINE_STAT(SimpleStatistic, edges_transfered, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, total_edges, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, participating_cores, 0);\n\n\/\/ intermediate results counts\n\/\/ only care about min, max, totals\nGRAPPA_DEFINE_STAT(SimpleStatistic, ir1_count, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, ir2_count, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, ir3_count, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, ir4_count, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, ir5_count, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, ir6_count, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, ir7_count, 0);\n\nGRAPPA_DEFINE_STAT(SummarizingStatistic, ir1_final_count, 0);\nGRAPPA_DEFINE_STAT(SummarizingStatistic, ir2_final_count, 0);\nGRAPPA_DEFINE_STAT(SummarizingStatistic, ir3_final_count, 0);\nGRAPPA_DEFINE_STAT(SummarizingStatistic, ir4_final_count, 0);\nGRAPPA_DEFINE_STAT(SummarizingStatistic, ir5_final_count, 0);\nGRAPPA_DEFINE_STAT(SummarizingStatistic, ir6_final_count, 0);\nGRAPPA_DEFINE_STAT(SummarizingStatistic, ir7_final_count, 0);\n\n\n\/\/outputs\nGRAPPA_DEFINE_STAT(SimpleStatistic, results_count, 0);\nGRAPPA_DEFINE_STAT(SimpleStatistic, query_runtime, 0);\n\ndouble generation_time;\ndouble construction_time;\n\nuint64_t count = 0;\nuint64_t edgesSent = 0;\n\nvoid emit(int64_t x, int64_t y, int64_t z, int64_t t) {\n\/\/ std::cout << x << \" \" << y << \" \" << z << std::endl;\n count++;\n}\n\n\nstd::vector localAssignedEdges_R1;\nstd::vector localAssignedEdges_R2;\nstd::vector localAssignedEdges_R3;\nstd::vector localAssignedEdges_R4;\n\n\/\/TODO\nstd::function makeHash( int64_t dim ) {\n \/\/ identity\n return [dim](int64_t x) { return x % dim; };\n}\n\nint64_t fourth_root(int64_t x) {\n \/\/ index pow 4\n std::vector powers = {0, 1, 16, 81, 256, 625, 1296, 2401};\n int64_t ind = powers.size() \/ 2;\n int64_t hi = powers.size()-1;\n int64_t lo = 0;\n while(true) {\n if (x == powers[ind]) {\n return ind;\n } else if (x > powers[ind]) {\n int64_t next = (ind+hi)\/2;\n if (next - ind == 0) {\n return ind;\n }\n lo = ind;\n ind = next;\n } else {\n int64_t next = (ind+lo)\/2;\n hi = ind;\n ind = next;\n }\n }\n}\n\n\/\/int64_t random_assignment(int64_t x) {\n\/\/ std::random_device rd;\n\/\/\n\/\/ \/\/ Choose a random mean between 1 and 6\n\/\/ std::default_random_engine e1(rd());\n\/\/ const int64_t root1 = fourth_root(x);\n\/\/ std::normal_distribution<> normal_dist1(root1, root1\/1.25);\n\/\/\n\/\/ const int64_t share1 = std::round(max(1, normal_dist1(e1)));\n\/\/ const int64_t left1 = x\/share1;\n\/\/ const int64_t root2 = std::round(cbrt(left));\n\/\/ std::normal_distribution<> normal_dist2(root2, root2\/1.25);\n\/\/ const int64_t share2 = std::round(max(1, normal_dist2(e1)));\n\/\/ const int64_t left2 = left1\/share2;\n\/\/\n \n \n\nvoid squares(GlobalAddress> g) {\n \n on_all_cores( [] { Grappa::Statistics::reset(); } );\n\n \/\/ arrange the processors in 4d\n auto sidelength = fourth_root(cores());\n LOG(INFO) << \"using \" << sidelength*sidelength*sidelength*sidelength << \" of \" << cores() << \" cores\";\n participating_cores = sidelength*sidelength*sidelength*sidelength;\n \n\n double start, end;\n start = Grappa_walltime(); \n \n \/\/ 1. Send edges to the partitions\n \/\/\n \/\/ really just care about local edges; we get to them\n \/\/ indirectly through local vertices at the moment.\n \/\/ This is sequential access since edgeslists and vertices are sorted the same\n forall_localized( g->vs, g->nv, [sidelength](int64_t i, Vertex& v) {\n \/\/ hash function\n auto hf = makeHash( sidelength );\n Hypercube h( { sidelength, sidelength, sidelength, sidelength } );\n\n for (auto& dest : v.adj_iter()) {\n\n total_edges += 4; \/\/ count 4 for 4 relations\n \n const int64_t src = i;\n const int64_t dst = dest;\n\n \/\/ a->b\n auto locs_ab = h.slice( {hf(src), hf(dst), HypercubeSlice::ALL, HypercubeSlice::ALL} );\n for (auto l : locs_ab) {\n Edge e(src, dst);\n delegate::call_async( l, [e] { \n localAssignedEdges_R1.push_back(e); \n });\n edgesSent++;\n }\n\n \/\/ b->c\n auto locs_bc = h.slice( {HypercubeSlice::ALL, hf(src), hf(dst), HypercubeSlice::ALL} );\n for (auto l : locs_bc) {\n Edge e(src, dst);\n delegate::call_async( l, [e] { \n localAssignedEdges_R2.push_back(e); \n });\n edgesSent++;\n }\n\n \/\/ c->d\n auto locs_cd = h.slice( {HypercubeSlice::ALL, HypercubeSlice::ALL, hf(src), hf(dst)} );\n for (auto l : locs_cd) {\n Edge e(src, dst);\n delegate::call_async( l, [e] { \n localAssignedEdges_R3.push_back(e); \n });\n edgesSent++;\n }\n\n \/\/ d->a\n auto locs_da = h.slice( {hf(dst), HypercubeSlice::ALL, HypercubeSlice::ALL, hf(src)} );\n for (auto l : locs_da) {\n Edge e(src, dst);\n delegate::call_async( l, [e] { \n localAssignedEdges_R4.push_back(e); \n });\n edgesSent++;\n }\n }\n });\n on_all_cores([] { \n LOG(INFO) << \"edges sent: \" << edgesSent;\n edges_transfered += edgesSent;\n });\n \n\n \/\/ 2. compute squares locally\n \/\/\n on_all_cores([] {\n\n LOG(INFO) << \"received (\" << localAssignedEdges_R1.size() << \", \" << localAssignedEdges_R2.size() << \", \" << localAssignedEdges_R3.size() << \", \" << localAssignedEdges_R4.size() << \") edges\";\n\n#ifdef DEDUP_EDGES\n \/\/ construct local graphs\n LOG(INFO) << \"dedup...\";\n std::unordered_set R1_dedup;\n std::unordered_set R2_dedup;\n std::unordered_set R3_dedup;\n std::unordered_set R4_dedup;\n for (auto e : localAssignedEdges_R1) { R1_dedup.insert( e ); }\n for (auto e : localAssignedEdges_R2) { R2_dedup.insert( e ); }\n for (auto e : localAssignedEdges_R3) { R3_dedup.insert( e ); }\n for (auto e : localAssignedEdges_R3) { R4_dedup.insert( e ); }\n \n LOG(INFO) << \"after dedup (\" << R1_dedup.size() << \", \" << R2_dedup.size() << \", \" << R3_dedup.size() << \", \" << R4_dedup.size() << \") edges\";\n\n localAssignedEdges_R1.resize(1);\n localAssignedEdges_R2.resize(1);\n localAssignedEdges_R3.resize(1);\n localAssignedEdges_R4.resize(1);\n\n\n LOG(INFO) << \"local graph construct...\";\n auto& R1 = *new LocalAdjListGraph(R1_dedup);\n auto& R2 = *new LocalAdjListGraph(R2_dedup);\n auto& R3 = *new LocalAdjListGraph(R3_dedup);\n auto& R4 = *new LocalMapGraph(R4_dedup);\n#else\n LOG(INFO) << \"local graph construct...\";\n auto& R1 = *new LocalAdjListGraph(localAssignedEdges_R1);\n auto& R2 = *new LocalAdjListGraph(localAssignedEdges_R2);\n auto& R3 = *new LocalAdjListGraph(localAssignedEdges_R3);\n auto& R4 = *new LocalMapGraph(localAssignedEdges_R4);\n#endif\n\n \/\/ use number of adjacencies (degree) as the ordering\n \/\/ EVAR: implementation of triangle count\n int64_t i=0;\n for (auto xy : R1.vertices()) {\n int64_t x = xy.first;\n auto& xadj = xy.second;\n for (auto y : xadj) {\n ir1_count++; \/\/ count(R1)\n auto& yadj = R2.neighbors(y);\n ir2_count+=yadj.size(); \/\/ count(R1xR2)\n if (xadj.size() < yadj.size()) { \n ir3_count+=yadj.size(); \/\/ count(sel(R1xR2))\n for (auto z : yadj) {\n auto& zadj = R3.neighbors(y);\n ir4_count+=zadj.size(); \/\/ count(sel(R1xR2)xR3)\n if (yadj.size() < zadj.size()) {\n ir5_count+=zadj.size(); \/\/ count(sel(sel(R1xR2)xR3))\n for (auto t : zadj) {\n auto tadjsize = R4.nadj(t);\n ir6_count+=tadjsize; \/\/ count(sel(sel(R1xR2)xR3)xR4)\n if (zadj.size() < tadjsize) {\n ir7_count+=tadjsize; \/\/ count(sel(sel(sel(R1xR2)xR3)xR4))\n if (R4.inNeighborhood(t, x)) {\n emit( x,y,z,t );\n results_count++; \/\/ count(sel(sel(sel(R1dxR2)xR3)xR4)xR1s)\n } \/\/ end select t.dst=x\n } \/\/ end select z < t\n } \/\/ end over t\n } \/\/ end select y < z\n } \/\/ end over z\n } \/\/ end select x < y\n } \/\/ end over y\n } \/\/ end over x\n\n LOG(INFO) << \"counted \" << count << \" squares\";\n\n\n \/\/ used to calculate max total over all cores\n ir1_final_count=ir1_count;\n ir2_final_count=ir2_count;\n ir3_final_count=ir3_count;\n ir4_final_count=ir4_count;\n ir5_final_count=ir5_count;\n ir6_final_count=ir6_count;\n ir7_final_count=ir7_count;\n\n });\n end = Grappa_walltime();\n query_runtime = end - start;\n\n \n Grappa::Statistics::merge_and_print();\n \n}\n\n\nvoid user_main( int * ignore ) {\n double t, start_time;\n start_time = walltime();\n \n\tint64_t nvtx_scale = ((int64_t)1)<(desired_nedge);\n \n LOG(INFO) << \"graph generation...\";\n t = walltime();\n make_graph( FLAGS_scale, desired_nedge, userseed, userseed, &tg.nedge, &tg.edges );\n generation_time = walltime() - t;\n LOG(INFO) << \"graph_generation: \" << generation_time;\n \n LOG(INFO) << \"graph construction...\";\n t = walltime();\n auto g = Graph::create(tg);\n construction_time = walltime() - t;\n LOG(INFO) << \"construction_time: \" << construction_time;\n\n LOG(INFO) << \"num edges: \" << g->nadj * 3; \/* 3 b\/c three copies*\/\n\n LOG(INFO) << \"query start...\";\n squares(g);\n}\n\n\nint main(int argc, char** argv) {\n Grappa_init(&argc, &argv);\n Grappa_activate();\n\n Grappa_run_user_main(&user_main, (int*)NULL);\n\n Grappa_finish(0);\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"WebMediaPlayerClientImpl.h\"\n\n#if ENABLE(VIDEO)\n\n\/\/ FIXME: GraphicsContext.h should include this itself!\n#if WEBKIT_USING_SKIA\n#include \"PlatformContextSkia.h\"\n#endif\n\n#include \"CString.h\"\n#include \"Frame.h\"\n#include \"GraphicsContext.h\"\n#include \"HTMLMediaElement.h\"\n#include \"IntSize.h\"\n#include \"KURL.h\"\n#include \"MediaPlayer.h\"\n#include \"NotImplemented.h\"\n#include \"TimeRanges.h\"\n\n#include \"WebCanvas.h\"\n#include \"WebCString.h\"\n#include \"WebFrameClient.h\"\n#include \"WebFrameImpl.h\"\n#include \"WebKit.h\"\n#include \"WebKitClient.h\"\n#include \"WebMediaPlayer.h\"\n#include \"WebMimeRegistry.h\"\n#include \"WebRect.h\"\n#include \"WebSize.h\"\n#include \"WebString.h\"\n#include \"WebURL.h\"\n\n#include \n\nusing namespace WebCore;\n\nnamespace WebKit {\n\nstatic WebMediaPlayer* createWebMediaPlayer(\n WebMediaPlayerClient* client, Frame* frame)\n{\n WebFrameImpl* webFrame = WebFrameImpl::fromFrame(frame);\n if (!webFrame->client())\n return 0;\n return webFrame->client()->createMediaPlayer(webFrame, client);\n}\n\nbool WebMediaPlayerClientImpl::m_isEnabled = false;\n\nbool WebMediaPlayerClientImpl::isEnabled()\n{\n return m_isEnabled;\n}\n\nvoid WebMediaPlayerClientImpl::setIsEnabled(bool isEnabled)\n{\n m_isEnabled = isEnabled;\n}\n\nvoid WebMediaPlayerClientImpl::registerSelf(MediaEngineRegistrar registrar)\n{\n if (m_isEnabled) {\n registrar(WebMediaPlayerClientImpl::create,\n WebMediaPlayerClientImpl::getSupportedTypes,\n WebMediaPlayerClientImpl::supportsType);\n }\n}\n\n\/\/ WebMediaPlayerClient --------------------------------------------------------\n\nvoid WebMediaPlayerClientImpl::networkStateChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->networkStateChanged();\n}\n\nvoid WebMediaPlayerClientImpl::readyStateChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->readyStateChanged();\n}\n\nvoid WebMediaPlayerClientImpl::volumeChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->volumeChanged();\n}\n\nvoid WebMediaPlayerClientImpl::timeChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->timeChanged();\n}\n\nvoid WebMediaPlayerClientImpl::repaint()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->repaint();\n}\n\nvoid WebMediaPlayerClientImpl::durationChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->durationChanged();\n}\n\nvoid WebMediaPlayerClientImpl::rateChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->rateChanged();\n}\n\nvoid WebMediaPlayerClientImpl::sizeChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->sizeChanged();\n}\n\nvoid WebMediaPlayerClientImpl::sawUnsupportedTracks()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->mediaPlayerClient()->mediaPlayerSawUnsupportedTracks(m_mediaPlayer);\n}\n\n\/\/ MediaPlayerPrivateInterface -------------------------------------------------\n\nvoid WebMediaPlayerClientImpl::load(const String& url)\n{\n Frame* frame = static_cast(\n m_mediaPlayer->mediaPlayerClient())->document()->frame();\n m_webMediaPlayer.set(createWebMediaPlayer(this, frame));\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->load(KURL(ParsedURLString, url));\n}\n\nvoid WebMediaPlayerClientImpl::cancelLoad()\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->cancelLoad();\n}\n\nvoid WebMediaPlayerClientImpl::play()\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->play();\n}\n\nvoid WebMediaPlayerClientImpl::pause()\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->pause();\n}\n\nIntSize WebMediaPlayerClientImpl::naturalSize() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->naturalSize();\n return IntSize();\n}\n\nbool WebMediaPlayerClientImpl::hasVideo() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->hasVideo();\n return false;\n}\n\nbool WebMediaPlayerClientImpl::hasAudio() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->hasAudio();\n return false;\n}\n\nvoid WebMediaPlayerClientImpl::setVisible(bool visible)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setVisible(visible);\n}\n\nfloat WebMediaPlayerClientImpl::duration() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->duration();\n return 0.0f;\n}\n\nfloat WebMediaPlayerClientImpl::currentTime() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->currentTime();\n return 0.0f;\n}\n\nvoid WebMediaPlayerClientImpl::seek(float time)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->seek(time);\n}\n\nbool WebMediaPlayerClientImpl::seeking() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->seeking();\n return false;\n}\n\nvoid WebMediaPlayerClientImpl::setEndTime(float time)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setEndTime(time);\n}\n\nvoid WebMediaPlayerClientImpl::setRate(float rate)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setRate(rate);\n}\n\nbool WebMediaPlayerClientImpl::paused() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->paused();\n return false;\n}\n\nbool WebMediaPlayerClientImpl::supportsFullscreen() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->supportsFullscreen();\n return false;\n}\n\nbool WebMediaPlayerClientImpl::supportsSave() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->supportsSave();\n return false;\n}\n\nvoid WebMediaPlayerClientImpl::setVolume(float volume)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setVolume(volume);\n}\n\nMediaPlayer::NetworkState WebMediaPlayerClientImpl::networkState() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->networkState());\n return MediaPlayer::Empty;\n}\n\nMediaPlayer::ReadyState WebMediaPlayerClientImpl::readyState() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->readyState());\n return MediaPlayer::HaveNothing;\n}\n\nfloat WebMediaPlayerClientImpl::maxTimeSeekable() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->maxTimeSeekable();\n return 0.0f;\n}\n\nPassRefPtr WebMediaPlayerClientImpl::buffered() const\n{\n if (m_webMediaPlayer.get()) {\n const WebTimeRanges& webRanges = m_webMediaPlayer->buffered();\n\n \/\/ FIXME: Save the time ranges in a member variable and update it when needed.\n RefPtr ranges = TimeRanges::create();\n for (size_t i = 0; i < webRanges.size(); ++i)\n ranges->add(webRanges[i].start, webRanges[i].end);\n return ranges.release();\n }\n return TimeRanges::create();\n}\n\nint WebMediaPlayerClientImpl::dataRate() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->dataRate();\n return 0;\n}\n\nbool WebMediaPlayerClientImpl::totalBytesKnown() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->totalBytesKnown();\n return false;\n}\n\nunsigned WebMediaPlayerClientImpl::totalBytes() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->totalBytes());\n return 0;\n}\n\nunsigned WebMediaPlayerClientImpl::bytesLoaded() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->bytesLoaded());\n return 0;\n}\n\nvoid WebMediaPlayerClientImpl::setSize(const IntSize& size)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setSize(WebSize(size.width(), size.height()));\n}\n\nvoid WebMediaPlayerClientImpl::paint(GraphicsContext* context, const IntRect& rect)\n{\n \/\/ Normally GraphicsContext operations do nothing when painting is disabled.\n \/\/ Since we're accessing platformContext() directly we have to manually\n \/\/ check.\n if (m_webMediaPlayer.get() && !context->paintingDisabled()) {\n#if WEBKIT_USING_SKIA\n m_webMediaPlayer->paint(context->platformContext()->canvas(), rect);\n#elif WEBKIT_USING_CG\n m_webMediaPlayer->paint(context->platformContext(), rect);\n#else\n notImplemented();\n#endif\n }\n}\n\nvoid WebMediaPlayerClientImpl::setAutobuffer(bool autoBuffer)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setAutoBuffer(autoBuffer);\n}\n\nbool WebMediaPlayerClientImpl::hasSingleSecurityOrigin() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->hasSingleSecurityOrigin();\n return false;\n}\n\nMediaPlayer::MovieLoadType WebMediaPlayerClientImpl::movieLoadType() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(\n m_webMediaPlayer->movieLoadType());\n return MediaPlayer::Unknown;\n}\n\nMediaPlayerPrivateInterface* WebMediaPlayerClientImpl::create(MediaPlayer* player)\n{\n WebMediaPlayerClientImpl* client = new WebMediaPlayerClientImpl();\n client->m_mediaPlayer = player;\n return client;\n}\n\nvoid WebMediaPlayerClientImpl::getSupportedTypes(HashSet& supportedTypes)\n{\n \/\/ FIXME: integrate this list with WebMediaPlayerClientImpl::supportsType.\n notImplemented();\n}\n\nMediaPlayer::SupportsType WebMediaPlayerClientImpl::supportsType(const String& type,\n const String& codecs)\n{\n WebMimeRegistry::SupportsType supportsType =\n webKitClient()->mimeRegistry()->supportsMediaMIMEType(type, codecs);\n\n switch (supportsType) {\n default:\n ASSERT_NOT_REACHED();\n case WebMimeRegistry::IsNotSupported:\n return MediaPlayer::IsNotSupported;\n case WebMimeRegistry::IsSupported:\n return MediaPlayer::IsSupported;\n case WebMimeRegistry::MayBeSupported:\n return MediaPlayer::MayBeSupported;\n }\n return MediaPlayer::IsNotSupported;\n}\n\nWebMediaPlayerClientImpl::WebMediaPlayerClientImpl()\n : m_mediaPlayer(0)\n{\n}\n\n} \/\/ namespace WebKit\n\n#endif \/\/ ENABLE(VIDEO)\nAnother attempt at the build fix. TEST=None BUG=None\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"WebMediaPlayerClientImpl.h\"\n\n#if ENABLE(VIDEO)\n\n#include \"CString.h\"\n#include \"Frame.h\"\n#include \"GraphicsContext.h\"\n#include \"HTMLMediaElement.h\"\n#include \"IntSize.h\"\n#include \"KURL.h\"\n#include \"MediaPlayer.h\"\n#include \"NotImplemented.h\"\n#include \"TimeRanges.h\"\n\n#include \"WebCanvas.h\"\n#include \"WebCString.h\"\n#include \"WebFrameClient.h\"\n#include \"WebFrameImpl.h\"\n#include \"WebKit.h\"\n#include \"WebKitClient.h\"\n#include \"WebMediaPlayer.h\"\n#include \"WebMimeRegistry.h\"\n#include \"WebRect.h\"\n#include \"WebSize.h\"\n#include \"WebString.h\"\n#include \"WebURL.h\"\n\n\/\/ WebCommon.h defines WEBKIT_USING_SKIA so this has to be included last.\n#if WEBKIT_USING_SKIA\n#include \"PlatformContextSkia.h\"\n#endif\n\n#include \n\nusing namespace WebCore;\n\nnamespace WebKit {\n\nstatic WebMediaPlayer* createWebMediaPlayer(\n WebMediaPlayerClient* client, Frame* frame)\n{\n WebFrameImpl* webFrame = WebFrameImpl::fromFrame(frame);\n if (!webFrame->client())\n return 0;\n return webFrame->client()->createMediaPlayer(webFrame, client);\n}\n\nbool WebMediaPlayerClientImpl::m_isEnabled = false;\n\nbool WebMediaPlayerClientImpl::isEnabled()\n{\n return m_isEnabled;\n}\n\nvoid WebMediaPlayerClientImpl::setIsEnabled(bool isEnabled)\n{\n m_isEnabled = isEnabled;\n}\n\nvoid WebMediaPlayerClientImpl::registerSelf(MediaEngineRegistrar registrar)\n{\n if (m_isEnabled) {\n registrar(WebMediaPlayerClientImpl::create,\n WebMediaPlayerClientImpl::getSupportedTypes,\n WebMediaPlayerClientImpl::supportsType);\n }\n}\n\n\/\/ WebMediaPlayerClient --------------------------------------------------------\n\nvoid WebMediaPlayerClientImpl::networkStateChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->networkStateChanged();\n}\n\nvoid WebMediaPlayerClientImpl::readyStateChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->readyStateChanged();\n}\n\nvoid WebMediaPlayerClientImpl::volumeChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->volumeChanged();\n}\n\nvoid WebMediaPlayerClientImpl::timeChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->timeChanged();\n}\n\nvoid WebMediaPlayerClientImpl::repaint()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->repaint();\n}\n\nvoid WebMediaPlayerClientImpl::durationChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->durationChanged();\n}\n\nvoid WebMediaPlayerClientImpl::rateChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->rateChanged();\n}\n\nvoid WebMediaPlayerClientImpl::sizeChanged()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->sizeChanged();\n}\n\nvoid WebMediaPlayerClientImpl::sawUnsupportedTracks()\n{\n ASSERT(m_mediaPlayer);\n m_mediaPlayer->mediaPlayerClient()->mediaPlayerSawUnsupportedTracks(m_mediaPlayer);\n}\n\n\/\/ MediaPlayerPrivateInterface -------------------------------------------------\n\nvoid WebMediaPlayerClientImpl::load(const String& url)\n{\n Frame* frame = static_cast(\n m_mediaPlayer->mediaPlayerClient())->document()->frame();\n m_webMediaPlayer.set(createWebMediaPlayer(this, frame));\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->load(KURL(ParsedURLString, url));\n}\n\nvoid WebMediaPlayerClientImpl::cancelLoad()\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->cancelLoad();\n}\n\nvoid WebMediaPlayerClientImpl::play()\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->play();\n}\n\nvoid WebMediaPlayerClientImpl::pause()\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->pause();\n}\n\nIntSize WebMediaPlayerClientImpl::naturalSize() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->naturalSize();\n return IntSize();\n}\n\nbool WebMediaPlayerClientImpl::hasVideo() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->hasVideo();\n return false;\n}\n\nbool WebMediaPlayerClientImpl::hasAudio() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->hasAudio();\n return false;\n}\n\nvoid WebMediaPlayerClientImpl::setVisible(bool visible)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setVisible(visible);\n}\n\nfloat WebMediaPlayerClientImpl::duration() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->duration();\n return 0.0f;\n}\n\nfloat WebMediaPlayerClientImpl::currentTime() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->currentTime();\n return 0.0f;\n}\n\nvoid WebMediaPlayerClientImpl::seek(float time)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->seek(time);\n}\n\nbool WebMediaPlayerClientImpl::seeking() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->seeking();\n return false;\n}\n\nvoid WebMediaPlayerClientImpl::setEndTime(float time)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setEndTime(time);\n}\n\nvoid WebMediaPlayerClientImpl::setRate(float rate)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setRate(rate);\n}\n\nbool WebMediaPlayerClientImpl::paused() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->paused();\n return false;\n}\n\nbool WebMediaPlayerClientImpl::supportsFullscreen() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->supportsFullscreen();\n return false;\n}\n\nbool WebMediaPlayerClientImpl::supportsSave() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->supportsSave();\n return false;\n}\n\nvoid WebMediaPlayerClientImpl::setVolume(float volume)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setVolume(volume);\n}\n\nMediaPlayer::NetworkState WebMediaPlayerClientImpl::networkState() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->networkState());\n return MediaPlayer::Empty;\n}\n\nMediaPlayer::ReadyState WebMediaPlayerClientImpl::readyState() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->readyState());\n return MediaPlayer::HaveNothing;\n}\n\nfloat WebMediaPlayerClientImpl::maxTimeSeekable() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->maxTimeSeekable();\n return 0.0f;\n}\n\nPassRefPtr WebMediaPlayerClientImpl::buffered() const\n{\n if (m_webMediaPlayer.get()) {\n const WebTimeRanges& webRanges = m_webMediaPlayer->buffered();\n\n \/\/ FIXME: Save the time ranges in a member variable and update it when needed.\n RefPtr ranges = TimeRanges::create();\n for (size_t i = 0; i < webRanges.size(); ++i)\n ranges->add(webRanges[i].start, webRanges[i].end);\n return ranges.release();\n }\n return TimeRanges::create();\n}\n\nint WebMediaPlayerClientImpl::dataRate() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->dataRate();\n return 0;\n}\n\nbool WebMediaPlayerClientImpl::totalBytesKnown() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->totalBytesKnown();\n return false;\n}\n\nunsigned WebMediaPlayerClientImpl::totalBytes() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->totalBytes());\n return 0;\n}\n\nunsigned WebMediaPlayerClientImpl::bytesLoaded() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(m_webMediaPlayer->bytesLoaded());\n return 0;\n}\n\nvoid WebMediaPlayerClientImpl::setSize(const IntSize& size)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setSize(WebSize(size.width(), size.height()));\n}\n\nvoid WebMediaPlayerClientImpl::paint(GraphicsContext* context, const IntRect& rect)\n{\n \/\/ Normally GraphicsContext operations do nothing when painting is disabled.\n \/\/ Since we're accessing platformContext() directly we have to manually\n \/\/ check.\n if (m_webMediaPlayer.get() && !context->paintingDisabled()) {\n#if WEBKIT_USING_SKIA\n m_webMediaPlayer->paint(context->platformContext()->canvas(), rect);\n#elif WEBKIT_USING_CG\n m_webMediaPlayer->paint(context->platformContext(), rect);\n#else\n notImplemented();\n#endif\n }\n}\n\nvoid WebMediaPlayerClientImpl::setAutobuffer(bool autoBuffer)\n{\n if (m_webMediaPlayer.get())\n m_webMediaPlayer->setAutoBuffer(autoBuffer);\n}\n\nbool WebMediaPlayerClientImpl::hasSingleSecurityOrigin() const\n{\n if (m_webMediaPlayer.get())\n return m_webMediaPlayer->hasSingleSecurityOrigin();\n return false;\n}\n\nMediaPlayer::MovieLoadType WebMediaPlayerClientImpl::movieLoadType() const\n{\n if (m_webMediaPlayer.get())\n return static_cast(\n m_webMediaPlayer->movieLoadType());\n return MediaPlayer::Unknown;\n}\n\nMediaPlayerPrivateInterface* WebMediaPlayerClientImpl::create(MediaPlayer* player)\n{\n WebMediaPlayerClientImpl* client = new WebMediaPlayerClientImpl();\n client->m_mediaPlayer = player;\n return client;\n}\n\nvoid WebMediaPlayerClientImpl::getSupportedTypes(HashSet& supportedTypes)\n{\n \/\/ FIXME: integrate this list with WebMediaPlayerClientImpl::supportsType.\n notImplemented();\n}\n\nMediaPlayer::SupportsType WebMediaPlayerClientImpl::supportsType(const String& type,\n const String& codecs)\n{\n WebMimeRegistry::SupportsType supportsType =\n webKitClient()->mimeRegistry()->supportsMediaMIMEType(type, codecs);\n\n switch (supportsType) {\n default:\n ASSERT_NOT_REACHED();\n case WebMimeRegistry::IsNotSupported:\n return MediaPlayer::IsNotSupported;\n case WebMimeRegistry::IsSupported:\n return MediaPlayer::IsSupported;\n case WebMimeRegistry::MayBeSupported:\n return MediaPlayer::MayBeSupported;\n }\n return MediaPlayer::IsNotSupported;\n}\n\nWebMediaPlayerClientImpl::WebMediaPlayerClientImpl()\n : m_mediaPlayer(0)\n{\n}\n\n} \/\/ namespace WebKit\n\n#endif \/\/ ENABLE(VIDEO)\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"ssvm_pre.h\"\n#include \"sslang_vm.h\"\n#include \"ssvm.h\"\n\nextern Script g_Script;\n\nint LoadScript(char* filename)\n{\n\tFILE* pScriptFile = fopen(filename, \"rb\");\n\tif (pScriptFile == NULL)\n\t\treturn LOAD_ERROR_FAIL_FILE_OPEN;\n\n\tchar* magicNumStr = (char*) malloc(5);\n\tfread(magicNumStr, 4, 1, pScriptFile);\n\tmagicNumStr[strlen(SSE_ID_STRING)] = '\\0';\n\n\tif (strcmp(magicNumStr, SSE_ID_STRING) != 0)\n\t\treturn LOAD_ERROR_INVALID_SSE;\n\n\tfree(magicNumStr);\n\n\tint majorVersion = 0;\n\tint minorVersion = 0;\n\n\tfread(&majorVersion, 1, 1, pScriptFile);\n\tfread(&minorVersion, 1, 1, pScriptFile);\n\n\tif (majorVersion != VERSION_MAJOR || minorVersion != VERSION_MINOR)\n\t\treturn LOAD_ERROR_UNSOPPORTED_VERSION;\n\n\tfread(&g_Script.stack.iSize, 4, 1, pScriptFile);\n\tif (g_Script.stack.iSize == 0)\n\t\tg_Script.stack.iSize = DEFAULT_STACK_SIZE;\n\n\tg_Script.stack.pElement = (Value*) malloc(g_Script.stack.iSize * sizeof(Value));\n\n\tfread(&g_Script.iGlobalDataSize, 4, 1, pScriptFile);\n\tfread(&g_Script.iIsMainFuncExist, 1, 1, pScriptFile);\n\tfread(&g_Script.iMainFuncIndex, 4, 1, pScriptFile);\n\n\tfread(&g_Script.instrStream.iSize, 4, 1, pScriptFile);\n\tg_Script.instrStream.pInstr = (Instr*) malloc(g_Script.instrStream.iSize * sizeof(Instr));\n\n\tfor (int i = 0; i < g_Script.instrStream.iSize; i++)\n\t{\n\t\tg_Script.instrStream.pInstr[i].iOpcode = 0;\n\t\tfread(&g_Script.instrStream.pInstr[i].iOpcode, 2, 1, pScriptFile);\n\t\tg_Script.instrStream.pInstr[i].iOpCount = 0;\n\t\tfread(&g_Script.instrStream.pInstr[i].iOpCount, 1, 1, pScriptFile);\n\n\t\tint opCount = g_Script.instrStream.pInstr[i].iOpCount;\n\n\t\tValue* pOplist = (Value*) malloc(opCount * sizeof(Value));\n\n\t\tfor (int j = 0; j < opCount; j++)\n\t\t{\n\t\t\tpOplist[j].iType = 0;\n\t\t\tfread(&pOplist[j].iType, 1, 1, pScriptFile);\n\n\t\t\tswitch (pOplist[j].iType)\n\t\t\t{\n\t\t\tcase OP_TYPE_INT:\n\t\t\t\tfread(&pOplist[j].iIntLiteral, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_FLOAT:\n\t\t\t\tfread(&pOplist[j].fFloatLiteral, sizeof(float), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_STRING_INDEX:\n\t\t\t\tfread(&pOplist[j].iIntLiteral, sizeof(int), 1, pScriptFile);\n\t\t\t\tpOplist[j].iType = OP_TYPE_STRING_INDEX;\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_INSTR_INDEX:\n\t\t\t\tfread(&pOplist[j].iInstrIndex, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_ABS_STACK_INDEX:\n\t\t\t\tfread(&pOplist[j].iStackIndex, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_REL_STACK_INDEX:\n\t\t\t\tfread(&pOplist[j].iStackIndex, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_FUNC_INDEX:\n\t\t\t\tfread(&pOplist[j].iOffsetIndex, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_HOST_API_CALL_INDEX:\n\t\t\t\tfread(&pOplist[j].iHostAPICallIndex, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_REG:\n\t\t\t\tfread(&pOplist[j].iReg, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tg_Script.instrStream.pInstr[i].pOplist = pOplist;\n\t}\n\n\tint stringTableSize;\n\tfread(&stringTableSize, 4, 1, pScriptFile);\n\tif (stringTableSize)\n\t{\n\t\tchar** ppStringTable = (char**) malloc(stringTableSize * sizeof(char*));\n\t\tfor (int i = 0; i < stringTableSize; i++)\n\t\t{\n\t\t\tint stringLen = 0;\n\t\t\tfread(&stringLen, sizeof(int), 1, pScriptFile);\n\n\t\t\tchar* pString = (char*) malloc((stringLen + 1) * sizeof(char));\n\t\t\tfread(pString, stringLen, 1, pScriptFile);\n\t\t\tpString[stringLen] = '\\0';\n\n\t\t\tppStringTable[i] = pString;\n\t\t}\n\n\t\tfor (int i = 0; i < g_Script.instrStream.iSize; i++)\n\t\t{\n\t\t\tint opCount = g_Script.instrStream.pInstr[i].iOpCount; \n\t\t\tValue* opList = g_Script.instrStream.pInstr[i].pOplist;\n\t\t\tfor (int j = 0; j < opCount; j++)\n\t\t\t{\n\t\t\t\tif (opList[j].iType == OP_TYPE_STRING_INDEX)\n\t\t\t\t{\n\t\t\t\t\tint stringIndex = opList[j].iIntLiteral;\n\t\t\t\t\tchar* temp = (char*) malloc(strlen(ppStringTable[stringIndex] + 1));\n\t\t\t\t\tstrcpy(temp, ppStringTable[stringIndex]);\n\n\t\t\t\t\topList[j].strStringLiteral = temp;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i < stringTableSize; i++)\n\t\t\tfree(ppStringTable[i]);\n\t\tfree(ppStringTable);\n\t}\n\t\n\tint functionTableSize;\n\tfread(&functionTableSize, 4, 1, pScriptFile);\n\tg_Script.pFuncTable = (Func*) malloc(functionTableSize * sizeof(Func));\n\tfor (int i = 0; i < functionTableSize; i++)\n\t{\n\t\tint entryPoint;\n\t\tfread(&entryPoint, 4, 1, pScriptFile);\n\n\t\tint paramCount = 0;\n\t\tfread(¶mCount, 1, 1, pScriptFile);\n\n\t\tint localDataSize;\n\t\tfread(&localDataSize, 4, 1, pScriptFile);\n\n\t\tint stackFrameSize = paramCount + 1 + localDataSize;\n\n\t\tg_Script.pFuncTable[i].iEntryPoint = entryPoint;\n\t\tg_Script.pFuncTable[i].iParamCount = paramCount;\n\t\tg_Script.pFuncTable[i].iLocalDataSize = localDataSize;\n\t\tg_Script.pFuncTable[i].iStackFrameSize = stackFrameSize;\n\t}\n\n\tfread(&g_Script.hostAPICallTable.iSize, 4, 1, pScriptFile);\n\tg_Script.hostAPICallTable.ppStrCalls = (char**) malloc(g_Script.hostAPICallTable.iSize * sizeof(char*));\n\tfor (int i = 0; i < g_Script.hostAPICallTable.iSize; i++)\n\t{\n\t\tint callLength = 0;\n\t\tfread(&callLength, 1, 1, pScriptFile);\n\n\t\tchar* pAPICall = (char*) malloc(callLength + 1);\n\t\tfread(pAPICall, callLength, 1, pScriptFile);\n\t\tpAPICall[callLength] = '\\0';\n\n\t\tg_Script.hostAPICallTable.ppStrCalls[i] = pAPICall;\n\t}\n\n\n\tfclose(pScriptFile);\n\n\treturn LOAD_OK;\n}\n\nvoid ResetScript()\n{\n\t\n}\n\nvoid RunScript()\n{\n\tint isExitExeLoop = FALSE;\n\twhile (TRUE)\n\t{\n\t\tif (g_Script.iIsPaused)\n\t\t{\n\t\t\t\/*if (GetCurrentTime() >= g_Script.iPauseEndTime)\n\t\t\tg_Script.iIsPaused = FALSE;\n\t\t\telse\n\t\t\tcontinue;*\/\n\t\t}\n\n\t\tint currentInstr = g_Script.instrStream.iCurrentInstr;\n\t\tint opCode = g_Script.instrStream.pInstr[currentInstr].iOpcode;\n\n\t\tprintf(\"\\t\");\n\t\tif (opCode < 10)\n\t\t\tprintf(\" %d\", opCode);\n\t\telse\n\t\t\tprintf(\"%d\", opCode);\n\t\tprintf(\" %s\", \"dd\");\n\n\t\tswitch (opCode)\n\t\t{\n\t\tcase INSTR_MOV:\n\n\t\tcase INSTR_ADD:\n\t\tcase INSTR_SUB:\n\t\tcase INSTR_MUL:\n\t\tcase INSTR_DIV:\n\t\tcase INSTR_MOD:\n\t\tcase INSTR_EXP:\n\n\t\tcase INSTR_AND:\n\t\tcase INSTR_OR:\n\t\tcase INSTR_XOR:\n\t\tcase INSTR_SHL:\n\t\tcase INSTR_SHR:\n\t\t\t{\n\t\t\t\tValue dest = GetOpValue(0);\n\t\t\t\tValue source = GetOpValue(1);\n\n\t\t\t\tswitch (opCode)\n\t\t\t\t{\n\t\t\t\tcase INSTR_MOV:\n\t\t\t\t\tif (GetOpValuePointer(0) == GetOpValuePointer(1))\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tCopyValue(&dest, source);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase INSTR_ADD:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral += GetOpValueAsInt(1);\n\t\t\t\t\telse\n\t\t\t\t\t\tdest.fFloatLiteral += GetOpValueAsFloat(1);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase INSTR_SUB:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral -= GetOpValueAsInt(1);\n\t\t\t\t\telse\n\t\t\t\t\t\tdest.fFloatLiteral -= GetOpValueAsFloat(1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase INSTR_MUL:\n\t\t\t\tcase INSTR_DIV:\n\t\t\t\tcase INSTR_MOD:\n\t\t\t\tcase INSTR_EXP:\n\n\t\t\t\tcase INSTR_AND:\n\t\t\t\tcase INSTR_OR:\n\t\t\t\tcase INSTR_XOR:\n\t\t\t\tcase INSTR_SHL:\n\t\t\t\tcase INSTR_SHR:\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\n\");\n\n\t\tif (currentInstr == g_Script.instrStream.iCurrentInstr)\n\t\t\tg_Script.instrStream.iCurrentInstr++;\n\n\t\tif (isExitExeLoop)\n\t\t\tbreak;\n\t}\n\t\n}\n\nvoid CopyValue(Value* dest, Value value)\n{\n\t*dest = value;\n}\n\nint ValueToInt(Value value)\n{\n\tswitch (value.iType)\n\t{\n\tcase OP_TYPE_INT:\n\t\treturn value.iIntLiteral;\n\tcase OP_TYPE_FLOAT:\n\t\treturn (int)value.fFloatLiteral;\n\tcase OP_TYPE_STRING_INDEX:\n\t\treturn atoi(value.strStringLiteral);\n\tdefault:\n\t\treturn 0;\n\t}\n}\n\nfloat ValueToFloat(Value value)\n{\n\tswitch (value.iType)\n\t{\n\tcase OP_TYPE_INT:\n\t\treturn (float) value.iIntLiteral;\n\tcase OP_TYPE_FLOAT:\n\t\treturn value.fFloatLiteral;\n\tcase OP_TYPE_STRING_INDEX:\n\t\treturn atof(value.strStringLiteral);\n\tdefault:\n\t\treturn 0;\n\t}\n}\n\nchar* ValueToString(Value value)\n{\n\tchar* str = NULL;\n\tif (value.iType != OP_TYPE_STRING_INDEX)\n\t\tstr = (char*) malloc(MAX_VALUE_STRING_SIZE + 1);\n\n\tswitch (value.iType)\n\t{\n\tcase OP_TYPE_INT:\n\t\t_itoa(value.iIntLiteral, str, 10);\n\t\treturn str;\n\tcase OP_TYPE_FLOAT:\n\t\tsprintf(str, \"%f\", value.fFloatLiteral);\n\t\treturn str;\n\tcase OP_TYPE_STRING_INDEX:\n\t\treturn value.strStringLiteral;\n\tdefault:\n\t\treturn NULL;\n\t}\n}\n\nValue GetStackValue(int index)\n{\n\treturn g_Script.stack.pElement[GET_STACK_INDEX(index)];\n}\n\nint GetOpType(int opIndex);\nValue GetOpValue(int opIndex)\n{\n\tint currentInstr = g_Script.instrStream.iCurrentInstr;\n\tValue opValue = g_Script.instrStream.pInstr[currentInstr].pOplist[opIndex];\n\n\tswitch (opValue.iType)\n\t{\n\t\t\n\t\n\t}\n\treturn opValue;\n}\nValue* GetOpValuePointer(int opIndex)\n{\n\treturn NULL;\n}\nint GetOpValueAsInt(int opIndex)\n{\n\treturn 0;\n}\nfloat GetOpValueAsFloat(int opIndex)\n{\n\treturn 0;\n}\nchar* GetOpValueAsString(int opIndex)\n{\n\treturn 0;\n}\nint GetOpValueAsStackIndex(int opIndex)\n{\n\tint currentInstr = g_Script.instrStream.iCurrentInstr;\n\tValue opValue = g_Script.instrStream.pInstr[currentInstr].pOplist[opIndex];\n\n\tswitch (opValue.iType)\n\t{\n\tcase OP_TYPE_ABS_STACK_INDEX:\n\t\treturn opValue.iStackIndex;\n\tcase OP_TYPE_REL_STACK_INDEX:\n\t\tbreak;\n\n\n\t}\n\treturn 0;\n}\nint GetOpValueAsInstrIndex(int opIndex)\n{\n\treturn 0;\n}\nint GetOpValueAsFuncIndex(int opIndex)\n{\n\treturn 0;\n}\nchar* GetOpValueASHostAPI(int opIndex)\n{\n\treturn NULL;\n}instr resolve#include \n#include \n#include \n#include \n\n#include \"ssvm_pre.h\"\n#include \"sslang_vm.h\"\n#include \"ssvm.h\"\n\nextern Script g_Script;\n\nint LoadScript(char* filename)\n{\n\tFILE* pScriptFile = fopen(filename, \"rb\");\n\tif (pScriptFile == NULL)\n\t\treturn LOAD_ERROR_FAIL_FILE_OPEN;\n\n\tchar* magicNumStr = (char*) malloc(5);\n\tfread(magicNumStr, 4, 1, pScriptFile);\n\tmagicNumStr[strlen(SSE_ID_STRING)] = '\\0';\n\n\tif (strcmp(magicNumStr, SSE_ID_STRING) != 0)\n\t\treturn LOAD_ERROR_INVALID_SSE;\n\n\tfree(magicNumStr);\n\n\tint majorVersion = 0;\n\tint minorVersion = 0;\n\n\tfread(&majorVersion, 1, 1, pScriptFile);\n\tfread(&minorVersion, 1, 1, pScriptFile);\n\n\tif (majorVersion != VERSION_MAJOR || minorVersion != VERSION_MINOR)\n\t\treturn LOAD_ERROR_UNSOPPORTED_VERSION;\n\n\tfread(&g_Script.stack.iSize, 4, 1, pScriptFile);\n\tif (g_Script.stack.iSize == 0)\n\t\tg_Script.stack.iSize = DEFAULT_STACK_SIZE;\n\n\tg_Script.stack.pElement = (Value*) malloc(g_Script.stack.iSize * sizeof(Value));\n\n\tfread(&g_Script.iGlobalDataSize, 4, 1, pScriptFile);\n\tfread(&g_Script.iIsMainFuncExist, 1, 1, pScriptFile);\n\tfread(&g_Script.iMainFuncIndex, 4, 1, pScriptFile);\n\n\tfread(&g_Script.instrStream.iSize, 4, 1, pScriptFile);\n\tg_Script.instrStream.pInstr = (Instr*) malloc(g_Script.instrStream.iSize * sizeof(Instr));\n\n\tfor (int i = 0; i < g_Script.instrStream.iSize; i++)\n\t{\n\t\tg_Script.instrStream.pInstr[i].iOpcode = 0;\n\t\tfread(&g_Script.instrStream.pInstr[i].iOpcode, 2, 1, pScriptFile);\n\t\tg_Script.instrStream.pInstr[i].iOpCount = 0;\n\t\tfread(&g_Script.instrStream.pInstr[i].iOpCount, 1, 1, pScriptFile);\n\n\t\tint opCount = g_Script.instrStream.pInstr[i].iOpCount;\n\n\t\tValue* pOplist = (Value*) malloc(opCount * sizeof(Value));\n\n\t\tfor (int j = 0; j < opCount; j++)\n\t\t{\n\t\t\tpOplist[j].iType = 0;\n\t\t\tfread(&pOplist[j].iType, 1, 1, pScriptFile);\n\n\t\t\tswitch (pOplist[j].iType)\n\t\t\t{\n\t\t\tcase OP_TYPE_INT:\n\t\t\t\tfread(&pOplist[j].iIntLiteral, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_FLOAT:\n\t\t\t\tfread(&pOplist[j].fFloatLiteral, sizeof(float), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_STRING_INDEX:\n\t\t\t\tfread(&pOplist[j].iIntLiteral, sizeof(int), 1, pScriptFile);\n\t\t\t\tpOplist[j].iType = OP_TYPE_STRING_INDEX;\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_INSTR_INDEX:\n\t\t\t\tfread(&pOplist[j].iInstrIndex, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_ABS_STACK_INDEX:\n\t\t\t\tfread(&pOplist[j].iStackIndex, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_REL_STACK_INDEX:\n\t\t\t\tfread(&pOplist[j].iStackIndex, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_FUNC_INDEX:\n\t\t\t\tfread(&pOplist[j].iOffsetIndex, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_HOST_API_CALL_INDEX:\n\t\t\t\tfread(&pOplist[j].iHostAPICallIndex, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tcase OP_TYPE_REG:\n\t\t\t\tfread(&pOplist[j].iReg, sizeof(int), 1, pScriptFile);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tg_Script.instrStream.pInstr[i].pOplist = pOplist;\n\t}\n\n\tint stringTableSize;\n\tfread(&stringTableSize, 4, 1, pScriptFile);\n\tif (stringTableSize)\n\t{\n\t\tchar** ppStringTable = (char**) malloc(stringTableSize * sizeof(char*));\n\t\tfor (int i = 0; i < stringTableSize; i++)\n\t\t{\n\t\t\tint stringLen = 0;\n\t\t\tfread(&stringLen, sizeof(int), 1, pScriptFile);\n\n\t\t\tchar* pString = (char*) malloc((stringLen + 1) * sizeof(char));\n\t\t\tfread(pString, stringLen, 1, pScriptFile);\n\t\t\tpString[stringLen] = '\\0';\n\n\t\t\tppStringTable[i] = pString;\n\t\t}\n\n\t\tfor (int i = 0; i < g_Script.instrStream.iSize; i++)\n\t\t{\n\t\t\tint opCount = g_Script.instrStream.pInstr[i].iOpCount; \n\t\t\tValue* opList = g_Script.instrStream.pInstr[i].pOplist;\n\t\t\tfor (int j = 0; j < opCount; j++)\n\t\t\t{\n\t\t\t\tif (opList[j].iType == OP_TYPE_STRING_INDEX)\n\t\t\t\t{\n\t\t\t\t\tint stringIndex = opList[j].iIntLiteral;\n\t\t\t\t\tchar* temp = (char*) malloc(strlen(ppStringTable[stringIndex] + 1));\n\t\t\t\t\tstrcpy(temp, ppStringTable[stringIndex]);\n\n\t\t\t\t\topList[j].strStringLiteral = temp;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i < stringTableSize; i++)\n\t\t\tfree(ppStringTable[i]);\n\t\tfree(ppStringTable);\n\t}\n\t\n\tint functionTableSize;\n\tfread(&functionTableSize, 4, 1, pScriptFile);\n\tg_Script.pFuncTable = (Func*) malloc(functionTableSize * sizeof(Func));\n\tfor (int i = 0; i < functionTableSize; i++)\n\t{\n\t\tint entryPoint;\n\t\tfread(&entryPoint, 4, 1, pScriptFile);\n\n\t\tint paramCount = 0;\n\t\tfread(¶mCount, 1, 1, pScriptFile);\n\n\t\tint localDataSize;\n\t\tfread(&localDataSize, 4, 1, pScriptFile);\n\n\t\tint stackFrameSize = paramCount + 1 + localDataSize;\n\n\t\tg_Script.pFuncTable[i].iEntryPoint = entryPoint;\n\t\tg_Script.pFuncTable[i].iParamCount = paramCount;\n\t\tg_Script.pFuncTable[i].iLocalDataSize = localDataSize;\n\t\tg_Script.pFuncTable[i].iStackFrameSize = stackFrameSize;\n\t}\n\n\tfread(&g_Script.hostAPICallTable.iSize, 4, 1, pScriptFile);\n\tg_Script.hostAPICallTable.ppStrCalls = (char**) malloc(g_Script.hostAPICallTable.iSize * sizeof(char*));\n\tfor (int i = 0; i < g_Script.hostAPICallTable.iSize; i++)\n\t{\n\t\tint callLength = 0;\n\t\tfread(&callLength, 1, 1, pScriptFile);\n\n\t\tchar* pAPICall = (char*) malloc(callLength + 1);\n\t\tfread(pAPICall, callLength, 1, pScriptFile);\n\t\tpAPICall[callLength] = '\\0';\n\n\t\tg_Script.hostAPICallTable.ppStrCalls[i] = pAPICall;\n\t}\n\n\n\tfclose(pScriptFile);\n\n\treturn LOAD_OK;\n}\n\nvoid ResetScript()\n{\n\t\n}\n\nvoid RunScript()\n{\n\tint isExitExeLoop = FALSE;\n\twhile (TRUE)\n\t{\n\t\tif (g_Script.iIsPaused)\n\t\t{\n\t\t\t\/*if (GetCurrentTime() >= g_Script.iPauseEndTime)\n\t\t\tg_Script.iIsPaused = FALSE;\n\t\t\telse\n\t\t\tcontinue;*\/\n\t\t}\n\n\t\tint currentInstr = g_Script.instrStream.iCurrentInstr;\n\t\tint opCode = g_Script.instrStream.pInstr[currentInstr].iOpcode;\n\n\t\tprintf(\"\\t\");\n\t\tif (opCode < 10)\n\t\t\tprintf(\" %d\", opCode);\n\t\telse\n\t\t\tprintf(\"%d\", opCode);\n\t\tprintf(\" %s\", \"dd\");\n\n\t\tswitch (opCode)\n\t\t{\n\t\tcase INSTR_MOV:\n\n\t\tcase INSTR_ADD:\n\t\tcase INSTR_SUB:\n\t\tcase INSTR_MUL:\n\t\tcase INSTR_DIV:\n\t\tcase INSTR_MOD:\n\t\tcase INSTR_EXP:\n\n\t\tcase INSTR_AND:\n\t\tcase INSTR_OR:\n\t\tcase INSTR_XOR:\n\t\tcase INSTR_SHL:\n\t\tcase INSTR_SHR:\n\t\t\t{\n\t\t\t\tValue dest = GetOpValue(0);\n\t\t\t\tValue source = GetOpValue(1);\n\n\t\t\t\tswitch (opCode)\n\t\t\t\t{\n\t\t\t\tcase INSTR_MOV:\n\t\t\t\t\tif (GetOpValuePointer(0) == GetOpValuePointer(1))\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tCopyValue(&dest, source);\n\t\t\t\t\tbreak;\n\t\t\t\tcase INSTR_ADD:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral += GetOpValueAsInt(1);\n\t\t\t\t\telse\n\t\t\t\t\t\tdest.fFloatLiteral += GetOpValueAsFloat(1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase INSTR_SUB:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral -= GetOpValueAsInt(1);\n\t\t\t\t\telse\n\t\t\t\t\t\tdest.fFloatLiteral -= GetOpValueAsFloat(1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase INSTR_MUL:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral *= GetOpValueAsInt(1);\n\t\t\t\t\telse\n\t\t\t\t\t\tdest.fFloatLiteral *= GetOpValueAsFloat(1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase INSTR_DIV:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral \/= GetOpValueAsInt(1);\n\t\t\t\t\telse\n\t\t\t\t\t\tdest.fFloatLiteral \/= GetOpValueAsFloat(1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase INSTR_MOD:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral %= GetOpValueAsInt(1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase INSTR_EXP:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral = (int) pow((float)dest.iIntLiteral, GetOpValueAsInt(1));\n\t\t\t\t\telse\n\t\t\t\t\t\tdest.fFloatLiteral = (float) pow((float)dest.iIntLiteral, GetOpValueAsFloat(1));\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase INSTR_AND:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral &= GetOpValueAsInt(1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase INSTR_OR:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral |= GetOpValueAsInt(1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase INSTR_XOR:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral ^= GetOpValueAsInt(1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase INSTR_SHL:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral <<= GetOpValueAsInt(1);\n\t\t\t\t\tbreak;\n\t\t\t\tcase INSTR_SHR:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral >>= GetOpValueAsInt(1);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t*GetOpValuePointer(0) = dest;\n\t\t\t}\n\n\t\tcase INSTR_NEG:\n\t\tcase INSTR_NOT:\n\t\tcase INSTR_INC:\n\t\tcase INSTR_DEC:\n\t\t\t{\n\t\t\t\tValue dest = GetOpValue(0);\n\n\t\t\t\tswitch (opCode)\n\t\t\t\t{\n\t\t\t\tcase INSTR_NEG:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral = -dest.iIntLiteral;\n\t\t\t\t\telse\n\t\t\t\t\t\tdest.fFloatLiteral = -dest.fFloatLiteral;\n\t\t\t\t\tbreak;\n\t\t\t\tcase INSTR_NOT:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral = ~dest.iIntLiteral;\n\t\t\t\tcase INSTR_INC:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral++;\n\t\t\t\t\telse\n\t\t\t\t\t\tdest.fFloatLiteral++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase INSTR_DEC:\n\t\t\t\t\tif (dest.iType == OP_TYPE_INT)\n\t\t\t\t\t\tdest.iIntLiteral--;\n\t\t\t\t\telse\n\t\t\t\t\t\tdest.fFloatLiteral--;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t*GetOpValuePointer(0) = dest;\n\t\t\t}\n\n\t\tcase INSTR_CONCAT:\n\t\t\t{\n\t\t\t\tValue dest = GetOpValue(0);\n\n\t\t\t\tif (dest.iType != OP_TYPE_STRING_INDEX)\n\t\t\t\t\tbreak;\n\n\t\t\t\tchar* appendString = GetOpValueAsString(1);\n\t\t\t\tint newStringLength = strlen(dest.strStringLiteral) + strlen(appendString);\n\t\t\t\tchar* newString = (char*) malloc(newStringLength + 1);\n\n\t\t\t\tstrcpy(newString, dest.strStringLiteral);\n\t\t\t\tstrcat(newString, appendString);\n\n\t\t\t\t\/\/newString[newStringLength] = '\\0';\n\t\t\t\tfree(dest.strStringLiteral);\n\t\t\t\tdest.strStringLiteral = newString;\n\n\t\t\t\t*GetOpValuePointer(0) = dest;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tcase INSTR_GETCHAR:\n\t\t\t{\n\n\t\t\t}\n\n\t\tcase INSTR_SETCHAR:\n\t\t\t{\n\n\t\t\t}\n\n\t\tcase INSTR_JMP:\n\t\tcase INSTR_JE:\n\t\tcase INSTR_JNE:\n\t\tcase INSTR_JG:\n\t\tcase INSTR_JGE:\n\t\tcase INSTR_JL:\n\t\tcase INSTR_JLE:\n\n\t\tcase INSTR_PUSH:\n\t\tcase INSTR_POP:\n\n\t\tcase INSTR_CALL:\n\t\tcase INSTR_RET:\n\t\tcase INSTR_CALLHOST:\n\n\t\tcase INSTR_PAUSE:\n\t\tcase INSTR_EXIT:\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"\\n\");\n\n\t\tif (currentInstr == g_Script.instrStream.iCurrentInstr)\n\t\t\tg_Script.instrStream.iCurrentInstr++;\n\n\t\tif (isExitExeLoop)\n\t\t\tbreak;\n\t}\n\t\n}\n\nvoid CopyValue(Value* dest, Value value)\n{\n\t*dest = value;\n}\n\nint ValueToInt(Value value)\n{\n\tswitch (value.iType)\n\t{\n\tcase OP_TYPE_INT:\n\t\treturn value.iIntLiteral;\n\tcase OP_TYPE_FLOAT:\n\t\treturn (int)value.fFloatLiteral;\n\tcase OP_TYPE_STRING_INDEX:\n\t\treturn atoi(value.strStringLiteral);\n\tdefault:\n\t\treturn 0;\n\t}\n}\n\nfloat ValueToFloat(Value value)\n{\n\tswitch (value.iType)\n\t{\n\tcase OP_TYPE_INT:\n\t\treturn (float) value.iIntLiteral;\n\tcase OP_TYPE_FLOAT:\n\t\treturn value.fFloatLiteral;\n\tcase OP_TYPE_STRING_INDEX:\n\t\treturn atof(value.strStringLiteral);\n\tdefault:\n\t\treturn 0;\n\t}\n}\n\nchar* ValueToString(Value value)\n{\n\tchar* str = NULL;\n\tif (value.iType != OP_TYPE_STRING_INDEX)\n\t\tstr = (char*) malloc(MAX_VALUE_STRING_SIZE + 1);\n\n\tswitch (value.iType)\n\t{\n\tcase OP_TYPE_INT:\n\t\t_itoa(value.iIntLiteral, str, 10);\n\t\treturn str;\n\tcase OP_TYPE_FLOAT:\n\t\tsprintf(str, \"%f\", value.fFloatLiteral);\n\t\treturn str;\n\tcase OP_TYPE_STRING_INDEX:\n\t\treturn value.strStringLiteral;\n\tdefault:\n\t\treturn NULL;\n\t}\n}\n\nValue GetStackValue(int index)\n{\n\treturn g_Script.stack.pElement[GET_STACK_INDEX(index)];\n}\n\nint GetOpType(int opIndex);\nValue GetOpValue(int opIndex)\n{\n\tint currentInstr = g_Script.instrStream.iCurrentInstr;\n\tValue opValue = g_Script.instrStream.pInstr[currentInstr].pOplist[opIndex];\n\n\tswitch (opValue.iType)\n\t{\n\t\t\n\t\n\t}\n\treturn opValue;\n}\nValue* GetOpValuePointer(int opIndex)\n{\n\treturn NULL;\n}\nint GetOpValueAsInt(int opIndex)\n{\n\treturn 0;\n}\nfloat GetOpValueAsFloat(int opIndex)\n{\n\treturn 0;\n}\nchar* GetOpValueAsString(int opIndex)\n{\n\treturn 0;\n}\nint GetOpValueAsStackIndex(int opIndex)\n{\n\tint currentInstr = g_Script.instrStream.iCurrentInstr;\n\tValue opValue = g_Script.instrStream.pInstr[currentInstr].pOplist[opIndex];\n\n\tswitch (opValue.iType)\n\t{\n\tcase OP_TYPE_ABS_STACK_INDEX:\n\t\treturn opValue.iStackIndex;\n\tcase OP_TYPE_REL_STACK_INDEX:\n\t\tbreak;\n\n\n\t}\n\treturn 0;\n}\nint GetOpValueAsInstrIndex(int opIndex)\n{\n\treturn 0;\n}\nint GetOpValueAsFuncIndex(int opIndex)\n{\n\treturn 0;\n}\nchar* GetOpValueASHostAPI(int opIndex)\n{\n\treturn NULL;\n}<|endoftext|>"} {"text":"#ifndef PARTIAL_FP_LIST_HPP\n#define PARTIAL_FP_LIST_HPP\n\n\n#include \n#include \n#include \n\nNS_IZENELIB_IR_BEGIN\n\ntemplate<\n typename UNIT_TYPE = uint64_t,\n uint8_t FP_LENGTH = 6,\n uint64_t CACHE_SIZE = 600\n >\nclass PartialFpList\n{\n \npublic:\n typedef izenelib::am::IntegerDynArray FpVector;\n \n typedef izenelib::am::IntegerDynArray DocIDVector;\n\n typedef DocIDVector::size_t size_t;\n \n\nprivate:\n \n enum CACHE_STATUS \n {\n ADD_DOCS, UNIFORM_ACCESS\n }\n ;\n\n \n \n std::string file_name_;\n size_t doc_num_; \/\/reset();\n }\n in_mem_doc_num_ = 0;\n start_doc_i_ = doc_num_;\n }\n else\n {\n cache_status_ = UNIFORM_ACCESS;\n unload_fps();\n \/\/ for (uint8_t i =0; i= ALL_INFO_IN_MEM_LENGTH;\n }\n \n inline void unload_fps()\n {\n for (uint8_t i =0; ilength()==0)\n continue;\n\n \/\/std::cout<<\"unload seeking: \"<data(), fp_ptrs_[i]->size(), 1, fhandlers_[i])==1);\n fp_ptrs_[i]->compact();\n fp_ptrs_[i]->reset();\n }\n }\n\n inline void clean_fp()\n {\n \/\/std::cout<<\"clean_fp....\\n\";\n for (uint8_t i =0; i max_fps_size? max_fps_size: size;\n \n std::cout<array(size), size*sizeof(UNIT_TYPE), 1, fhandlers_[fpi])==1);\n }\n\n inline bool is_in_mem(uint8_t fpi, size_t n)\n {\n if (fp_ptrs_[fpi]!=NULL && n>=start_doc_i_ && n < start_doc_i_+fp_ptrs_[fpi]->length()\/UNIT_LEN)\n return true;\n \n return false;\n }\n \n \npublic:\n explicit PartialFpList(const char* file_name, uint8_t unit_len=2, size_t doc_num = 0)\n :file_name_(file_name),doc_num_(doc_num), in_mem_doc_num_(0),start_doc_i_(0),cache_status_(ADD_DOCS),\n ALL_INFO_IN_MEM_LENGTH(CACHE_SIZE*1000000\/(FP_LENGTH*sizeof(UNIT_TYPE))),\n UNIT_LEN(unit_len)\n , PARTIALS_SIZE((uint8_t)((double)FP_LENGTH\/UNIT_LEN+0.5)) \n {\n fp_ptrs_ = new FpVector*[PARTIALS_SIZE];\n fhandlers_ = new FILE*[PARTIALS_SIZE+1];\n clean_fp_ptr();\n \n static char num[8];\n \n for (uint8_t i =0; ipush_back(iilength()\/UNIT_LEN<<\") ------------------\\n\";\n for (size_t j=0; jlength(); j++)\n {\n std::cout<dupd memory leaking problem#ifndef PARTIAL_FP_LIST_HPP\n#define PARTIAL_FP_LIST_HPP\n\n\n#include \n#include \n#include \n\nNS_IZENELIB_IR_BEGIN\n\ntemplate<\n typename UNIT_TYPE = uint64_t,\n uint8_t FP_LENGTH = 6,\n uint64_t CACHE_SIZE = 600\n >\nclass PartialFpList\n{\n \npublic:\n typedef izenelib::am::IntegerDynArray FpVector;\n \n typedef izenelib::am::IntegerDynArray DocIDVector;\n\n typedef DocIDVector::size_t size_t;\n \n\nprivate:\n \n enum CACHE_STATUS \n {\n ADD_DOCS, UNIFORM_ACCESS\n }\n ;\n\n \n \n std::string file_name_;\n size_t doc_num_; \/\/reset();\n }\n in_mem_doc_num_ = 0;\n start_doc_i_ = doc_num_;\n }\n else\n {\n cache_status_ = UNIFORM_ACCESS;\n unload_fps();\n \/\/ for (uint8_t i =0; i= ALL_INFO_IN_MEM_LENGTH;\n }\n \n inline void unload_fps()\n {\n for (uint8_t i =0; ilength()==0)\n continue;\n\n \/\/std::cout<<\"unload seeking: \"<data(), fp_ptrs_[i]->size(), 1, fhandlers_[i])==1);\n fp_ptrs_[i]->compact();\n fp_ptrs_[i]->reset();\n }\n }\n\n inline void clean_fp()\n {\n \/\/std::cout<<\"clean_fp....\\n\";\n for (uint8_t i =0; i max_fps_size? max_fps_size: size;\n \n std::cout<array(size), size*sizeof(UNIT_TYPE), 1, fhandlers_[fpi])==1);\n }\n\n inline bool is_in_mem(uint8_t fpi, size_t n)\n {\n if (fp_ptrs_[fpi]!=NULL && n>=start_doc_i_ && n < start_doc_i_+fp_ptrs_[fpi]->length()\/UNIT_LEN)\n return true;\n \n return false;\n }\n \n \npublic:\n explicit PartialFpList(const char* file_name, uint8_t unit_len=2, size_t doc_num = 0)\n :file_name_(file_name),doc_num_(doc_num), in_mem_doc_num_(0),start_doc_i_(0),cache_status_(ADD_DOCS),\n ALL_INFO_IN_MEM_LENGTH(CACHE_SIZE*1000000\/(FP_LENGTH*sizeof(UNIT_TYPE))),\n UNIT_LEN(unit_len)\n , PARTIALS_SIZE((uint8_t)((double)FP_LENGTH\/UNIT_LEN+0.5)) \n {\n fp_ptrs_ = new FpVector*[PARTIALS_SIZE];\n fhandlers_ = new FILE*[PARTIALS_SIZE+1];\n clean_fp_ptr();\n \n static char num[8];\n \n for (uint8_t i =0; ipush_back(iilength()\/UNIT_LEN<<\") ------------------\\n\";\n for (size_t j=0; jlength(); j++)\n {\n std::cout<"} {"text":"\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include \n#include \n#include \"libtorrent\/entry.hpp\"\n#include \"libtorrent\/config.hpp\"\n\n#if defined(_MSC_VER)\nnamespace std\n{\n\tusing ::isprint;\n}\n#define for if (false) {} else for\n#endif\n\nnamespace\n{\n\ttemplate \n\tvoid call_destructor(T* o)\n\t{\n\t\tTORRENT_ASSERT(o);\n\t\to->~T();\n\t}\n\n\tstruct compare_string\n\t{\n\t\tcompare_string(char const* s): m_str(s) {}\n\t\n\t\tbool operator()(\n\t\t\tstd::pair const& e) const\n\t\t{\n\t\t\treturn m_str && e.first == m_str;\n\t\t}\n\t\tchar const* m_str;\n\t};\n}\n\nnamespace libtorrent\n{\n\tnamespace detail\n\t{\n\t\tTORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)\n\t\t{\n\t\t\tint sign = 0;\n\t\t\tif (val < 0)\n\t\t\t{\n\t\t\t\tsign = 1;\n\t\t\t\tval = -val;\n\t\t\t}\n\t\t\tbuf[--size] = '\\0';\n\t\t\tif (val == 0) buf[--size] = '0';\n\t\t\tfor (; size > sign && val != 0;)\n\t\t\t{\n\t\t\t\tbuf[--size] = '0' + char(val % 10);\n\t\t\t\tval \/= 10;\n\t\t\t}\n\t\t\tif (sign) buf[--size] = '-';\n\t\t\treturn buf + size;\n\t\t}\n\t}\n\n\tentry& entry::operator[](char const* key)\n\t{\n\t\tdictionary_type::iterator i = dict().find(key);\n\t\tif (i != dict().end()) return i->second;\n\t\tdictionary_type::iterator ret = dict().insert(\n\t\t\tdict().begin()\n\t\t\t, std::make_pair(std::string(key), entry()));\n\t\treturn ret->second;\n\t}\n\n\n\tentry& entry::operator[](std::string const& key)\n\t{\n\t\treturn (*this)[key.c_str()];\n\t}\n\n\tentry* entry::find_key(char const* key)\n\t{\n\t\tdictionary_type::iterator i = std::find_if(\n\t\t\tdict().begin()\n\t\t\t, dict().end()\n\t\t\t, compare_string(key));\n\t\tif (i == dict().end()) return 0;\n\t\treturn &i->second;\n\t\n\t}\n\n\tentry const* entry::find_key(char const* key) const\n\t{\n\t\tdictionary_type::const_iterator i = dict().find(key);\n\t\tif (i == dict().end()) return 0;\n\t\treturn &i->second;\n\t}\n\t\n#ifndef BOOST_NO_EXCEPTIONS\n\tconst entry& entry::operator[](char const* key) const\n\t{\n\t\tdictionary_type::const_iterator i = dict().find(key);\n\t\tif (i == dict().end()) throw type_error(\n\t\t\t(std::string(\"key not found: \") + key).c_str());\n\t\treturn i->second;\n\t}\n\n\tconst entry& entry::operator[](std::string const& key) const\n\t{\n\t\treturn (*this)[key.c_str()];\n\t}\n#endif\n\n\tentry::entry(dictionary_type const& v)\n\t{\n\t\tnew(data) dictionary_type(v);\n\t\tm_type = dictionary_t;\n\t}\n\n\tentry::entry(string_type const& v)\n\t{\n\t\tnew(data) string_type(v);\n\t\tm_type = string_t;\n\t}\n\n\tentry::entry(list_type const& v)\n\t{\n\t\tnew(data) list_type(v);\n\t\tm_type = list_t;\n\t}\n\n\tentry::entry(integer_type const& v)\n\t{\n\t\tnew(data) integer_type(v);\n\t\tm_type = int_t;\n\t}\n\n\tvoid entry::operator=(dictionary_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) dictionary_type(v);\n\t\tm_type = dictionary_t;\n\t}\n\n\tvoid entry::operator=(string_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) string_type(v);\n\t\tm_type = string_t;\n\t}\n\n\tvoid entry::operator=(list_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) list_type(v);\n\t\tm_type = list_t;\n\t}\n\n\tvoid entry::operator=(integer_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) integer_type(v);\n\t\tm_type = int_t;\n\t}\n\n\tbool entry::operator==(entry const& e) const\n\t{\n\t\tif (m_type != e.m_type) return false;\n\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\treturn integer() == e.integer();\n\t\tcase string_t:\n\t\t\treturn string() == e.string();\n\t\tcase list_t:\n\t\t\treturn list() == e.list();\n\t\tcase dictionary_t:\n\t\t\treturn dict() == e.dict();\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tvoid entry::construct(data_type t)\n\t{\n\t\tm_type = t;\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tnew(data) integer_type;\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tnew(data) string_type;\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tnew(data) list_type;\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tnew (data) dictionary_type;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\tm_type = undefined_t;\n\t\t}\n\t}\n\n\tvoid entry::copy(entry const& e)\n\t{\n\t\tm_type = e.m_type;\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tnew(data) integer_type(e.integer());\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tnew(data) string_type(e.string());\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tnew(data) list_type(e.list());\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tnew (data) dictionary_type(e.dict());\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tm_type = undefined_t;\n\t\t}\n\t}\n\n\tvoid entry::destruct()\n\t{\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tcall_destructor(reinterpret_cast(data));\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tcall_destructor(reinterpret_cast(data));\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tcall_destructor(reinterpret_cast(data));\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tcall_destructor(reinterpret_cast(data));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tvoid entry::swap(entry& e)\n\t{\n\t\t\/\/ not implemented\n\t\tTORRENT_ASSERT(false);\n\t}\n\n\tvoid entry::print(std::ostream& os, int indent) const\n\t{\n\t\tTORRENT_ASSERT(indent >= 0);\n\t\tfor (int i = 0; i < indent; ++i) os << \" \";\n\t\tswitch (m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tos << integer() << \"\\n\";\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\t{\n\t\t\t\tbool binary_string = false;\n\t\t\t\tfor (std::string::const_iterator i = string().begin(); i != string().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tif (!std::isprint(static_cast(*i)))\n\t\t\t\t\t{\n\t\t\t\t\t\tbinary_string = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (binary_string)\n\t\t\t\t{\n\t\t\t\t\tos.unsetf(std::ios_base::dec);\n\t\t\t\t\tos.setf(std::ios_base::hex);\n\t\t\t\t\tfor (std::string::const_iterator i = string().begin(); i != string().end(); ++i)\n\t\t\t\t\t\tos << std::setfill('0') << std::setw(2)\n\t\t\t\t\t\t\t<< static_cast((unsigned char)*i);\n\t\t\t\t\tos.unsetf(std::ios_base::hex);\n\t\t\t\t\tos.setf(std::ios_base::dec);\n\t\t\t\t\tos << \"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tos << string() << \"\\n\";\n\t\t\t\t}\n\t\t\t} break;\n\t\tcase list_t:\n\t\t\t{\n\t\t\t\tos << \"list\\n\";\n\t\t\t\tfor (list_type::const_iterator i = list().begin(); i != list().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\ti->print(os, indent+1);\n\t\t\t\t}\n\t\t\t} break;\n\t\tcase dictionary_t:\n\t\t\t{\n\t\t\t\tos << \"dictionary\\n\";\n\t\t\t\tfor (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tfor (int j = 0; j < indent+1; ++j) os << \" \";\n\t\t\t\t\tos << \"[\" << i->first << \"]\";\n\t\t\t\t\tif (i->second.type() != entry::string_t\n\t\t\t\t\t\t&& i->second.type() != entry::int_t)\n\t\t\t\t\t\tos << \"\\n\";\n\t\t\t\t\telse os << \" \";\n\t\t\t\t\ti->second.print(os, indent+2);\n\t\t\t\t}\n\t\t\t} break;\n\t\tdefault:\n\t\t\tos << \"\\n\";\n\t\t}\n\t}\n}\n\nfixed missing include in entry.cpp\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include \n#include \n#include \n#include \"libtorrent\/entry.hpp\"\n#include \"libtorrent\/config.hpp\"\n\n#if defined(_MSC_VER)\nnamespace std\n{\n\tusing ::isprint;\n}\n#define for if (false) {} else for\n#endif\n\nnamespace\n{\n\ttemplate \n\tvoid call_destructor(T* o)\n\t{\n\t\tTORRENT_ASSERT(o);\n\t\to->~T();\n\t}\n\n\tstruct compare_string\n\t{\n\t\tcompare_string(char const* s): m_str(s) {}\n\t\n\t\tbool operator()(\n\t\t\tstd::pair const& e) const\n\t\t{\n\t\t\treturn m_str && e.first == m_str;\n\t\t}\n\t\tchar const* m_str;\n\t};\n}\n\nnamespace libtorrent\n{\n\tnamespace detail\n\t{\n\t\tTORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)\n\t\t{\n\t\t\tint sign = 0;\n\t\t\tif (val < 0)\n\t\t\t{\n\t\t\t\tsign = 1;\n\t\t\t\tval = -val;\n\t\t\t}\n\t\t\tbuf[--size] = '\\0';\n\t\t\tif (val == 0) buf[--size] = '0';\n\t\t\tfor (; size > sign && val != 0;)\n\t\t\t{\n\t\t\t\tbuf[--size] = '0' + char(val % 10);\n\t\t\t\tval \/= 10;\n\t\t\t}\n\t\t\tif (sign) buf[--size] = '-';\n\t\t\treturn buf + size;\n\t\t}\n\t}\n\n\tentry& entry::operator[](char const* key)\n\t{\n\t\tdictionary_type::iterator i = dict().find(key);\n\t\tif (i != dict().end()) return i->second;\n\t\tdictionary_type::iterator ret = dict().insert(\n\t\t\tdict().begin()\n\t\t\t, std::make_pair(std::string(key), entry()));\n\t\treturn ret->second;\n\t}\n\n\n\tentry& entry::operator[](std::string const& key)\n\t{\n\t\treturn (*this)[key.c_str()];\n\t}\n\n\tentry* entry::find_key(char const* key)\n\t{\n\t\tdictionary_type::iterator i = std::find_if(\n\t\t\tdict().begin()\n\t\t\t, dict().end()\n\t\t\t, compare_string(key));\n\t\tif (i == dict().end()) return 0;\n\t\treturn &i->second;\n\t\n\t}\n\n\tentry const* entry::find_key(char const* key) const\n\t{\n\t\tdictionary_type::const_iterator i = dict().find(key);\n\t\tif (i == dict().end()) return 0;\n\t\treturn &i->second;\n\t}\n\t\n#ifndef BOOST_NO_EXCEPTIONS\n\tconst entry& entry::operator[](char const* key) const\n\t{\n\t\tdictionary_type::const_iterator i = dict().find(key);\n\t\tif (i == dict().end()) throw type_error(\n\t\t\t(std::string(\"key not found: \") + key).c_str());\n\t\treturn i->second;\n\t}\n\n\tconst entry& entry::operator[](std::string const& key) const\n\t{\n\t\treturn (*this)[key.c_str()];\n\t}\n#endif\n\n\tentry::entry(dictionary_type const& v)\n\t{\n\t\tnew(data) dictionary_type(v);\n\t\tm_type = dictionary_t;\n\t}\n\n\tentry::entry(string_type const& v)\n\t{\n\t\tnew(data) string_type(v);\n\t\tm_type = string_t;\n\t}\n\n\tentry::entry(list_type const& v)\n\t{\n\t\tnew(data) list_type(v);\n\t\tm_type = list_t;\n\t}\n\n\tentry::entry(integer_type const& v)\n\t{\n\t\tnew(data) integer_type(v);\n\t\tm_type = int_t;\n\t}\n\n\tvoid entry::operator=(dictionary_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) dictionary_type(v);\n\t\tm_type = dictionary_t;\n\t}\n\n\tvoid entry::operator=(string_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) string_type(v);\n\t\tm_type = string_t;\n\t}\n\n\tvoid entry::operator=(list_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) list_type(v);\n\t\tm_type = list_t;\n\t}\n\n\tvoid entry::operator=(integer_type const& v)\n\t{\n\t\tdestruct();\n\t\tnew(data) integer_type(v);\n\t\tm_type = int_t;\n\t}\n\n\tbool entry::operator==(entry const& e) const\n\t{\n\t\tif (m_type != e.m_type) return false;\n\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\treturn integer() == e.integer();\n\t\tcase string_t:\n\t\t\treturn string() == e.string();\n\t\tcase list_t:\n\t\t\treturn list() == e.list();\n\t\tcase dictionary_t:\n\t\t\treturn dict() == e.dict();\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tvoid entry::construct(data_type t)\n\t{\n\t\tm_type = t;\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tnew(data) integer_type;\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tnew(data) string_type;\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tnew(data) list_type;\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tnew (data) dictionary_type;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\tm_type = undefined_t;\n\t\t}\n\t}\n\n\tvoid entry::copy(entry const& e)\n\t{\n\t\tm_type = e.m_type;\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tnew(data) integer_type(e.integer());\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tnew(data) string_type(e.string());\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tnew(data) list_type(e.list());\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tnew (data) dictionary_type(e.dict());\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tm_type = undefined_t;\n\t\t}\n\t}\n\n\tvoid entry::destruct()\n\t{\n\t\tswitch(m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tcall_destructor(reinterpret_cast(data));\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\tcall_destructor(reinterpret_cast(data));\n\t\t\tbreak;\n\t\tcase list_t:\n\t\t\tcall_destructor(reinterpret_cast(data));\n\t\t\tbreak;\n\t\tcase dictionary_t:\n\t\t\tcall_destructor(reinterpret_cast(data));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTORRENT_ASSERT(m_type == undefined_t);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tvoid entry::swap(entry& e)\n\t{\n\t\t\/\/ not implemented\n\t\tTORRENT_ASSERT(false);\n\t}\n\n\tvoid entry::print(std::ostream& os, int indent) const\n\t{\n\t\tTORRENT_ASSERT(indent >= 0);\n\t\tfor (int i = 0; i < indent; ++i) os << \" \";\n\t\tswitch (m_type)\n\t\t{\n\t\tcase int_t:\n\t\t\tos << integer() << \"\\n\";\n\t\t\tbreak;\n\t\tcase string_t:\n\t\t\t{\n\t\t\t\tbool binary_string = false;\n\t\t\t\tfor (std::string::const_iterator i = string().begin(); i != string().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tif (!std::isprint(static_cast(*i)))\n\t\t\t\t\t{\n\t\t\t\t\t\tbinary_string = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (binary_string)\n\t\t\t\t{\n\t\t\t\t\tos.unsetf(std::ios_base::dec);\n\t\t\t\t\tos.setf(std::ios_base::hex);\n\t\t\t\t\tfor (std::string::const_iterator i = string().begin(); i != string().end(); ++i)\n\t\t\t\t\t\tos << std::setfill('0') << std::setw(2)\n\t\t\t\t\t\t\t<< static_cast((unsigned char)*i);\n\t\t\t\t\tos.unsetf(std::ios_base::hex);\n\t\t\t\t\tos.setf(std::ios_base::dec);\n\t\t\t\t\tos << \"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tos << string() << \"\\n\";\n\t\t\t\t}\n\t\t\t} break;\n\t\tcase list_t:\n\t\t\t{\n\t\t\t\tos << \"list\\n\";\n\t\t\t\tfor (list_type::const_iterator i = list().begin(); i != list().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\ti->print(os, indent+1);\n\t\t\t\t}\n\t\t\t} break;\n\t\tcase dictionary_t:\n\t\t\t{\n\t\t\t\tos << \"dictionary\\n\";\n\t\t\t\tfor (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tfor (int j = 0; j < indent+1; ++j) os << \" \";\n\t\t\t\t\tos << \"[\" << i->first << \"]\";\n\t\t\t\t\tif (i->second.type() != entry::string_t\n\t\t\t\t\t\t&& i->second.type() != entry::int_t)\n\t\t\t\t\t\tos << \"\\n\";\n\t\t\t\t\telse os << \" \";\n\t\t\t\t\ti->second.print(os, indent+2);\n\t\t\t\t}\n\t\t\t} break;\n\t\tdefault:\n\t\t\tos << \"\\n\";\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"analyzer.h\"\n#include \"ast.h\"\n#include \"cell.h\"\n#include \"compiler.h\"\n#include \"debuginfo.h\"\n#include \"disassembler.h\"\n#include \"exec.h\"\n#include \"lexer.h\"\n#include \"parser.h\"\n#include \"pt_dump.h\"\n#include \"repl.h\"\n#include \"support.h\"\n\nbool dump_tokens = false;\nbool dump_parse = false;\nbool dump_ast = false;\nbool dump_listing = false;\nbool enable_assert = true;\nbool enable_trace = false;\nbool error_json = false;\nunsigned short debug_port = 0;\nbool repl_no_prompt = false;\nbool repl_stop_on_any_error = false;\n\nstatic bool has_suffix(const std::string &str, const std::string &suffix)\n{\n return str.size() >= suffix.size() && str.substr(str.size() - suffix.size()) == suffix;\n}\n\nstatic TokenizedSource dump(const TokenizedSource &tokens)\n{\n for (auto t: tokens.tokens) {\n std::cerr << t.tostring() << \"\\n\";\n }\n return tokens;\n}\n\nstatic const pt::Program *dump(const pt::Program *parsetree)\n{\n pt::dump(std::cerr, parsetree);\n return parsetree;\n}\n\nstatic const ast::Program *dump(const ast::Program *program)\n{\n program->dump(std::cerr);\n return program;\n}\n\nstatic void repl(int argc, char *argv[])\n{\n Repl repl(argc, argv, repl_no_prompt, repl_stop_on_any_error, dump_listing);\n for (;;) {\n if (not repl_no_prompt) {\n std::cout << \"> \";\n }\n std::string s;\n if (not std::getline(std::cin, s)) {\n if (not repl_no_prompt) {\n std::cout << std::endl;\n }\n break;\n }\n repl.handle(s);\n }\n exit(0);\n}\n\nint main(int argc, char *argv[])\n{\n if (argc < 1) {\n fprintf(stderr, \"Usage: %s filename.neon\\n\", argv[0]);\n exit(1);\n }\n\n int a = 1;\n while (a < argc && argv[a][0] == '-' && argv[a][1] != '\\0') {\n std::string arg = argv[a];\n if (arg == \"-c\") {\n if (argv[a+1] == NULL) {\n fprintf(stderr, \"%s: -c requires argument\\n\", argv[0]);\n exit(1);\n }\n break;\n } else if (arg == \"-d\") {\n a++;\n try {\n debug_port = static_cast(std::stoul(argv[a]));\n } catch(std::invalid_argument) {\n fprintf(stderr, \"%s: -d requires integer argument\\n\", argv[0]);\n exit(1);\n }\n } else if (arg == \"--json\") {\n error_json = true;\n } else if (arg == \"-l\") {\n dump_listing = true;\n } else if (arg == \"-n\") {\n enable_assert = false;\n } else if (arg == \"--repl-no-prompt\") {\n repl_no_prompt = true;\n } else if (arg == \"--repl-stop-on-any-error\") {\n repl_stop_on_any_error = true;\n } else if (arg == \"-t\") {\n enable_trace = true;\n } else {\n fprintf(stderr, \"Unknown option: %s\\n\", arg.c_str());\n exit(1);\n }\n a++;\n }\n\n if (a >= argc) {\n repl(argc, argv);\n }\n\n const std::string name = argv[a];\n auto i = name.find_last_of(\"\/:\\\\\");\n const std::string source_path { i != std::string::npos ? name.substr(0, i+1) : \"\" };\n\n CompilerSupport compiler_support(source_path, nullptr);\n RuntimeSupport runtime_support(source_path);\n std::unique_ptr debug;\n\n std::vector bytecode;\n if (not has_suffix(name, \".neonx\")) {\n\n std::stringstream source;\n if (name == \"-\") {\n source << std::cin.rdbuf();\n } else if (name == \"-c\") {\n source << argv[a+1];\n } else {\n std::ifstream inf(name);\n if (not inf) {\n fprintf(stderr, \"Source file not found: %s\\n\", name.c_str());\n exit(1);\n }\n source << inf.rdbuf();\n }\n\n \/\/ TODO - Allow reading debug information from file.\n debug.reset(new DebugInfo(name, source.str()));\n\n try {\n auto tokens = tokenize(name, source.str());\n if (dump_tokens) {\n dump(*tokens);\n }\n\n auto parsetree = parse(*tokens);\n if (dump_parse) {\n dump(parsetree.get());\n }\n\n auto program = analyze(&compiler_support, parsetree.get());\n if (dump_ast) {\n dump(program);\n }\n\n bytecode = compile(program, debug.get());\n if (dump_listing) {\n disassemble(bytecode, std::cerr, debug.get());\n }\n\n } catch (CompilerError *error) {\n if (error_json) {\n error->write_json(std::cerr);\n } else {\n error->write(std::cerr);\n }\n exit(1);\n }\n\n } else {\n\n std::ifstream inf(name, std::ios::binary);\n if (not inf) {\n fprintf(stderr, \"Source file not found: %s\\n\", name.c_str());\n exit(1);\n }\n std::stringstream object;\n object << inf.rdbuf();\n std::string s = object.str();\n std::copy(s.begin(), s.end(), std::back_inserter(bytecode));\n\n }\n\n struct ExecOptions options;\n options.enable_assert = enable_assert;\n options.enable_trace = enable_trace;\n exit(exec(name, bytecode, debug.get(), &runtime_support, &options, debug_port, argc-a, argv+a));\n}\nCatch polymorphic exception by reference, not value#include \n#include \n#include \n\n#include \"analyzer.h\"\n#include \"ast.h\"\n#include \"cell.h\"\n#include \"compiler.h\"\n#include \"debuginfo.h\"\n#include \"disassembler.h\"\n#include \"exec.h\"\n#include \"lexer.h\"\n#include \"parser.h\"\n#include \"pt_dump.h\"\n#include \"repl.h\"\n#include \"support.h\"\n\nbool dump_tokens = false;\nbool dump_parse = false;\nbool dump_ast = false;\nbool dump_listing = false;\nbool enable_assert = true;\nbool enable_trace = false;\nbool error_json = false;\nunsigned short debug_port = 0;\nbool repl_no_prompt = false;\nbool repl_stop_on_any_error = false;\n\nstatic bool has_suffix(const std::string &str, const std::string &suffix)\n{\n return str.size() >= suffix.size() && str.substr(str.size() - suffix.size()) == suffix;\n}\n\nstatic TokenizedSource dump(const TokenizedSource &tokens)\n{\n for (auto t: tokens.tokens) {\n std::cerr << t.tostring() << \"\\n\";\n }\n return tokens;\n}\n\nstatic const pt::Program *dump(const pt::Program *parsetree)\n{\n pt::dump(std::cerr, parsetree);\n return parsetree;\n}\n\nstatic const ast::Program *dump(const ast::Program *program)\n{\n program->dump(std::cerr);\n return program;\n}\n\nstatic void repl(int argc, char *argv[])\n{\n Repl repl(argc, argv, repl_no_prompt, repl_stop_on_any_error, dump_listing);\n for (;;) {\n if (not repl_no_prompt) {\n std::cout << \"> \";\n }\n std::string s;\n if (not std::getline(std::cin, s)) {\n if (not repl_no_prompt) {\n std::cout << std::endl;\n }\n break;\n }\n repl.handle(s);\n }\n exit(0);\n}\n\nint main(int argc, char *argv[])\n{\n if (argc < 1) {\n fprintf(stderr, \"Usage: %s filename.neon\\n\", argv[0]);\n exit(1);\n }\n\n int a = 1;\n while (a < argc && argv[a][0] == '-' && argv[a][1] != '\\0') {\n std::string arg = argv[a];\n if (arg == \"-c\") {\n if (argv[a+1] == NULL) {\n fprintf(stderr, \"%s: -c requires argument\\n\", argv[0]);\n exit(1);\n }\n break;\n } else if (arg == \"-d\") {\n a++;\n try {\n debug_port = static_cast(std::stoul(argv[a]));\n } catch (std::invalid_argument &) {\n fprintf(stderr, \"%s: -d requires integer argument\\n\", argv[0]);\n exit(1);\n }\n } else if (arg == \"--json\") {\n error_json = true;\n } else if (arg == \"-l\") {\n dump_listing = true;\n } else if (arg == \"-n\") {\n enable_assert = false;\n } else if (arg == \"--repl-no-prompt\") {\n repl_no_prompt = true;\n } else if (arg == \"--repl-stop-on-any-error\") {\n repl_stop_on_any_error = true;\n } else if (arg == \"-t\") {\n enable_trace = true;\n } else {\n fprintf(stderr, \"Unknown option: %s\\n\", arg.c_str());\n exit(1);\n }\n a++;\n }\n\n if (a >= argc) {\n repl(argc, argv);\n }\n\n const std::string name = argv[a];\n auto i = name.find_last_of(\"\/:\\\\\");\n const std::string source_path { i != std::string::npos ? name.substr(0, i+1) : \"\" };\n\n CompilerSupport compiler_support(source_path, nullptr);\n RuntimeSupport runtime_support(source_path);\n std::unique_ptr debug;\n\n std::vector bytecode;\n if (not has_suffix(name, \".neonx\")) {\n\n std::stringstream source;\n if (name == \"-\") {\n source << std::cin.rdbuf();\n } else if (name == \"-c\") {\n source << argv[a+1];\n } else {\n std::ifstream inf(name);\n if (not inf) {\n fprintf(stderr, \"Source file not found: %s\\n\", name.c_str());\n exit(1);\n }\n source << inf.rdbuf();\n }\n\n \/\/ TODO - Allow reading debug information from file.\n debug.reset(new DebugInfo(name, source.str()));\n\n try {\n auto tokens = tokenize(name, source.str());\n if (dump_tokens) {\n dump(*tokens);\n }\n\n auto parsetree = parse(*tokens);\n if (dump_parse) {\n dump(parsetree.get());\n }\n\n auto program = analyze(&compiler_support, parsetree.get());\n if (dump_ast) {\n dump(program);\n }\n\n bytecode = compile(program, debug.get());\n if (dump_listing) {\n disassemble(bytecode, std::cerr, debug.get());\n }\n\n } catch (CompilerError *error) {\n if (error_json) {\n error->write_json(std::cerr);\n } else {\n error->write(std::cerr);\n }\n exit(1);\n }\n\n } else {\n\n std::ifstream inf(name, std::ios::binary);\n if (not inf) {\n fprintf(stderr, \"Source file not found: %s\\n\", name.c_str());\n exit(1);\n }\n std::stringstream object;\n object << inf.rdbuf();\n std::string s = object.str();\n std::copy(s.begin(), s.end(), std::back_inserter(bytecode));\n\n }\n\n struct ExecOptions options;\n options.enable_assert = enable_assert;\n options.enable_trace = enable_trace;\n exit(exec(name, bytecode, debug.get(), &runtime_support, &options, debug_port, argc-a, argv+a));\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2012, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/rss.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n#include \"libtorrent\/aux_\/session_impl.hpp\"\n#include \"libtorrent\/http_parser.hpp\"\n\n#include \"test.hpp\"\n\nusing namespace libtorrent;\n\nvoid print_feed(feed_status const& f)\n{\n\tfprintf(stderr, \"FEED: %s\\n\",f.url.c_str());\n\tif (f.error)\n\t\tfprintf(stderr, \"ERROR: %s\\n\", f.error.message().c_str());\n\n\tfprintf(stderr, \" %s\\n %s\\n\", f.title.c_str(), f.description.c_str());\n\tfprintf(stderr, \" ttl: %d minutes\\n\", f.ttl);\n\tfprintf(stderr, \" num items: %d\\n\", int(f.items.size()));\n\n\tfor (std::vector::const_iterator i = f.items.begin()\n\t\t, end(f.items.end()); i != end; ++i)\n\t{\n\t\tfprintf(stderr, \"\\033[32m%s\\033[0m\\n------------------------------------------------------\\n\"\n\t\t\t\" url: %s\\n size: %\"PRId64\"\\n info-hash: %s\\n uuid: %s\\n description: %s\\n\"\n\t\t\t\" comment: %s\\n category: %s\\n\"\n\t\t\t, i->title.c_str(), i->url.c_str(), i->size\n\t\t\t, i->info_hash.is_all_zeros() ? \"\" : to_hex(i->info_hash.to_string()).c_str()\n\t\t\t, i->uuid.c_str(), i->description.c_str(), i->comment.c_str(), i->category.c_str());\n\t}\n}\n\nstruct rss_expect\n{\n\trss_expect(int nitems, std::string url, std::string title, size_type size)\n\t\t: num_items(nitems), first_url(url), first_title(title), first_size(size)\n\t{}\n\n\tint num_items;\n\tstd::string first_url;\n\tstd::string first_title;\n\tsize_type first_size;\n};\n\nvoid test_feed(std::string const& filename, rss_expect const& expect)\n{\n\tstd::vector buffer;\n\terror_code ec;\n\tload_file(filename, buffer, ec);\n\tif (ec)\n\t{\n\t\tfprintf(stderr, \"failed to load file \\\"%s\\\": %s\\n\", filename.c_str(), ec.message().c_str());\n\t}\n\tTEST_CHECK(!ec);\n\n\tchar* buf = buffer.size() ? &buffer[0] : NULL;\n\tint len = buffer.size();\n\n\tchar const header[] = \"HTTP\/1.1 200 OK\\r\\n\"\n\t\t\"\\r\\n\";\n\n\tboost::shared_ptr s = boost::shared_ptr(new aux::session_impl(\n\t\tstd::make_pair(100, 200), fingerprint(\"TT\", 0, 0, 0 ,0), NULL, 0));\n\ts->start_session();\n\n\tfeed_settings sett;\n\tsett.auto_download = false;\n\tsett.auto_map_handles = false;\n\tboost::shared_ptr f = boost::shared_ptr(new feed(*s, sett));\n\thttp_parser parser;\n\tbool err = false;\n\tparser.incoming(buffer::const_interval(header, header + sizeof(header)-1), err);\n\tTEST_CHECK(err == false);\n\n\tf->on_feed(error_code(), parser, buf, len);\n\n\tfeed_status st;\n\tf->get_feed_status(&st);\n\tTEST_CHECK(!st.error);\n\n\tprint_feed(st);\n\n\tTEST_CHECK(st.items.size() == expect.num_items);\n\tif (st.items.size() > 0)\n\t{\n\t\tTEST_CHECK(st.items[0].url == expect.first_url);\n\t\tTEST_CHECK(st.items[0].size == expect.first_size);\n\t\tTEST_CHECK(st.items[0].title == expect.first_title);\n\t}\n\n\tentry state;\n\tf->save_state(state);\n\n\tfprintf(stderr, \"feed_state:\\n\");\n#ifdef TORRENT_DEBUG\n\tstate.print(std::cerr);\n#endif\n\n\t\/\/ TODO: verify some key state is saved in 'state'\n}\n\nint test_main()\n{\n\ttest_feed(combine_path(\"..\", \"eztv.xml\"), rss_expect(30, \"http:\/\/torrent.zoink.it\/The.Daily.Show.2012.02.16.(HDTV-LMAO)[VTV].torrent\", \"The Daily Show 2012-02-16 [HDTV - LMAO]\", 183442338));\n\ttest_feed(combine_path(\"..\", \"cb.xml\"), rss_expect(50, \"http:\/\/www.clearbits.net\/get\/1911-norbergfestival-2011.torrent\", \"Norbergfestival 2011\", 1160773632));\n\ttest_feed(combine_path(\"..\", \"kat.xml\"), rss_expect(25, \"http:\/\/kat.ph\/torrents\/benito-di-paula-1975-benito-di-paula-lp-rip-ogg-at-500-jarax4u-t6194897\/\", \"Benito Di Paula - 1975 - Benito Di Paula (LP Rip OGG at 500) [jarax4u]\", 168773863));\n\ttest_feed(combine_path(\"..\", \"mn.xml\"), rss_expect(20, \"http:\/\/www.mininova.org\/get\/13203100\", \"Dexcell - January TwentyTwelve Mix\", 137311179));\n\ttest_feed(combine_path(\"..\", \"pb.xml\"), rss_expect(60, \"magnet:?xt=urn:btih:FD4CDDB7BBE722D17A018EFD875EB0695ED7159C&dn=Thompson+Twins+-+1989+-+Big+Trash+%5BMP3%5D\", \"Thompson Twins - 1989 - Big Trash [MP3]\", 100160904));\n\treturn 0;\n}\n\nfix test_rss for windows\/*\n\nCopyright (c) 2012, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/rss.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n#include \"libtorrent\/aux_\/session_impl.hpp\"\n#include \"libtorrent\/http_parser.hpp\"\n\n#include \"test.hpp\"\n\nusing namespace libtorrent;\n\nvoid print_feed(feed_status const& f)\n{\n\tfprintf(stderr, \"FEED: %s\\n\",f.url.c_str());\n\tif (f.error)\n\t\tfprintf(stderr, \"ERROR: %s\\n\", f.error.message().c_str());\n\n\tfprintf(stderr, \" %s\\n %s\\n\", f.title.c_str(), f.description.c_str());\n\tfprintf(stderr, \" ttl: %d minutes\\n\", f.ttl);\n\tfprintf(stderr, \" num items: %d\\n\", int(f.items.size()));\n\n\tfor (std::vector::const_iterator i = f.items.begin()\n\t\t, end(f.items.end()); i != end; ++i)\n\t{\n\t\tfprintf(stderr, \"\\033[32m%s\\033[0m\\n------------------------------------------------------\\n\"\n\t\t\t\" url: %s\\n size: %\"PRId64\"\\n info-hash: %s\\n uuid: %s\\n description: %s\\n\"\n\t\t\t\" comment: %s\\n category: %s\\n\"\n\t\t\t, i->title.c_str(), i->url.c_str(), i->size\n\t\t\t, i->info_hash.is_all_zeros() ? \"\" : to_hex(i->info_hash.to_string()).c_str()\n\t\t\t, i->uuid.c_str(), i->description.c_str(), i->comment.c_str(), i->category.c_str());\n\t}\n}\n\nstruct rss_expect\n{\n\trss_expect(int nitems, std::string url, std::string title, size_type size)\n\t\t: num_items(nitems), first_url(url), first_title(title), first_size(size)\n\t{}\n\n\tint num_items;\n\tstd::string first_url;\n\tstd::string first_title;\n\tsize_type first_size;\n};\n\nvoid test_feed(std::string const& filename, rss_expect const& expect)\n{\n\tstd::vector buffer;\n\terror_code ec;\n\tload_file(filename, buffer, ec);\n\tif (ec)\n\t{\n\t\tfprintf(stderr, \"failed to load file \\\"%s\\\": %s\\n\", filename.c_str(), ec.message().c_str());\n\t}\n\tTEST_CHECK(!ec);\n\n\tchar* buf = buffer.size() ? &buffer[0] : NULL;\n\tint len = buffer.size();\n\n\tchar const header[] = \"HTTP\/1.1 200 OK\\r\\n\"\n\t\t\"\\r\\n\";\n\n\tboost::shared_ptr s = boost::shared_ptr(new aux::session_impl(\n\t\tstd::make_pair(100, 200), fingerprint(\"TT\", 0, 0, 0 ,0), NULL, 0));\n\ts->start_session();\n\n\tfeed_settings sett;\n\tsett.auto_download = false;\n\tsett.auto_map_handles = false;\n\tboost::shared_ptr f = boost::shared_ptr(new feed(*s, sett));\n\thttp_parser parser;\n\tbool err = false;\n\tparser.incoming(buffer::const_interval(header, header + sizeof(header)-1), err);\n\tTEST_CHECK(err == false);\n\n\tf->on_feed(error_code(), parser, buf, len);\n\n\tfeed_status st;\n\tf->get_feed_status(&st);\n\tTEST_CHECK(!st.error);\n\n\tprint_feed(st);\n\n\tTEST_CHECK(st.items.size() == expect.num_items);\n\tif (st.items.size() > 0)\n\t{\n\t\tTEST_CHECK(st.items[0].url == expect.first_url);\n\t\tTEST_CHECK(st.items[0].size == expect.first_size);\n\t\tTEST_CHECK(st.items[0].title == expect.first_title);\n\t}\n\n\tentry state;\n\tf->save_state(state);\n\n\tfprintf(stderr, \"feed_state:\\n\");\n#ifdef TORRENT_DEBUG\n\tstate.print(std::cerr);\n#endif\n\n\t\/\/ TODO: verify some key state is saved in 'state'\n}\n\nint test_main()\n{\n\tstd::string root_dir = parent_path(current_working_directory());\n\n\ttest_feed(combine_path(root_dir, \"eztv.xml\"), rss_expect(30, \"http:\/\/torrent.zoink.it\/The.Daily.Show.2012.02.16.(HDTV-LMAO)[VTV].torrent\", \"The Daily Show 2012-02-16 [HDTV - LMAO]\", 183442338));\n\ttest_feed(combine_path(root_dir, \"cb.xml\"), rss_expect(50, \"http:\/\/www.clearbits.net\/get\/1911-norbergfestival-2011.torrent\", \"Norbergfestival 2011\", 1160773632));\n\ttest_feed(combine_path(root_dir, \"kat.xml\"), rss_expect(25, \"http:\/\/kat.ph\/torrents\/benito-di-paula-1975-benito-di-paula-lp-rip-ogg-at-500-jarax4u-t6194897\/\", \"Benito Di Paula - 1975 - Benito Di Paula (LP Rip OGG at 500) [jarax4u]\", 168773863));\n\ttest_feed(combine_path(root_dir, \"mn.xml\"), rss_expect(20, \"http:\/\/www.mininova.org\/get\/13203100\", \"Dexcell - January TwentyTwelve Mix\", 137311179));\n\ttest_feed(combine_path(root_dir, \"pb.xml\"), rss_expect(60, \"magnet:?xt=urn:btih:FD4CDDB7BBE722D17A018EFD875EB0695ED7159C&dn=Thompson+Twins+-+1989+-+Big+Trash+%5BMP3%5D\", \"Thompson Twins - 1989 - Big Trash [MP3]\", 100160904));\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield \n *\n * This application is open source and may be redistributed and\/or modified \n * freely and without restriction, both in commericial and non commericial applications,\n * as long as this copyright notice is maintained.\n * \n * This application is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#include \n#include \n#include \n#include \n\nint main( int argc, char **argv )\n{\n\n \/\/ use an ArgumentParser object to manage the program arguments.\n osg::ArgumentParser arguments(&argc,argv);\n \n \/\/ set up the usage document, in case we need to print out how to use this program.\n arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());\n arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+\" is the standard OpenSceneGraph example which loads and visualises 3d models.\");\n arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+\" [options] filename ...\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--image \",\"Load an image and render it on a quad\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--dem \",\"Load an image\/DEM and render it on a HeightField\");\n arguments.getApplicationUsage()->addCommandLineOption(\"-h or --help\",\"Display command line parameters\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--help-env\",\"Display environmental variables available\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--help-keys\",\"Display keyboard & mouse bindings available\");\n\n arguments.getApplicationUsage()->addCommandLineOption(\"--help-all\",\"Display all command line, env vars and keyboard & mouse bindings.\");\n \n\n \/\/ construct the viewer.\n osgProducer::Viewer viewer(arguments);\n\n \/\/ set up the value with sensible default event handlers.\n viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);\n\n \/\/ get details on keyboard and mouse bindings used by the viewer.\n viewer.getUsage(*arguments.getApplicationUsage());\n\n \/\/ if user request help write it out to cout.\n bool helpAll = arguments.read(\"--help-all\");\n unsigned int helpType = ((helpAll || arguments.read(\"-h\") || arguments.read(\"--help\"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) |\n ((helpAll || arguments.read(\"--help-env\"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) |\n ((helpAll || arguments.read(\"--help-keys\"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 );\n if (helpType)\n {\n arguments.getApplicationUsage()->write(std::cout, helpType);\n return 1;\n }\n\n \/\/ report any errors if they have occurred when parsing the program arguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n return 1;\n }\n \n if (arguments.argc()<=1)\n {\n arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);\n return 1;\n }\n\n osg::Timer_t start_tick = osg::Timer::instance()->tick();\n\n \/\/ read the scene from the list of file specified command line args.\n osg::ref_ptr loadedModel = osgDB::readNodeFiles(arguments);\n\n \/\/ if no model has been successfully loaded report failure.\n if (!loadedModel) \n {\n std::cout << arguments.getApplicationName() <<\": No data loaded\" << std::endl;\n return 1;\n }\n\n \/\/ any option left unread are converted into errors to write out later.\n arguments.reportRemainingOptionsAsUnrecognized();\n\n \/\/ report any errors if they have occurred when parsing the program arguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n }\n\n osg::Timer_t end_tick = osg::Timer::instance()->tick();\n\n std::cout << \"Time to load = \"<delta_s(start_tick,end_tick)<tweaked comment.\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield \n *\n * This application is open source and may be redistributed and\/or modified \n * freely and without restriction, both in commericial and non commericial applications,\n * as long as this copyright notice is maintained.\n * \n * This application is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#include \n#include \n#include \n#include \n\nint main( int argc, char **argv )\n{\n\n \/\/ use an ArgumentParser object to manage the program arguments.\n osg::ArgumentParser arguments(&argc,argv);\n \n \/\/ set up the usage document, in case we need to print out how to use this program.\n arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());\n arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+\" is the standard OpenSceneGraph example which loads and visualises 3d models.\");\n arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+\" [options] filename ...\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--image \",\"Load an image and render it on a quad\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--dem \",\"Load an image\/DEM and render it on a HeightField\");\n arguments.getApplicationUsage()->addCommandLineOption(\"-h or --help\",\"Display command line parameters\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--help-env\",\"Display environmental variables available\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--help-keys\",\"Display keyboard & mouse bindings available\");\n\n arguments.getApplicationUsage()->addCommandLineOption(\"--help-all\",\"Display all command line, env vars and keyboard & mouse bindings.\");\n \n\n \/\/ construct the viewer.\n osgProducer::Viewer viewer(arguments);\n\n \/\/ set up the value with sensible default event handlers.\n viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);\n\n \/\/ get details on keyboard and mouse bindings used by the viewer.\n viewer.getUsage(*arguments.getApplicationUsage());\n\n \/\/ if user request help write it out to cout.\n bool helpAll = arguments.read(\"--help-all\");\n unsigned int helpType = ((helpAll || arguments.read(\"-h\") || arguments.read(\"--help\"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) |\n ((helpAll || arguments.read(\"--help-env\"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) |\n ((helpAll || arguments.read(\"--help-keys\"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 );\n if (helpType)\n {\n arguments.getApplicationUsage()->write(std::cout, helpType);\n return 1;\n }\n\n \/\/ report any errors if they have occurred when parsing the program arguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n return 1;\n }\n \n if (arguments.argc()<=1)\n {\n arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);\n return 1;\n }\n\n osg::Timer_t start_tick = osg::Timer::instance()->tick();\n\n \/\/ read the scene from the list of file specified command line args.\n osg::ref_ptr loadedModel = osgDB::readNodeFiles(arguments);\n\n \/\/ if no model has been successfully loaded report failure.\n if (!loadedModel) \n {\n std::cout << arguments.getApplicationName() <<\": No data loaded\" << std::endl;\n return 1;\n }\n\n \/\/ any option left unread are converted into errors to write out later.\n arguments.reportRemainingOptionsAsUnrecognized();\n\n \/\/ report any errors if they have occurred when parsing the program arguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n }\n\n osg::Timer_t end_tick = osg::Timer::instance()->tick();\n\n std::cout << \"Time to load = \"<delta_s(start_tick,end_tick)<"} {"text":"\n\/* Interface for debugging- spawns a prompt that will controll the main thread if it hits a specifies break point*\/\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"debug_simHandler.hpp\"\n\nusing namespace std;\n\n\/*function prototypes*\/\nvoid *run_debugger(void * holder);\nvoid parseline(string line);\nint handle_command(string command);\nvoid help();\nvoid messageHandler(uint64_t* msg);\nvoid debugSend(int command, string build);\n\n\/*to store the last input in the debugger*\/\nint lastInstruction = 0;\nstring lastBuild = \"\";\n\n#define DEBUG 16\n#define SIZE (sizeof(uint64_t))\n\nstatic bool isPaused = false;\nstatic void (*sendMessage)(int,int,uint64_t*);\nstatic void (*pauseSimulation)(int);\nstatic void (*unPauseSimulation)(void);\n\n\/*spawn the debbugging prompt as a separate thread to\n controll the main one*\/\nvoid (*initDebugger(void (*sendMsg)(int,int,uint64_t*),\n\t\t void (*pauseSim)(int),\n\t\t void (*unPauseSim)(void)))(uint64_t*){\n \n\n pthread_t tid;\n \n sendMessage = sendMsg;\n pauseSimulation = pauseSim;\n unPauseSimulation = unPauseSim;\n\n isPaused = true;\n pthread_create(&tid,NULL,run_debugger, NULL);\n\n return messageHandler;\n}\n\n\n\/*to be called by the simulator to controll the debugger\n * or to display some info*\/\nvoid messageHandler(uint64_t* msg){\n\n int sizeMsg;\n int command = (int)msg[2];\n\n if (command == BREAKPOINT){\n sizeMsg = 2*SIZE;\n uint64_t msgSend[sizeMsg\/SIZE];\n msgSend[0] = sizeMsg;\n msgSend[1] = DEBUG;\n msgSend[2] = PAUSE;\n sendMessage(-1,sizeMsg,(uint64_t*)msgSend);\n pauseSimulation(0);\n cout << (char*)&msg[3];\n isPaused = true;\n\n } else if (command == PRINTCONTENT){\n cout << (char*)&msg[3];\n isPaused = true;\n }\n}\n\n\n\/\/continuously attend command line prompt for debugger\n\/\/when the system is not paused\nvoid *run_debugger(void* holder){\n\n (void)holder;\n string inpt;\n \n while(true){\n if (isPaused){\n cout << \">\";\n isPaused = false;\n getline(cin,inpt);\n \/\/react to the input\n parseline(inpt);\n }\n }\n return NULL;\n}\n\n\n\n\/*parses the command line and run the debugger*\/\nvoid parseline(string line){\n\n string build = \"\";\n int wordCount = 1;\n \n int command = NOTHING;\n\n \/*empty input*\/\n if (line == \"\"){\n \/\/enterlast stored command\n debugSend(lastInstruction,lastBuild);\n return;\n }\n\n \/*loop through input line*\/\n for (unsigned int i = 0; i < line.length(); i++){\n \n\n \/*parse line for words*\/\n if (line[i]!=' '){\n build += line[i];\n\n } else {\n \/\/exract the command\n if (wordCount == 1)\n\tcommand = handle_command(build);\n wordCount++;\n build = \"\";\n }\n }\n \n\n \/*no whitespace at all-single word commands*\/\n if (wordCount == 1){\n command = handle_command(build);\n \n if (command != BREAKPOINT && command!=DUMP){\n debugSend(command,\"\");\n lastInstruction = command;\n lastBuild = build;\n return;\n }\n }\n \n \/*if not enough info - these types must have a specification*\/\n if ((command == BREAKPOINT||command == DUMP)&& wordCount == 1){\n cout << \"Please specify- type help for options\" << endl;\n isPaused = true;\n return;\n }\n\n \/*handle breakpoints and dumps*\/\n if (wordCount == 2){\n\tif (command == BREAKPOINT||command == DUMP)\n\t debugSend(command,build);\n\telse \n\t debugSend(command,\"\");\n lastInstruction = command;\n lastBuild = build;\n }\n}\n\n\nint stringType2Int(string type){\n if (type == \"factDer\"){\n return FACTDER;\n } else if (type == \"factCon\"){\n return FACTCON;\n } else if (type == \"factRet\"){\n return FACTRET;\n } else if (type == \"sense\"){\n return SENSE;\n } else if (type == \"action\"){\n return ACTION;\n } else if (type == \"block\"){\n return BLOCK;\n } else { \n cout << \"unknown type-- enter help for options\" << endl;\n return -1;\n }\n}\n\n\n\/*constructs a message to be sent to the Simulator*\/\nvoid debugSend(int command, string build){\n \n int node;\n string name;\n int size;\n int type;\n char* nameSpot;\n\n \n if(command == CONTINUE){\n size = 2*SIZE;\n uint64_t msgCont[size\/SIZE];\n msgCont[0] = size;\n msgCont[1] = DEBUG;\n msgCont[2] = UNPAUSE;\n \/*broadcast unpause to all VMs*\/\n sendMessage(-1,size,(uint64_t*)msgCont);\n unPauseSimulation();\n\n } else if (command == BREAKPOINT) {\n if (build[0] == ':'||build[0] == '@'){\n cout << \"Please Specify a Type\" << endl;\n isPaused = true;\n return;\n }\n type = stringType2Int(getType(build));\n if (type == -1){\n isPaused = true;\n return;\n }\n \/*if no node specified broadcast to all*\/\n if (getNode(build) == \"\"){\n node = -1;\n else\n node = atoi(getNode(build).c_str());\n name = getName(build);\n size = 3*SIZE + (name.length() + 1) \n + (SIZE - (name.length() + 1)%SIZE);\n uint64_t msgBreak[size\/SIZE];\n msgBreak[0] = size;\n msgBreak[1] = DEBUG;\n msgBreak[2] = BREAKPOINT;\n msgBreak[3] = type;\n nameSpot = (char*)&msgBreak[4];\n memcpy(nameSpot,name.c_str(),name.length()+1);\n sendMessage(node,size,(uint64_t*)msgBreak);\n\n } else if (command == DUMP){\n node = atoi(build.c_str());\n size = 2*SIZE;\n uint64_t msgDump[size\/SIZE];\n msgDump[0] = size;\n msgDump[1] = DEBUG;\n msgDump[2] = DUMP;\n sendMessage(node,size,(uint64_t*)msgDump);\n\n } else if (command == NOTHING){\n isPaused = true;\n }\n return;\n}\n\t\t \n\t\t \n\n\t \n\n\n\/*recognizes and sets different modes for the debugger*\/\nint handle_command(string command){\n\n int retVal;\n\n if (command == \"break\"){\n retVal = BREAKPOINT;\n } else if (command == \"help\"||command == \"h\") {\n help();\n retVal = NOTHING;\n } else if (command == \"run\"|| command == \"r\") {\n retVal = CONTINUE;\n } else if (command == \"dump\"||command == \"d\") {\n retVal = DUMP;\n } else if (command == \"continue\"||command == \"c\"){\n retVal = CONTINUE;\n } else if (command == \"quit\"||command == \"q\"){\n exit(0);\n } else {\n cout << \"unknown command: type 'help' for options \" << endl;\n retVal = NOTHING;\n }\n return retVal;\n}\n\n\n\/*prints the help screen*\/\nvoid help(){\n cout << endl;\n cout << \"*******************************************************************\" << endl;\n cout << endl;\n cout << \"DEBUGGER HELP\" << endl;\n cout << \"\\t-break - set break point at specified place\" << endl;\n cout << \"\\t\\t-Specification Format:\" << endl;\n cout << \"\\t\\t :@ OR\" << endl;\n cout << \"\\t\\t : OR\" << endl;\n cout << \"\\t\\t @\" << endl;\n cout << \"\\t\\t -type - [factRet|factDer|factCon|action|sense|block]\" << endl;\n cout << \"\\t\\t\\t-a type MUST be specified\" << endl;\n cout << \"\\t\\t -name - the name of certain type ex. the name of a fact\" << endl;\n cout << \"\\t\\t -node - the number of the node\" << endl;\n cout << \"\\t-dump or d - dump the state of the system\" << endl;\n cout << \"\\t-continue or c - continue execution\" << endl;\n cout << \"\\t-run or r - start the program\" << endl;\n cout << \"\\t-quit - exit debugger\" << endl;\n cout << endl;\n cout << \"\\t-Press Enter to use last Input\" << endl;\n cout << endl;\n cout << \"*******************************************************************\" << endl;\n}\n \n\n\n\n \n \n\n \nfixed for andre's size specifications\n\/* Interface for debugging- spawns a prompt that will controll the main thread if it hits a specifies break point*\/\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"debug_simHandler.hpp\"\n\nusing namespace std;\n\n\/*function prototypes*\/\nvoid *run_debugger(void * holder);\nvoid parseline(string line);\nint handle_command(string command);\nvoid help();\nvoid messageHandler(uint64_t* msg);\nvoid debugSend(int command, string build);\n\n\/*to store the last input in the debugger*\/\nint lastInstruction = 0;\nstring lastBuild = \"\";\n\n#define DEBUG 16\n#define SIZE (sizeof(uint64_t))\n\nstatic bool isPaused = false;\nstatic void (*sendMessage)(int,int,uint64_t*);\nstatic void (*pauseSimulation)(int);\nstatic void (*unPauseSimulation)(void);\n\n\/*spawn the debbugging prompt as a separate thread to\n controll the main one*\/\nvoid (*initDebugger(void (*sendMsg)(int,int,uint64_t*),\n\t\t void (*pauseSim)(int),\n\t\t void (*unPauseSim)(void)))(uint64_t*){\n \n\n pthread_t tid;\n \n sendMessage = sendMsg;\n pauseSimulation = pauseSim;\n unPauseSimulation = unPauseSim;\n\n isPaused = true;\n pthread_create(&tid,NULL,run_debugger, NULL);\n\n return messageHandler;\n}\n\n\n\/*to be called by the simulator to controll the debugger\n * or to display some info*\/\nvoid messageHandler(uint64_t* msg){\n\n int sizeMsg;\n int command = (int)msg[2];\n\n if (command == BREAKPOINT){\n sizeMsg = 2*SIZE;\n uint64_t msgSend[sizeMsg\/SIZE];\n msgSend[0] = sizeMsg;\n msgSend[1] = DEBUG;\n msgSend[2] = PAUSE;\n sendMessage(-1,sizeMsg+SIZE,(uint64_t*)msgSend);\n pauseSimulation(0);\n cout << (char*)&msg[3];\n isPaused = true;\n\n } else if (command == PRINTCONTENT){\n cout << (char*)&msg[3];\n isPaused = true;\n }\n}\n\n\n\/\/continuously attend command line prompt for debugger\n\/\/when the system is not paused\nvoid *run_debugger(void* holder){\n\n (void)holder;\n string inpt;\n \n while(true){\n if (isPaused){\n cout << \">\";\n isPaused = false;\n getline(cin,inpt);\n \/\/react to the input\n parseline(inpt);\n }\n }\n return NULL;\n}\n\n\n\n\/*parses the command line and run the debugger*\/\nvoid parseline(string line){\n\n string build = \"\";\n int wordCount = 1;\n \n int command = NOTHING;\n\n \/*empty input*\/\n if (line == \"\"){\n \/\/enterlast stored command\n debugSend(lastInstruction,lastBuild);\n return;\n }\n\n \/*loop through input line*\/\n for (unsigned int i = 0; i < line.length(); i++){\n \n\n \/*parse line for words*\/\n if (line[i]!=' '){\n build += line[i];\n\n } else {\n \/\/exract the command\n if (wordCount == 1)\n\tcommand = handle_command(build);\n wordCount++;\n build = \"\";\n }\n }\n \n\n \/*no whitespace at all-single word commands*\/\n if (wordCount == 1){\n command = handle_command(build);\n \n if (command != BREAKPOINT && command!=DUMP){\n debugSend(command,\"\");\n lastInstruction = command;\n lastBuild = build;\n return;\n }\n }\n \n \/*if not enough info - these types must have a specification*\/\n if ((command == BREAKPOINT||command == DUMP)&& wordCount == 1){\n cout << \"Please specify- type help for options\" << endl;\n isPaused = true;\n return;\n }\n\n \/*handle breakpoints and dumps*\/\n if (wordCount == 2){\n\tif (command == BREAKPOINT||command == DUMP)\n\t debugSend(command,build);\n\telse \n\t debugSend(command,\"\");\n lastInstruction = command;\n lastBuild = build;\n }\n}\n\n\nint stringType2Int(string type){\n if (type == \"factDer\"){\n return FACTDER;\n } else if (type == \"factCon\"){\n return FACTCON;\n } else if (type == \"factRet\"){\n return FACTRET;\n } else if (type == \"sense\"){\n return SENSE;\n } else if (type == \"action\"){\n return ACTION;\n } else if (type == \"block\"){\n return BLOCK;\n } else { \n cout << \"unknown type-- enter help for options\" << endl;\n return -1;\n }\n}\n\n\n\/*constructs a message to be sent to the Simulator*\/\nvoid debugSend(int command, string build){\n \n int node;\n string name;\n int size;\n int type;\n char* nameSpot;\n\n \n if(command == CONTINUE){\n size = 2*SIZE;\n uint64_t msgCont[size\/SIZE];\n msgCont[0] = size;\n msgCont[1] = DEBUG;\n msgCont[2] = UNPAUSE;\n \/*broadcast unpause to all VMs*\/\n sendMessage(-1,size+SIZE,(uint64_t*)msgCont);\n unPauseSimulation();\n\n } else if (command == BREAKPOINT) {\n if (build[0] == ':'||build[0] == '@'){\n cout << \"Please Specify a Type\" << endl;\n isPaused = true;\n return;\n }\n type = stringType2Int(getType(build));\n if (type == -1){\n isPaused = true;\n return;\n }\n \/*if no node specified broadcast to all*\/\n if (getNode(build) == \"\")\n node = -1;\n else\n node = atoi(getNode(build).c_str());\n name = getName(build);\n size = 3*SIZE + (name.length() + 1) \n + (SIZE - (name.length() + 1)%SIZE);\n uint64_t msgBreak[size\/SIZE];\n msgBreak[0] = size;\n msgBreak[1] = DEBUG;\n msgBreak[2] = BREAKPOINT;\n msgBreak[3] = type;\n nameSpot = (char*)&msgBreak[4];\n memcpy(nameSpot,name.c_str(),name.length()+1);\n sendMessage(node,size+SIZE,(uint64_t*)msgBreak);\n\n } else if (command == DUMP){\n node = atoi(build.c_str());\n size = 2*SIZE;\n uint64_t msgDump[size\/SIZE];\n msgDump[0] = size;\n msgDump[1] = DEBUG;\n msgDump[2] = DUMP;\n sendMessage(node,size+SIZE,(uint64_t*)msgDump);\n\n } else if (command == NOTHING){\n isPaused = true;\n }\n return;\n}\n\t\t \n\t\t \n\n\t \n\n\n\/*recognizes and sets different modes for the debugger*\/\nint handle_command(string command){\n\n int retVal;\n\n if (command == \"break\"){\n retVal = BREAKPOINT;\n } else if (command == \"help\"||command == \"h\") {\n help();\n retVal = NOTHING;\n } else if (command == \"run\"|| command == \"r\") {\n retVal = CONTINUE;\n } else if (command == \"dump\"||command == \"d\") {\n retVal = DUMP;\n } else if (command == \"continue\"||command == \"c\"){\n retVal = CONTINUE;\n } else if (command == \"quit\"||command == \"q\"){\n exit(0);\n } else {\n cout << \"unknown command: type 'help' for options \" << endl;\n retVal = NOTHING;\n }\n return retVal;\n}\n\n\n\/*prints the help screen*\/\nvoid help(){\n cout << endl;\n cout << \"*******************************************************************\" << endl;\n cout << endl;\n cout << \"DEBUGGER HELP\" << endl;\n cout << \"\\t-break - set break point at specified place\" << endl;\n cout << \"\\t\\t-Specification Format:\" << endl;\n cout << \"\\t\\t :@ OR\" << endl;\n cout << \"\\t\\t : OR\" << endl;\n cout << \"\\t\\t @\" << endl;\n cout << \"\\t\\t -type - [factRet|factDer|factCon|action|sense|block]\" << endl;\n cout << \"\\t\\t\\t-a type MUST be specified\" << endl;\n cout << \"\\t\\t -name - the name of certain type ex. the name of a fact\" << endl;\n cout << \"\\t\\t -node - the number of the node\" << endl;\n cout << \"\\t-dump or d - dump the state of the system\" << endl;\n cout << \"\\t-continue or c - continue execution\" << endl;\n cout << \"\\t-run or r - start the program\" << endl;\n cout << \"\\t-quit - exit debugger\" << endl;\n cout << endl;\n cout << \"\\t-Press Enter to use last Input\" << endl;\n cout << endl;\n cout << \"*******************************************************************\" << endl;\n}\n \n\n\n\n \n \n\n \n<|endoftext|>"} {"text":"\/***************************************************************************\n * mng\/test_buf_streams.cpp\n *\n * Part of the STXXL. See http:\/\/stxxl.sourceforge.net\n *\n * Copyright (C) 2002 Roman Dementiev \n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http:\/\/www.boost.org\/LICENSE_1_0.txt)\n **************************************************************************\/\n\n\/\/! \\example mng\/test_streams.cpp\n\/\/! This is an example of use of \\c stxxl::buf_istream and \\c stxxl::buf_ostream\n\n#include \n#include \n#include \n#include \n\n\n#define BLOCK_SIZE (1024 * 512)\n\ntypedef stxxl::typed_block block_type;\ntypedef stxxl::buf_ostream::iterator> buf_ostream_type;\ntypedef stxxl::buf_istream::iterator> buf_istream_type;\n\nint main()\n{\n const unsigned nblocks = 64;\n const unsigned nelements = nblocks * block_type::size;\n stxxl::BIDArray bids(nblocks);\n\n stxxl::block_manager * bm = stxxl::block_manager::get_instance();\n bm->new_blocks(stxxl::striping(), bids.begin(), bids.end());\n {\n buf_ostream_type out(bids.begin(), 2);\n for (unsigned i = 0; i < nelements; i++)\n out << i;\n }\n {\n buf_istream_type in(bids.begin(), bids.end(), 2);\n for (unsigned i = 0; i < nelements; i++)\n {\n int value;\n in >> value;\n if (value != int(i))\n {\n STXXL_ERRMSG(\"Error at position \" << std::hex << i << \" (\" << value << \") block \" << (i \/ block_type::size));\n }\n }\n }\n bm->delete_blocks(bids.begin(), bids.end());\n}\nunmix int\/unsigned\/***************************************************************************\n * mng\/test_buf_streams.cpp\n *\n * Part of the STXXL. See http:\/\/stxxl.sourceforge.net\n *\n * Copyright (C) 2002 Roman Dementiev \n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http:\/\/www.boost.org\/LICENSE_1_0.txt)\n **************************************************************************\/\n\n\/\/! \\example mng\/test_streams.cpp\n\/\/! This is an example of use of \\c stxxl::buf_istream and \\c stxxl::buf_ostream\n\n#include \n#include \n#include \n#include \n\n\n#define BLOCK_SIZE (1024 * 512)\n\ntypedef stxxl::typed_block block_type;\ntypedef stxxl::buf_ostream::iterator> buf_ostream_type;\ntypedef stxxl::buf_istream::iterator> buf_istream_type;\n\nint main()\n{\n const unsigned nblocks = 64;\n const unsigned nelements = nblocks * block_type::size;\n stxxl::BIDArray bids(nblocks);\n\n stxxl::block_manager * bm = stxxl::block_manager::get_instance();\n bm->new_blocks(stxxl::striping(), bids.begin(), bids.end());\n {\n buf_ostream_type out(bids.begin(), 2);\n for (unsigned i = 0; i < nelements; i++)\n out << i;\n }\n {\n buf_istream_type in(bids.begin(), bids.end(), 2);\n for (unsigned i = 0; i < nelements; i++)\n {\n unsigned value;\n in >> value;\n if (value != i)\n {\n STXXL_ERRMSG(\"Error at position \" << std::hex << i << \" (\" << value << \") block \" << (i \/ block_type::size));\n }\n }\n }\n bm->delete_blocks(bids.begin(), bids.end());\n}\n<|endoftext|>"} {"text":"#include \n#include \n\nnamespace lua\n{\n\terror::error(const char* what, int errcode) : std::runtime_error(what), err(errcode)\n\t{\n\t}\n\n\tint error::code()\n\t{\n\t\treturn err;\n\t}\n}\nForgot to add updated doxygen comments to error.cpp#include \n#include \n\nnamespace lua\n{\n\terror::error(const char* what) : std::runtime_error(what)\n\t{\n\t}\n}\n<|endoftext|>"} {"text":"\/**\n *\n * OFDevCon Example Code Sprint\n * Camera Ribbon example\n * This example generates ribbons along the mouse trail that descend in space\n * When you click space bar, you can\n *\n * Created by James George for openFrameworks workshop at Waves Festival Vienna sponsored by Lichterloh and Pratersauna\n * Adapted during ofDevCon on 2\/23\/2012\n *\/\n\n\n#include \"ofApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid ofApp::setup(){\n\t\/\/just set up the openFrameworks stuff\n ofSetFrameRate(60);\n ofSetVerticalSync(true);\n ofBackground(255);\n\n\t\/\/initialize the variable so it's off at the beginning\n usecamera = false;\n\tpointsMax = 1000; \/\/TODO: put this into the GUI\n\n\t\/\/initialize kinect object\n\t\/\/TODO: only initialize necessary sources\n\tkinect.open();\n\tkinect.initDepthSource();\n\tkinect.initColorSource();\n\tkinect.initInfraredSource();\n\tkinect.initBodySource();\n\tkinect.initBodyIndexSource();\n\n\t\/\/set debugging variables\n\tdebugging = false;\/\/TODO: put this into the GUI\n\tpreviewScaleH = 1.0f;\/\/TODO: put this into the GUI\n\tpreviewScaleW = 1.0f;\/\/TODO: put this into the GUI\n\n\t\/\/TODO: setup gui & text instructions for keypresses, etc.\n\t\/\/ change color settings\n\t\/\/ set mode to debugging\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::update(){\n\t\/\/don't move the points if we are using the camera\n if(!usecamera){\n ofVec3f sumOfAllPoints(0,0,0);\n for(unsigned int i = 0; i < points.size(); i++){\n points[i].z -= 4;\n sumOfAllPoints += points[i];\n }\n center = sumOfAllPoints \/ points.size();\n }\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Kinect\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tkinect.update();\n\n\t\/\/--\n\t\/\/Getting joint positions (skeleton tracking)\n\t\/\/--\n\t\/\/\n\t{\n\t\tauto bodies = kinect.getBodySource()->getBodies();\n\t\tfor (auto body : bodies) {\n\t\t\tfor (auto joint : body.joints) {\n\t\t\t\t\/\/TODO: now do something with the joints\n\t\t\t}\n\t\t}\n\t}\n\t\/\/\n\t\/\/--\n\n\n\n\t\/\/--\n\t\/\/Getting bones (connected joints)\n\t\/\/--\n\t\/\/\n\t{\n\t\t\/\/ Note that for this we need a reference of which joints are connected to each other.\n\t\t\/\/ We call this the 'boneAtlas', and you can ask for a reference to this atlas whenever you like\n\t\tauto bodies = kinect.getBodySource()->getBodies();\n\t\tauto boneAtlas = ofxKinectForWindows2::Data::Body::getBonesAtlas();\n\n\t\tfor (auto body : bodies) {\n\t\t\tfor (auto bone : boneAtlas) {\n\t\t\t\tauto firstJointInBone = body.joints[bone.first];\n\t\t\t\tauto secondJointInBone = body.joints[bone.second];\n\n\t\t\t\t\/\/TODO: now do something with the joints\n\t\t\t}\n\t\t}\n\t}\n\t\/\/\n\t\/\/--\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::draw(){\n\n\n\t\/\/if we're using the camera, start it.\n\t\/\/everything that you draw between begin()\/end() shows up from the view of the camera\n if(usecamera){\n camera.begin();\n }\n\n\tofSetColor(0);\n\t\/\/do the same thing from the first example...\n ofMesh mesh;\n\tmesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);\n\tfor(unsigned int i = 1; i < points.size(); i++){\n\n\t\t\/\/find this point and the next point\n\t\tofVec3f thisPoint = points[i-1];\n\t\tofVec3f nextPoint = points[i];\n\n\t\t\/\/get the direction from one to the next.\n\t\t\/\/the ribbon should fan out from this direction\n\t\tofVec3f direction = (nextPoint - thisPoint);\n\n\t\t\/\/get the distance from one point to the next\n\t\tfloat distance = direction.length();\n\n\t\t\/\/get the normalized direction. normalized vectors always have a length of one\n\t\t\/\/and are really useful for representing directions as opposed to something with length\n\t\tofVec3f unitDirection = direction.getNormalized();\n\n\t\t\/\/find both directions to the left and to the right\n\t\tofVec3f toTheLeft = unitDirection.getRotated(-90, ofVec3f(0,0,1));\n\t\tofVec3f toTheRight = unitDirection.getRotated(90, ofVec3f(0,0,1));\n\n\t\t\/\/use the map function to determine the distance.\n\t\t\/\/the longer the distance, the narrower the line.\n\t\t\/\/this makes it look a bit like brush strokes\n\t\tfloat thickness = ofMap(distance, 0, 60, 20, 2, true);\n\n\t\t\/\/calculate the points to the left and to the right\n\t\t\/\/by extending the current point in the direction of left\/right by the length\n\t\tofVec3f leftPoint = thisPoint+toTheLeft*thickness;\n\t\tofVec3f rightPoint = thisPoint+toTheRight*thickness;\n\n\t\t\/\/add these points to the triangle strip\n\t\tmesh.addVertex(ofVec3f(leftPoint.x, leftPoint.y, leftPoint.z));\n\t\tmesh.addVertex(ofVec3f(rightPoint.x, rightPoint.y, rightPoint.z));\n\t}\n\n\t\/\/end the shape\n\tmesh.draw();\n\n\n\t\/\/if we're using the camera, take it away\n if(usecamera){\n \tcamera.end();\n }\n\n\tofPushStyle();\n\t\/\/TODO: move these hardcoded numbers into GUI\n\tofEnableBlendMode(OF_BLENDMODE_SUBTRACT);\n\tofSetColor(127);\n\tif (debugging) {\n\t\tkinect.getDepthSource()->draw(0, 0, previewWidth, previewHeight); \/\/ note that the depth texture is RAW so may appear dark\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \/\/ Color is at 1920x1080 instead of 512x424 so we should fix aspect ratio\n\t\tfloat colorHeight = previewWidth * (kinect.getColorSource()->getHeight() \/ kinect.getColorSource()->getWidth());\n\t\tfloat colorTop = (previewHeight - colorHeight) \/ 2.0;\n\n\t\tkinect.getColorSource()->draw(previewWidth, 0 + colorTop, previewWidth, colorHeight);\n\t\tkinect.getBodySource()->drawProjected(previewWidth, 0 + colorTop, previewWidth, colorHeight);\n\n\t\tkinect.getInfraredSource()->draw(0, previewHeight, previewWidth, previewHeight);\n\n\t\tkinect.getBodyIndexSource()->draw(previewWidth, previewHeight, previewWidth, previewHeight);\n\t\tkinect.getBodySource()->drawProjected(previewWidth, previewHeight, previewWidth, previewHeight, ofxKFW2::ProjectionCoordinates::DepthCamera);\n\t}\n\tofPopStyle();\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyPressed(int key){\n\tswitch (key) {\n\n\tcase ' ':\n\t\t\/\/hitting space key swaps the camera view\n\t\tusecamera = !usecamera;\n\t\tbreak;\n\n\tcase 'd':\n\tcase 'D':\n\t\t\/\/hitting space key swaps the camera view\n\t\tdebugging = !debugging;\n\t\tbreak;\n\n\tcase 'f':\n\tcase 'F':\n\t\t\/\/hitting 'f' key toggles full screen mode\n\t\tofToggleFullscreen();\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyReleased(int key){\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseMoved(int x, int y ){\n\t\/\/if we are using the camera, the mouse moving should rotate it around the whole sculpture\n if(usecamera){\n float rotateAmount = ofMap(ofGetMouseX(), 0, ofGetWidth(), 0, 360);\n ofVec3f furthestPoint;\n if (points.size() > 0) {\n furthestPoint = points[0];\n }\n else\n {\n furthestPoint = ofVec3f(x, y, 0);\n }\n\n ofVec3f directionToFurthestPoint = (furthestPoint - center);\n ofVec3f directionToFurthestPointRotated = directionToFurthestPoint.getRotated(rotateAmount, ofVec3f(0,1,0));\n camera.setPosition(center + directionToFurthestPointRotated);\n camera.lookAt(center);\n }\n\t\/\/otherwise add points like before\n else{\n ofVec3f mousePoint(x,y,0);\n\t\tif (points.size() < pointsMax) {\n\t\t\tpoints.push_back(mousePoint);\n\t\t}\n\t\telse {\n\t\t\tfor (int i = 0; i < pointsMax-1; i++) {\n\t\t\t\tpoints[i] = points[i + 1];\n\t\t\t}\n\t\t\tpoints[pointsMax-1] = mousePoint;\n\t\t}\n }\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseDragged(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mousePressed(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseReleased(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseEntered(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseExited(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::windowResized(int w, int h){\n\tpreviewWidth = ofGetWindowWidth() \/ 2;\n\tpreviewHeight = ofGetWindowHeight() \/ 2;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::gotMessage(ofMessage msg){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::dragEvent(ofDragInfo dragInfo){\n\n}\nA bunch of \"TODO\" comments.\/**\n *\n * OFDevCon Example Code Sprint\n * Camera Ribbon example\n * This example generates ribbons along the mouse trail that descend in space\n * When you click space bar, you can\n *\n * Created by James George for openFrameworks workshop at Waves Festival Vienna sponsored by Lichterloh and Pratersauna\n * Adapted during ofDevCon on 2\/23\/2012\n *\/\n\n\n#include \"ofApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid ofApp::setup(){\n\t\/\/just set up the openFrameworks stuff\n ofSetFrameRate(60);\/\/TODO: put this into the GUI\n ofSetVerticalSync(true);\n ofBackground(255);\/\/TODO: put this into the GUI\n\n\t\/\/initialize the variable so it's off at the beginning\n usecamera = false;\n\tpointsMax = 1000; \/\/TODO: put this into the GUI\n\n\t\/\/initialize kinect object\n\t\/\/TODO: only initialize necessary sources\n\tkinect.open();\n\tkinect.initDepthSource();\n\tkinect.initColorSource();\n\tkinect.initInfraredSource();\n\tkinect.initBodySource();\n\tkinect.initBodyIndexSource();\n\n\t\/\/set debugging variables\n\tdebugging = false;\/\/TODO: put this into the GUI\n\tpreviewScaleH = 1.0f;\/\/TODO: put this into the GUI\n\tpreviewScaleW = 1.0f;\/\/TODO: put this into the GUI\n\n\t\/\/TODO: setup gui & text instructions for keypresses, etc.\n\t\/\/ change color settings\n\t\/\/ set mode to debugging\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::update(){\n\t\/\/don't move the points if we are using the camera\n if(!usecamera){\n ofVec3f sumOfAllPoints(0,0,0);\n for(unsigned int i = 0; i < points.size(); i++){\n points[i].z -= 4;\n sumOfAllPoints += points[i];\n }\n center = sumOfAllPoints \/ points.size();\n }\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Kinect\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tkinect.update();\n\n\t\/\/--\n\t\/\/Getting joint positions (skeleton tracking)\n\t\/\/--\n\t\/\/\n\t{\n\t\tauto bodies = kinect.getBodySource()->getBodies();\n\t\tfor (auto body : bodies) {\n\t\t\tfor (auto joint : body.joints) {\n\t\t\t\t\/\/TODO: now do something with the joints\n\t\t\t}\n\t\t}\n\t}\n\t\/\/\n\t\/\/--\n\n\n\n\t\/\/--\n\t\/\/Getting bones (connected joints)\n\t\/\/--\n\t\/\/\n\t{\n\t\t\/\/ Note that for this we need a reference of which joints are connected to each other.\n\t\t\/\/ We call this the 'boneAtlas', and you can ask for a reference to this atlas whenever you like\n\t\tauto bodies = kinect.getBodySource()->getBodies();\n\t\tauto boneAtlas = ofxKinectForWindows2::Data::Body::getBonesAtlas();\n\n\t\tfor (auto body : bodies) {\n\t\t\tfor (auto bone : boneAtlas) {\n\t\t\t\tauto firstJointInBone = body.joints[bone.first];\n\t\t\t\tauto secondJointInBone = body.joints[bone.second];\n\n\t\t\t\t\/\/TODO: now do something with the joints\n\t\t\t}\n\t\t}\n\t}\n\t\/\/\n\t\/\/--\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::draw(){\n\n\n\t\/\/if we're using the camera, start it.\n\t\/\/everything that you draw between begin()\/end() shows up from the view of the camera\n if(usecamera){\n camera.begin();\n }\n\n\tofSetColor(0);\/\/TODO: put this into the GUI\n\t\/\/do the same thing from the first example...\n ofMesh mesh;\n\tmesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);\n\tfor(unsigned int i = 1; i < points.size(); i++){\n\n\t\t\/\/find this point and the next point\n\t\tofVec3f thisPoint = points[i-1];\n\t\tofVec3f nextPoint = points[i];\n\n\t\t\/\/get the direction from one to the next.\n\t\t\/\/the ribbon should fan out from this direction\n\t\tofVec3f direction = (nextPoint - thisPoint);\n\n\t\t\/\/get the distance from one point to the next\n\t\tfloat distance = direction.length();\n\n\t\t\/\/get the normalized direction. normalized vectors always have a length of one\n\t\t\/\/and are really useful for representing directions as opposed to something with length\n\t\tofVec3f unitDirection = direction.getNormalized();\n\n\t\t\/\/find both directions to the left and to the right\n\t\tofVec3f toTheLeft = unitDirection.getRotated(-90, ofVec3f(0,0,1));\n\t\tofVec3f toTheRight = unitDirection.getRotated(90, ofVec3f(0,0,1));\n\n\t\t\/\/use the map function to determine the distance.\n\t\t\/\/the longer the distance, the narrower the line.\n\t\t\/\/this makes it look a bit like brush strokes\n\t\tfloat thickness = ofMap(distance, 0, 60, 20, 2, true);\/\/TODO: put these constants into the GUI\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \/\/TODO: have tail shrink towards end so it disappears\n\n\t\t\/\/calculate the points to the left and to the right\n\t\t\/\/by extending the current point in the direction of left\/right by the length\n\t\tofVec3f leftPoint = thisPoint+toTheLeft*thickness;\n\t\tofVec3f rightPoint = thisPoint+toTheRight*thickness;\n\n\t\t\/\/add these points to the triangle strip\n\t\tmesh.addVertex(ofVec3f(leftPoint.x, leftPoint.y, leftPoint.z));\n\t\tmesh.addVertex(ofVec3f(rightPoint.x, rightPoint.y, rightPoint.z));\n\t}\n\n\t\/\/end the shape\n\tmesh.draw();\n\n\n\t\/\/if we're using the camera, take it away\n if(usecamera){\n \tcamera.end();\n }\n\n\tofPushStyle();\n\t\/\/TODO: move these hardcoded numbers into GUI\n\tofEnableBlendMode(OF_BLENDMODE_SUBTRACT);\/\/TODO: put this into the GUI\n\tofSetColor(127);\/\/TODO: put this into the GUI\n\tif (debugging) {\n\t\tkinect.getDepthSource()->draw(0, 0, previewWidth, previewHeight); \/\/ note that the depth texture is RAW so may appear dark\n\n\t\tfloat colorHeight = previewWidth * (kinect.getColorSource()->getHeight() \/ kinect.getColorSource()->getWidth());\n\t\tfloat colorTop = (previewHeight - colorHeight) \/ 2.0;\n\t\t\/\/ Color is at 1920x1080 instead of 512x424 so we should fix aspect ratio\n\n\t\tkinect.getColorSource()->draw(previewWidth, 0 + colorTop, previewWidth, colorHeight);\n\t\tkinect.getBodySource()->drawProjected(previewWidth, 0 + colorTop, previewWidth, colorHeight);\n\n\t\tkinect.getInfraredSource()->draw(0, previewHeight, previewWidth, previewHeight);\n\n\t\tkinect.getBodyIndexSource()->draw(previewWidth, previewHeight, previewWidth, previewHeight);\n\t\tkinect.getBodySource()->drawProjected(previewWidth, previewHeight, previewWidth, previewHeight, ofxKFW2::ProjectionCoordinates::DepthCamera);\n\t}\n\tofPopStyle();\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyPressed(int key){\n\tswitch (key) {\n\n\tcase ' ':\n\t\t\/\/hitting space key swaps the camera view\n\t\tusecamera = !usecamera;\n\t\tbreak;\n\n\tcase 'd':\n\tcase 'D':\n\t\t\/\/hitting space key swaps the camera view\n\t\tdebugging = !debugging;\n\t\tbreak;\n\n\tcase 'f':\n\tcase 'F':\n\t\t\/\/hitting 'f' key toggles full screen mode\n\t\tofToggleFullscreen();\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyReleased(int key){\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseMoved(int x, int y ){\n\t\/\/if we are using the camera, the mouse moving should rotate it around the whole sculpture\n if(usecamera){\n float rotateAmount = ofMap(ofGetMouseX(), 0, ofGetWidth(), 0, 360);\/\/TODO: put this into the GUI\n ofVec3f furthestPoint;\n if (points.size() > 0) {\n furthestPoint = points[0];\n }\n else\n {\n furthestPoint = ofVec3f(x, y, 0);\n }\n\n ofVec3f directionToFurthestPoint = (furthestPoint - center);\n ofVec3f directionToFurthestPointRotated = directionToFurthestPoint.getRotated(rotateAmount, ofVec3f(0,1,0));\n camera.setPosition(center + directionToFurthestPointRotated);\n camera.lookAt(center);\n }\n\t\/\/otherwise add points like before\n else{\n ofVec3f mousePoint(x,y,0);\n\t\tif (points.size() < pointsMax) {\n\t\t\tpoints.push_back(mousePoint);\n\t\t}\n\t\telse {\n\t\t\tfor (int i = 0; i < pointsMax-1; i++) {\n\t\t\t\tpoints[i] = points[i + 1];\n\t\t\t}\n\t\t\tpoints[pointsMax-1] = mousePoint;\n\t\t}\n }\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseDragged(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mousePressed(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseReleased(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseEntered(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseExited(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::windowResized(int w, int h){\n\tpreviewWidth = ofGetWindowWidth() \/ 2;\n\tpreviewHeight = ofGetWindowHeight() \/ 2;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::gotMessage(ofMessage msg){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::dragEvent(ofDragInfo dragInfo){\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2017 deepstreamHub GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n\nnamespace deepstream\n{\n\n\nEvent::Event(const SendFn& send) :\n\tsend_(send)\n{\n\tassert( send_ );\n}\n\n\n\nEvent::SubscribeFnPtr Event::subscribe(const Name& name, const SubscribeFn& f)\n{\n\tSubscribeFnPtr p_f( new SubscribeFn(f) );\n\tsubscribe(name, p_f);\n\n\treturn p_f;\n}\n\n\nvoid Event::subscribe(const Name& name, const SubscribeFnPtr& p_f)\n{\n\tassert( p_f );\n\n\tif( name.empty() )\n\t\tthrow std::invalid_argument( \"Empty event subscription pattern\" );\n\n\n\tauto ret = subscriber_map_.equal_range(name);\n\tSubscriberMap::iterator first = ret.first;\n\tSubscriberMap::iterator last = ret.second;\n\n\tif( first != last )\n\t{\n\t\tassert( first != subscriber_map_.end() );\n\t\tassert( first->first == name );\n\t\tassert( std::distance(first, last) == 1 );\n\n\t\t\/\/ avoid inserting duplicates\n\t\tSubscriberList& subscribers = first->second;\n\t\tassert( !subscribers.empty() );\n\n\t\tSubscriberList::const_iterator it =\n\t\t\tstd::find( subscribers.cbegin(), subscribers.cend(), p_f );\n\n\t\tif( it == subscribers.cend() )\n\t\t\tsubscribers.push_back(p_f);\n\n\t\treturn;\n\t}\n\n\tsubscriber_map_[name].push_back(p_f);\n\n\tMessageBuilder message(Topic::EVENT, Action::SUBSCRIBE);\n\tmessage.add_argument( name );\n\tsend_(message);\n}\n\n\nvoid Event::unsubscribe(const Name& name)\n{\n\tSubscriberMap::iterator it = subscriber_map_.find(name);\n\n\tif( it == subscriber_map_.end() )\n\t\treturn;\n\n\tsubscriber_map_.erase(it);\n\n\tMessageBuilder message(Topic::EVENT, Action::UNSUBSCRIBE);\n\tmessage.add_argument(name);\n\tsend_(message);\n}\n\n\nvoid Event::unsubscribe(const Name& name, const SubscribeFnPtr& p_f)\n{\n\tSubscriberMap::iterator it = subscriber_map_.find(name);\n\n\tif( it == subscriber_map_.end() )\n\t\treturn;\n\n\n\tSubscriberList& subscribers = it->second;\n\tSubscriberList::iterator ju =\n\t\tstd::find( subscribers.begin(), subscribers.end(), p_f );\n\n\tif( ju == subscribers.end() )\n\t\treturn;\n\n\tsubscribers.erase(ju);\n\n\tif( subscribers.empty() )\n\t\tunsubscribe(name);\n}\n\n\n\nvoid Event::listen(const std::string& pattern, const ListenFnPtr& p_f)\n{\n\tListenerMap::iterator it = listener_map_.find(pattern);\n\n\tif( it != listener_map_.end() )\n\t\treturn;\n\n\tlistener_map_[pattern] = p_f;\n\n\tMessageBuilder message(Topic::EVENT, Action::LISTEN);\n\tmessage.add_argument(pattern);\n\tsend_(message);\n}\n\n\nvoid Event::unlisten(const std::string& pattern)\n{\n\tListenerMap::iterator it = listener_map_.find(pattern);\n\n\tif( it == listener_map_.end() )\n\t\treturn;\n\n\tlistener_map_.erase(it);\n\n\tMessageBuilder message(Topic::EVENT, Action::UNLISTEN);\n\tmessage.add_argument(pattern);\n\tsend_(message);\n}\n\n\n\nvoid Event::notify_(const Message& message)\n{\n\tassert( message.topic() == Topic::EVENT );\n\n\tswitch( message.action() )\n\t{\n\t\tcase Action::EVENT:\n\t\t\tassert( message.num_arguments() == 2 );\n\t\t\tnotify_subscribers_(\n\t\t\t\tName( message[0].cbegin(), message[0].cend() ),\n\t\t\t\tmessage[1]\n\t\t\t);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tassert(0);\n\t}\n}\n\n\nvoid Event::notify_subscribers_(const Name& name, const Buffer& data)\n{\n\tSubscriberMap::iterator it = subscriber_map_.find(name);\n\n\tif( it == subscriber_map_.end() )\n\t{\n\t\tstd::fprintf(\n\t\t\tstderr, \"E|EVT: no subscriber named '%s'\\n\", name.c_str()\n\t\t);\n\t\treturn;\n\t}\n\n\tassert( it->first == name );\n\n\t\/\/ Copying the list of subscribers is a necessity here because the callbacks\n\t\/\/ may unsubscribe during their execution and modifications of a subscriber\n\t\/\/ list may invalidate iterations and ranges. Also, copying the smart\n\t\/\/ pointer pointer here is a necessity because the referenced function may\n\t\/\/ decide to unsubscribe and in this case, the std::function object must not\n\t\/\/ be destructed. Copying ensures a non-zero reference count until `*p_f`\n\t\/\/ returns.\n\t\/\/ Finally, the iterator `it` may be invalid after executing a callback\n\t\/\/ because the list of subscribers for this `name` may have been erased.\n\tSubscriberList subscribers = it->second;\n\tit = subscriber_map_.end();\n\n\tfor(const SubscribeFnPtr& p_f : subscribers)\n\t{\n\t\tauto f = *p_f;\n\t\tf(data);\n\t}\n}\n\n}\nEvents: fix dangling reference to a temporary\/*\n * Copyright 2017 deepstreamHub GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n\nnamespace deepstream\n{\n\n\nEvent::Event(const SendFn& send) :\n\tsend_(send)\n{\n\tassert( send_ );\n}\n\n\n\nEvent::SubscribeFnPtr Event::subscribe(const Name& name, const SubscribeFn& f)\n{\n\tSubscribeFnPtr p_f( new SubscribeFn(f) );\n\tsubscribe(name, p_f);\n\n\treturn p_f;\n}\n\n\nvoid Event::subscribe(const Name& name, const SubscribeFnPtr& p_f)\n{\n\tassert( p_f );\n\n\tif( name.empty() )\n\t\tthrow std::invalid_argument( \"Empty event subscription pattern\" );\n\n\n\tauto ret = subscriber_map_.equal_range(name);\n\tSubscriberMap::iterator first = ret.first;\n\tSubscriberMap::iterator last = ret.second;\n\n\tif( first != last )\n\t{\n\t\tassert( first != subscriber_map_.end() );\n\t\tassert( first->first == name );\n\t\tassert( std::distance(first, last) == 1 );\n\n\t\t\/\/ avoid inserting duplicates\n\t\tSubscriberList& subscribers = first->second;\n\t\tassert( !subscribers.empty() );\n\n\t\tSubscriberList::const_iterator it =\n\t\t\tstd::find( subscribers.cbegin(), subscribers.cend(), p_f );\n\n\t\tif( it == subscribers.cend() )\n\t\t\tsubscribers.push_back(p_f);\n\n\t\treturn;\n\t}\n\n\tsubscriber_map_[name].push_back(p_f);\n\n\tMessageBuilder message(Topic::EVENT, Action::SUBSCRIBE);\n\tmessage.add_argument( name );\n\tsend_(message);\n}\n\n\nvoid Event::unsubscribe(const Name& name)\n{\n\tSubscriberMap::iterator it = subscriber_map_.find(name);\n\n\tif( it == subscriber_map_.end() )\n\t\treturn;\n\n\tsubscriber_map_.erase(it);\n\n\tMessageBuilder message(Topic::EVENT, Action::UNSUBSCRIBE);\n\tmessage.add_argument(name);\n\tsend_(message);\n}\n\n\nvoid Event::unsubscribe(const Name& name, const SubscribeFnPtr& p_f)\n{\n\tSubscriberMap::iterator it = subscriber_map_.find(name);\n\n\tif( it == subscriber_map_.end() )\n\t\treturn;\n\n\n\tSubscriberList& subscribers = it->second;\n\tSubscriberList::iterator ju =\n\t\tstd::find( subscribers.begin(), subscribers.end(), p_f );\n\n\tif( ju == subscribers.end() )\n\t\treturn;\n\n\tsubscribers.erase(ju);\n\n\tif( subscribers.empty() )\n\t\tunsubscribe(name);\n}\n\n\n\nvoid Event::listen(const std::string& pattern, const ListenFnPtr& p_f)\n{\n\tListenerMap::iterator it = listener_map_.find(pattern);\n\n\tif( it != listener_map_.end() )\n\t\treturn;\n\n\tlistener_map_[pattern] = p_f;\n\n\tMessageBuilder message(Topic::EVENT, Action::LISTEN);\n\tmessage.add_argument(pattern);\n\tsend_(message);\n}\n\n\nvoid Event::unlisten(const std::string& pattern)\n{\n\tListenerMap::iterator it = listener_map_.find(pattern);\n\n\tif( it == listener_map_.end() )\n\t\treturn;\n\n\tlistener_map_.erase(it);\n\n\tMessageBuilder message(Topic::EVENT, Action::UNLISTEN);\n\tmessage.add_argument(pattern);\n\tsend_(message);\n}\n\n\n\nvoid Event::notify_(const Message& message)\n{\n\tassert( message.topic() == Topic::EVENT );\n\n\tconst Buffer& arg0 = message[0];\n\tName name( arg0.cbegin(), arg0.cend() );\n\n\tswitch( message.action() )\n\t{\n\t\tcase Action::EVENT:\n\t\t\tassert( message.num_arguments() == 2 );\n\t\t\tnotify_subscribers_( name, message[1] );\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tassert(0);\n\t}\n}\n\n\nvoid Event::notify_subscribers_(const Name& name, const Buffer& data)\n{\n\tSubscriberMap::iterator it = subscriber_map_.find(name);\n\n\tif( it == subscriber_map_.end() )\n\t{\n\t\tstd::fprintf(\n\t\t\tstderr, \"E|EVT: no subscriber named '%s'\\n\", name.c_str()\n\t\t);\n\t\treturn;\n\t}\n\n\tassert( it->first == name );\n\n\t\/\/ Copying the list of subscribers is a necessity here because the callbacks\n\t\/\/ may unsubscribe during their execution and modifications of a subscriber\n\t\/\/ list may invalidate iterations and ranges. Also, copying the smart\n\t\/\/ pointer pointer here is a necessity because the referenced function may\n\t\/\/ decide to unsubscribe and in this case, the std::function object must not\n\t\/\/ be destructed. Copying ensures a non-zero reference count until `*p_f`\n\t\/\/ returns.\n\t\/\/ Finally, the iterator `it` may be invalid after executing a callback\n\t\/\/ because the list of subscribers for this `name` may have been erased.\n\tSubscriberList subscribers = it->second;\n\tit = subscriber_map_.end();\n\n\tfor(const SubscribeFnPtr& p_f : subscribers)\n\t{\n\t\tauto f = *p_f;\n\t\tf(data);\n\t}\n}\n\n}\n<|endoftext|>"} {"text":"some code simplifications<|endoftext|>"} {"text":"#include \r\n#include \r\n\r\n#include \r\n\r\nusing namespace mix;\r\n\r\nnamespace {\r\n\r\nCommand MakeSTA(int address, const WordField& field = Word::MaxField(), std::size_t index_register = 0)\r\n{\r\n\treturn Command{24, address, index_register, field};\r\n}\r\n\r\nCommand MakeLDA(int address, const WordField& field = Word::MaxField(), std::size_t index_register = 0)\r\n{\r\n\treturn Command{8, address, index_register, field};\r\n}\r\n\r\nCommand MakeADD(int address, const WordField& field = Word::MaxField(), std::size_t index_register = 0)\r\n{\r\n\treturn Command{1, address, index_register, field};\r\n}\r\n\r\nclass ADD_TAOCP_Book_Test : public ::testing::Test\r\n{\r\nprivate:\r\n\tvoid SetUp() override\r\n\t{\r\n\t\tRegister ra;\r\n\t\tra.set_byte(1, Byte{1});\r\n\t\tra.set_byte(2, Byte{1});\r\n\t\tra.set_byte(3, Byte{1});\r\n\t\tra.set_byte(4, Byte{1});\r\n\t\tra.set_byte(5, Byte{1});\r\n\t\tmix.set_ra(ra);\r\n\t}\r\n\r\nprotected:\r\n\tComputer mix;\r\n};\r\n\r\n} \/\/ namespace\r\n\r\nTEST_F(ADD_TAOCP_Book_Test, Register_A_Bytes_Sum)\r\n{\r\n\tmix.execute(MakeSTA(2000));\r\n\tmix.execute(MakeLDA(2000, WordField{5, 5}));\r\n\r\n\tmix.execute(MakeADD(2000, WordField{4, 4}));\r\n\tmix.execute(MakeADD(2000, WordField{3, 3}));\r\n\tmix.execute(MakeADD(2000, WordField{2, 2}));\r\n\tmix.execute(MakeADD(2000, WordField{1, 1}));\r\n\r\n\tASSERT_EQ(5, mix.ra().value());\r\n}\r\nAdd second example of ADD from TAOCP#include \r\n#include \r\n\r\n#include \r\n\r\nusing namespace mix;\r\n\r\nnamespace {\r\n\r\nCommand MakeSTA(int address, const WordField& field = Word::MaxField(), std::size_t index_register = 0)\r\n{\r\n\treturn Command{24, address, index_register, field};\r\n}\r\n\r\nCommand MakeLDA(int address, const WordField& field = Word::MaxField(), std::size_t index_register = 0)\r\n{\r\n\treturn Command{8, address, index_register, field};\r\n}\r\n\r\nCommand MakeADD(int address, const WordField& field = Word::MaxField(), std::size_t index_register = 0)\r\n{\r\n\treturn Command{1, address, index_register, field};\r\n}\r\n} \/\/ namespace\r\n\r\nTEST(ADD_TAOCP_Book_Test, Register_A_Bytes_Sum)\r\n{\r\n\tComputer mix;\r\n\r\n\t{\r\n\t\tRegister ra;\r\n\t\tra.set_byte(1, Byte{1});\r\n\t\tra.set_byte(2, Byte{1});\r\n\t\tra.set_byte(3, Byte{1});\r\n\t\tra.set_byte(4, Byte{1});\r\n\t\tra.set_byte(5, Byte{1});\r\n\t\tmix.set_ra(ra);\r\n\t}\r\n\r\n\tmix.execute(MakeSTA(2000));\r\n\tmix.execute(MakeLDA(2000, WordField{5, 5}));\r\n\r\n\tmix.execute(MakeADD(2000, WordField{4, 4}));\r\n\tmix.execute(MakeADD(2000, WordField{3, 3}));\r\n\tmix.execute(MakeADD(2000, WordField{2, 2}));\r\n\tmix.execute(MakeADD(2000, WordField{1, 1}));\r\n\r\n\tconst auto result = mix.ra().value();\r\n\tconst auto expected_result = 1 * 5;\r\n\tASSERT_EQ(expected_result, result);\r\n}\r\n\r\nTEST(ADD_TAOCP_Book_Test, Simple_Addition)\r\n{\r\n\tComputer mix;\r\n\r\n\t{\r\n\t\tRegister ra;\r\n\t\tra.set_value(1234, WordField{0, 2});\r\n\t\tra.set_byte(3, Byte{1});\r\n\t\tra.set_value(150, WordField{4, 5});\r\n\t\tmix.set_ra(ra);\r\n\t}\r\n\r\n\t{\r\n\t\tWord w;\r\n\t\tw.set_value(100, WordField{0, 2});\r\n\t\tw.set_byte(3, Byte{5});\r\n\t\tw.set_value(50, WordField{4, 5});\r\n\t\tmix.set_memory(1000, w);\r\n\t}\r\n\r\n\tmix.execute(MakeADD(1000));\r\n\r\n\t{\r\n\t\tASSERT_EQ(1334, mix.ra().value(WordField{0, 2}));\r\n\t\tASSERT_EQ(6, mix.ra().value(WordField{3, 3}));\r\n\t\tASSERT_EQ(200, mix.ra().value(WordField{4, 5}));\r\n\t}\r\n}\r\n\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"client.h\"\n#include \"duckchat.h\"\n\n\/\/ Variables\nstruct sockaddr_in client_addr;\nstruct sockaddr_in server_addr;\nint client_socket;\nstruct addrinfo *server_info;\nchar *channel;\n\n\n\/\/ Prints an error message and exits the program.\nvoid Error(const char *msg) {\n std::cerr << msg << std::endl;\n exit(1);\n}\n\n\n\/\/ Connects to the server at a the given port.\nvoid Connect(char *domain, const char *port) {\n std::cout << \"Connecting to \" << domain << std::endl;\n\n struct addrinfo hints;\n struct addrinfo *server_info_tmp;\n int status;\n\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_DGRAM;\n hints.ai_protocol = 0;\n\n if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) {\n std::cerr << \"client: unable to resolve address: \" << gai_strerror(status) << std::endl;\n exit(1);\n }\n\n \/\/ getaddrinfo() returns a list of address structures into server_info_tmp.\n \/\/ Try each address until we successfully connect().\n \/\/ If socket() (or connect()) fails, close the socket and try the next address.\n\n for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) {\n if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) {\n continue;\n }\n if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) {\n fcntl(client_socket, F_SETFL, O_NONBLOCK);\n break; \/\/ Success\n }\n close(client_socket);\n }\n\n\n\n if (server_info == NULL) {\n Error(\"client: all sockets failed to connect\");\n }\n}\n\n\n\/\/ Sends a message to all users in on the active channel.\nint RequestSay(const char *message) {\n struct request_say say;\n memset(&say, 0, sizeof(say));\n say.req_type = REQ_SAY;\n strncpy(say.req_text, message, SAY_MAX);\n strncpy(say.req_channel, channel, CHANNEL_MAX);\n\n if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to send message\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends login requests to the server.\nint RequestLogin(char *username) {\n struct request_login login;\n memset(&login, 0, sizeof(login));\n login.req_type = REQ_LOGIN;\n strncpy(login.req_username, username, USERNAME_MAX);\n\n size_t message_size = sizeof(struct request_login);\n\n if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request login\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends logout requests to the server.\nint RequestLogout() {\n struct request_logout logout;\n memset((char *) &logout, 0, sizeof(logout));\n logout.req_type = REQ_LOGOUT;\n\n size_t message_size = sizeof(struct request_logout);\n\n if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request logout\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends join requests to the server.\nint RequestJoin(char *channel) {\n struct request_join join;\n memset((char *) &join, 0, sizeof(join));\n join.req_type = REQ_JOIN;\n strncpy(join.req_channel, channel, CHANNEL_MAX);\n\n size_t message_size = sizeof(struct request_join);\n\n if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request join\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector StringSplit(std::string input) {\n std::istringstream iss(input);\n std::vector result{std::istream_iterator{iss}, std::istream_iterator{}};\n\n return result;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector SplitString(std::string input, char delimiter) {\n std::vector result;\n std::string word = \"\";\n\n for (char c : input) {\n if (c != delimiter) {\n word += c;\n } else {\n result.push_back(word);\n word = \"\";\n }\n }\n result.push_back(word);\n\n return result;\n}\n\n\n\/\/ Processes the input string to decide what type of command it is.\nbool ProcessInput(std::string input) {\n std::vector inputs = StringSplit(input);\n bool result = true;\n\n if (inputs[0] == \"\/exit\") {\n RequestLogout();\n result = false;\n } else if (inputs[0] == \"\/list\") {\n\n } else if (inputs[0] == \"\/join\") {\n\n } else if (inputs[0] == \"\/leave\") {\n\n } else if (inputs[0] == \"\/who\") {\n\n } else if (inputs[0] == \"\/switch\") {\n\n } else {\n std::cout << \"Invalid command\" << std::endl;\n }\n\n return result;\n}\n\n\nint main(int argc, char *argv[]) {\n char *domain;\n char *port_str;\n int port_num;\n char *username;\n std::string input;\n\n struct timeval timeout;\n fd_set read_set;\n int file_desc = 0;\n int result;\n char receive_buffer[SAY_MAX];\n memset(&receive_buffer, 0, SAY_MAX);\n\n if (argc < 4) {\n Error(\"usage: client [server name] [port] [username]\");\n }\n\n domain = argv[1];\n port_str = argv[2];\n port_num = atoi(argv[2]);\n username = argv[3];\n\n if (strlen(domain) > UNIX_PATH_MAX) {\n Error(\"client: server name must be less than 108 characters\");\n }\n\n if (port_num < 0 || port_num > 65535) {\n Error(\"client: port number must be between 0 and 65535\");\n }\n\n if (strlen(username) > USERNAME_MAX) {\n Error(\"client: username must be less than 32 characters\");\n }\n\n Connect(domain, port_str);\n\n RequestLogin(username);\n\n channel = (char *) \"Common\";\n RequestJoin(channel);\n\n \/\/ TODO handle response from send\n\n while(1) {\n FD_ZERO(&read_set);\n FD_SET(file_desc, &read_set);\n\n timeout.tv_sec = 0; \/\/ TODO change time value?\n timeout.tv_usec = 0;\n\n\/\/ if ((result = select(file_desc + 1, &read_set, NULL, NULL, NULL)) < 0) {\n\/\/ continue;\n\/\/ }\n if ((result = select(file_desc + 1, &read_set, NULL, NULL, &timeout)) < 0) {\n Error(\"client: problem using select\");\n }\n\n\/\/ size_t size = sizeof(receive_buffer);\n\n\/\/ std::cout << \"past select, result: \" << result << std::endl;\n\n if (result > 0) {\n if (FD_ISSET(file_desc, &read_set)) {\n \/\/ Socket has data\n result = read(client_socket, receive_buffer, sizeof(receive_buffer));\n }\n\n if (result == 0) {\n close(file_desc);\n } else {\n \/\/ TODO capture user input, store, clean input, then print buffer, afterward replace input\n std::cout << \"[\" << channel << \"]\" << \"[\" << username << \"]: \" << receive_buffer << std::endl;\n }\n }\n\n\/\/ std::cout << \"past check result\" << std::endl;\n\n\/\/ std::cout << \"> \";\n\/\/ getline(std::cin, input);\n\/\/\n\/\/ if (input[0] == '\/') {\n\/\/ if (!ProcessInput(input)) {\n\/\/ break;\n\/\/ }\n\/\/ } else {\n\/\/ \/\/ Send chat messages\n\/\/ RequestSay(input.c_str());\n\/\/ std::cout << \"[\" << channel << \"]\" << \"[\" << username << \"]: \" << input << std::endl;\n\/\/ }\n\n std::cout << \"> \";\n getline(std::cin, input);\n\n if (input[0] == '\/') {\n if (!ProcessInput(input)) {\n break;\n }\n } else {\n \/\/ Send chat messages\n RequestSay(input.c_str());\n std::cout << \"[\" << channel << \"]\" << \"[\" << username << \"]: \" << input << std::endl;\n }\n\n\/\/ if (FD_ISSET(STDIN_FILENO, &read_set)) {\n\/\/ std::cout << \"> \";\n\/\/ getline(std::cin, input);\n\/\/\n\/\/ if (input[0] == '\/') {\n\/\/ if (!ProcessInput(input)) {\n\/\/ break;\n\/\/ }\n\/\/ } else {\n\/\/ \/\/ Send chat messages\n\/\/ RequestSay(input.c_str());\n\/\/ std::cout << \"[\" << channel << \"]\" << \"[\" << username << \"]: \" << input << std::endl;\n\/\/ }\n\/\/ }\n\n\/\/ std::cout << \"past getline\" << std::endl;\n\n }\n\n return 0;\n}fd_set read_set; read -> recv;#include \n#include \n#include \n\n#include \"client.h\"\n#include \"duckchat.h\"\n\n\/\/ Variables\nstruct sockaddr_in client_addr;\nstruct sockaddr_in server_addr;\nint client_socket;\nstruct addrinfo *server_info;\nchar *channel;\n\n\n\/\/ Prints an error message and exits the program.\nvoid Error(const char *msg) {\n std::cerr << msg << std::endl;\n exit(1);\n}\n\n\n\/\/ Connects to the server at a the given port.\nvoid Connect(char *domain, const char *port) {\n std::cout << \"Connecting to \" << domain << std::endl;\n\n struct addrinfo hints;\n struct addrinfo *server_info_tmp;\n int status;\n\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_DGRAM;\n hints.ai_protocol = 0;\n\n if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) {\n std::cerr << \"client: unable to resolve address: \" << gai_strerror(status) << std::endl;\n exit(1);\n }\n\n \/\/ getaddrinfo() returns a list of address structures into server_info_tmp.\n \/\/ Try each address until we successfully connect().\n \/\/ If socket() (or connect()) fails, close the socket and try the next address.\n\n for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) {\n if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) {\n continue;\n }\n if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) {\n fcntl(client_socket, F_SETFL, O_NONBLOCK);\n break; \/\/ Success\n }\n close(client_socket);\n }\n\n\n\n if (server_info == NULL) {\n Error(\"client: all sockets failed to connect\");\n }\n}\n\n\n\/\/ Sends a message to all users in on the active channel.\nint RequestSay(const char *message) {\n struct request_say say;\n memset(&say, 0, sizeof(say));\n say.req_type = REQ_SAY;\n strncpy(say.req_text, message, SAY_MAX);\n strncpy(say.req_channel, channel, CHANNEL_MAX);\n\n if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to send message\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends login requests to the server.\nint RequestLogin(char *username) {\n struct request_login login;\n memset(&login, 0, sizeof(login));\n login.req_type = REQ_LOGIN;\n strncpy(login.req_username, username, USERNAME_MAX);\n\n size_t message_size = sizeof(struct request_login);\n\n if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request login\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends logout requests to the server.\nint RequestLogout() {\n struct request_logout logout;\n memset((char *) &logout, 0, sizeof(logout));\n logout.req_type = REQ_LOGOUT;\n\n size_t message_size = sizeof(struct request_logout);\n\n if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request logout\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends join requests to the server.\nint RequestJoin(char *channel) {\n struct request_join join;\n memset((char *) &join, 0, sizeof(join));\n join.req_type = REQ_JOIN;\n strncpy(join.req_channel, channel, CHANNEL_MAX);\n\n size_t message_size = sizeof(struct request_join);\n\n if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request join\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector StringSplit(std::string input) {\n std::istringstream iss(input);\n std::vector result{std::istream_iterator{iss}, std::istream_iterator{}};\n\n return result;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector SplitString(std::string input, char delimiter) {\n std::vector result;\n std::string word = \"\";\n\n for (char c : input) {\n if (c != delimiter) {\n word += c;\n } else {\n result.push_back(word);\n word = \"\";\n }\n }\n result.push_back(word);\n\n return result;\n}\n\n\n\/\/ Processes the input string to decide what type of command it is.\nbool ProcessInput(std::string input) {\n std::vector inputs = StringSplit(input);\n bool result = true;\n\n if (inputs[0] == \"\/exit\") {\n RequestLogout();\n result = false;\n } else if (inputs[0] == \"\/list\") {\n\n } else if (inputs[0] == \"\/join\") {\n\n } else if (inputs[0] == \"\/leave\") {\n\n } else if (inputs[0] == \"\/who\") {\n\n } else if (inputs[0] == \"\/switch\") {\n\n } else {\n std::cout << \"Invalid command\" << std::endl;\n }\n\n return result;\n}\n\n\nint main(int argc, char *argv[]) {\n char *domain;\n char *port_str;\n int port_num;\n char *username;\n std::string input;\n\n struct timeval timeout;\n fd_set read_set;\n int file_desc = 0;\n int result;\n char receive_buffer[SAY_MAX];\n memset(&receive_buffer, 0, SAY_MAX);\n\n if (argc < 4) {\n Error(\"usage: client [server name] [port] [username]\");\n }\n\n domain = argv[1];\n port_str = argv[2];\n port_num = atoi(argv[2]);\n username = argv[3];\n\n if (strlen(domain) > UNIX_PATH_MAX) {\n Error(\"client: server name must be less than 108 characters\");\n }\n\n if (port_num < 0 || port_num > 65535) {\n Error(\"client: port number must be between 0 and 65535\");\n }\n\n if (strlen(username) > USERNAME_MAX) {\n Error(\"client: username must be less than 32 characters\");\n }\n\n Connect(domain, port_str);\n\n RequestLogin(username);\n\n channel = (char *) \"Common\";\n RequestJoin(channel);\n\n \/\/ TODO handle response from send\n\n while(1) {\n FD_ZERO(&read_set);\n FD_SET(file_desc, &read_set);\n FD_SET(STDIN_FILENO, &read_set);\n\n timeout.tv_sec = 0; \/\/ TODO change time value?\n timeout.tv_usec = 0;\n\n\/\/ if ((result = select(file_desc + 1, &read_set, NULL, NULL, NULL)) < 0) {\n\/\/ continue;\n\/\/ }\n if ((result = select(file_desc + 1, &read_set, NULL, NULL, &timeout)) < 0) {\n Error(\"client: problem using select\");\n }\n\n\/\/ size_t size = sizeof(receive_buffer);\n\n\/\/ std::cout << \"past select, result: \" << result << std::endl;\n\n if (result > 0) {\n if (FD_ISSET(file_desc, &read_set)) {\n \/\/ Socket has data\n result = recv(file_desc, receive_buffer, sizeof(receive_buffer), 0);\n\n FD_CLR(file_desc, &read_set);\n memset(&receive_buffer, 0, SAY_MAX);\n\n if (result == 0) {\n close(file_desc);\n } else {\n \/\/ TODO capture user input, store, clean input, then print buffer, afterward replace input\n std::cout << \"[\" << channel << \"]\" << \"[\" << username << \"]: \" << receive_buffer << std::endl;\n }\n }\n }\n\n\/\/ std::cout << \"past check result\" << std::endl;\n\n\/\/ std::cout << \"> \";\n\/\/ getline(std::cin, input);\n\/\/\n\/\/ if (input[0] == '\/') {\n\/\/ if (!ProcessInput(input)) {\n\/\/ break;\n\/\/ }\n\/\/ } else {\n\/\/ \/\/ Send chat messages\n\/\/ RequestSay(input.c_str());\n\/\/ std::cout << \"[\" << channel << \"]\" << \"[\" << username << \"]: \" << input << std::endl;\n\/\/ }\n\n if (FD_ISSET(STDIN_FILENO, &read_set)) {\n std::cout << \"> \";\n getline(std::cin, input);\n\n if (input[0] == '\/') {\n if (!ProcessInput(input)) {\n break;\n }\n } else {\n \/\/ Send chat messages\n RequestSay(input.c_str());\n std::cout << \"[\" << channel << \"]\" << \"[\" << username << \"]: \" << input << std::endl;\n }\n }\n\n\/\/ std::cout << \"past getline\" << std::endl;\n\n }\n\n return 0;\n}<|endoftext|>"} {"text":"\/***********************************************************************\n test_uds.cpp - Tests the Unix domain socket verifier in\n \tUnixDomainSocketConnection. This test always succeeds on Windows!\n\n Copyright (c) 2007 by Educational Technology Resources, Inc.\n Others may also hold copyrights on code in this file. See the\n CREDITS file in the top directory of the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#include \n\n#include \n#include \n#include \n\n#if !defined(MYSQLPP_PLATFORM_WINDOWS)\n#include \n#include \n#include \n#include \n\n#include \n\nstatic const char* success_path = \"test_uds_success.sock\";\nstatic const char* failure_path = \"test_uds_failure.sock\";\n\nstatic int\nmake_socket(const char* path, mode_t mode)\n{\n\t\/\/ Just in case a socket with this name exists already, try to\n\t\/\/ remove it. Only a failure if it exists and we can't remove it.\n\tif ((unlink(path) < 0) && (errno != ENOENT)) {\n\t\treturn -1;\n\t}\n\n\t\/\/ Create the domain socket\n\tint fd = socket(AF_LOCAL, SOCK_STREAM, 0);\n\tif (fd < 0) {\n\t\treturn -1;\n\t}\n\t\n\t\/\/ Bind the socket to the named file\n\tstruct sockaddr_un sun;\n\tmemset(&sun, sizeof(sun), 0);\n\tsun.sun_family = AF_LOCAL;\n\tstrncpy(sun.sun_path, path, sizeof(sun.sun_path));\n\tsun.sun_path[sizeof(sun.sun_path) - 1] = '\\0';\n\tif (bind(fd, (sockaddr*)&sun, sizeof(sun)) < 0) {\n\t\treturn -1;\n\t}\n\n\t\/\/ Change the socket's mode as requested\n\tif (chmod(path, mode) < 0) {\n\t\treturn -1;\n\t}\n\n\treturn fd;\n}\n\n\t\nstatic void\ntest_success()\n{\n\tstd::string error;\n\tint fd = make_socket(success_path, S_IREAD | S_IWRITE);\n\tif (fd >= 0) {\n\t\tbool fail = !mysqlpp::UnixDomainSocketConnection::is_socket(\n\t\t\t\tsuccess_path, &error);\n\t\tif (fail) {\n\t\t\tthrow mysqlpp::SelfTestFailed(error);\n\t\t}\n\t}\n\telse {\n\t\tstd::ostringstream outs;\n\t\touts << \"Failed to create test domain socket: \" << strerror(errno);\n\t\tthrow mysqlpp::SelfTestFailed(outs.str());\n\t}\n}\n\n\nstatic void\ntest_failure()\n{\n\tint fd = make_socket(failure_path, S_IREAD);\n\tif (fd < 0) {\n\t\tstd::ostringstream outs;\n\t\touts << \"Failed to create test domain socket: \" << strerror(errno);\n\t\tthrow mysqlpp::SelfTestFailed(outs.str());\n\t}\n\n\tif (mysqlpp::UnixDomainSocketConnection::is_socket(failure_path)) {\n\t\tthrow mysqlpp::SelfTestFailed(\"Failed to fail on read-only socket\");\n\t}\n\telse if (mysqlpp::UnixDomainSocketConnection::is_socket(\n\t\t\t\"BogusBogus.sock\")) {\n\t\tthrow mysqlpp::SelfTestFailed(\"Failed to fail on bad file name\");\n\t}\n\telse {\n\t\tclose(fd);\n\t\tunlink(failure_path);\n\t\tfd = creat(failure_path, S_IREAD | S_IWRITE);\n\t\tbool success = mysqlpp::UnixDomainSocketConnection::is_socket(\n\t\t\t\tfailure_path);\n\t\tif (success) {\n\t\t\tthrow mysqlpp::SelfTestFailed(\"Failed to fail on non-socket\");\n\t\t}\n\t}\n}\n#endif\n\n\nint\nmain()\n{\n#if defined(MYSQLPP_PLATFORM_WINDOWS)\n\t\/\/ Test not appropriate to this platform. Always succeed.\n\treturn 0;\n#else\n\ttry {\n\t\ttest_success();\n\t\tunlink(success_path);\n\t\ttest_failure();\n\t\tunlink(failure_path);\n\t\treturn 0;\n\t}\n\tcatch (mysqlpp::SelfTestFailed& e) {\n\t\tstd::cerr << \"TCP address parse error: \" << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\tcatch (std::exception& e) {\n\t\tstd::cerr << \"Unexpected test failure: \" << e.what() << std::endl;\n\t\treturn 2;\n\t}\n#endif\n}\n#include fix for OS X\/***********************************************************************\n test_uds.cpp - Tests the Unix domain socket verifier in\n \tUnixDomainSocketConnection. This test always succeeds on Windows!\n\n Copyright (c) 2007 by Educational Technology Resources, Inc.\n Others may also hold copyrights on code in this file. See the\n CREDITS file in the top directory of the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#include \n\n#include \n#include \n#include \n\n#if !defined(MYSQLPP_PLATFORM_WINDOWS)\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nstatic const char* success_path = \"test_uds_success.sock\";\nstatic const char* failure_path = \"test_uds_failure.sock\";\n\nstatic int\nmake_socket(const char* path, mode_t mode)\n{\n\t\/\/ Just in case a socket with this name exists already, try to\n\t\/\/ remove it. Only a failure if it exists and we can't remove it.\n\tif ((unlink(path) < 0) && (errno != ENOENT)) {\n\t\treturn -1;\n\t}\n\n\t\/\/ Create the domain socket\n\tint fd = socket(AF_LOCAL, SOCK_STREAM, 0);\n\tif (fd < 0) {\n\t\treturn -1;\n\t}\n\t\n\t\/\/ Bind the socket to the named file\n\tstruct sockaddr_un sun;\n\tmemset(&sun, sizeof(sun), 0);\n\tsun.sun_family = AF_LOCAL;\n\tstrncpy(sun.sun_path, path, sizeof(sun.sun_path));\n\tsun.sun_path[sizeof(sun.sun_path) - 1] = '\\0';\n\tif (bind(fd, (sockaddr*)&sun, sizeof(sun)) < 0) {\n\t\treturn -1;\n\t}\n\n\t\/\/ Change the socket's mode as requested\n\tif (chmod(path, mode) < 0) {\n\t\treturn -1;\n\t}\n\n\treturn fd;\n}\n\n\t\nstatic void\ntest_success()\n{\n\tstd::string error;\n\tint fd = make_socket(success_path, S_IREAD | S_IWRITE);\n\tif (fd >= 0) {\n\t\tbool fail = !mysqlpp::UnixDomainSocketConnection::is_socket(\n\t\t\t\tsuccess_path, &error);\n\t\tif (fail) {\n\t\t\tthrow mysqlpp::SelfTestFailed(error);\n\t\t}\n\t}\n\telse {\n\t\tstd::ostringstream outs;\n\t\touts << \"Failed to create test domain socket: \" << strerror(errno);\n\t\tthrow mysqlpp::SelfTestFailed(outs.str());\n\t}\n}\n\n\nstatic void\ntest_failure()\n{\n\tint fd = make_socket(failure_path, S_IREAD);\n\tif (fd < 0) {\n\t\tstd::ostringstream outs;\n\t\touts << \"Failed to create test domain socket: \" << strerror(errno);\n\t\tthrow mysqlpp::SelfTestFailed(outs.str());\n\t}\n\n\tif (mysqlpp::UnixDomainSocketConnection::is_socket(failure_path)) {\n\t\tthrow mysqlpp::SelfTestFailed(\"Failed to fail on read-only socket\");\n\t}\n\telse if (mysqlpp::UnixDomainSocketConnection::is_socket(\n\t\t\t\"BogusBogus.sock\")) {\n\t\tthrow mysqlpp::SelfTestFailed(\"Failed to fail on bad file name\");\n\t}\n\telse {\n\t\tclose(fd);\n\t\tunlink(failure_path);\n\t\tfd = creat(failure_path, S_IREAD | S_IWRITE);\n\t\tbool success = mysqlpp::UnixDomainSocketConnection::is_socket(\n\t\t\t\tfailure_path);\n\t\tif (success) {\n\t\t\tthrow mysqlpp::SelfTestFailed(\"Failed to fail on non-socket\");\n\t\t}\n\t}\n}\n#endif\n\n\nint\nmain()\n{\n#if defined(MYSQLPP_PLATFORM_WINDOWS)\n\t\/\/ Test not appropriate to this platform. Always succeed.\n\treturn 0;\n#else\n\ttry {\n\t\ttest_success();\n\t\tunlink(success_path);\n\t\ttest_failure();\n\t\tunlink(failure_path);\n\t\treturn 0;\n\t}\n\tcatch (mysqlpp::SelfTestFailed& e) {\n\t\tstd::cerr << \"TCP address parse error: \" << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\tcatch (std::exception& e) {\n\t\tstd::cerr << \"Unexpected test failure: \" << e.what() << std::endl;\n\t\treturn 2;\n\t}\n#endif\n}\n<|endoftext|>"} {"text":"#include \"Halide.h\"\n\nusing namespace Halide;\n\nint main(int argc, char** argv) {\n ImageParam input(UInt(32), 3, \"input\");\n input.dim(2).set_bounds(0, 4).set_stride(1).dim(0).set_stride(4);\n\n Var x, y, c;\n Func f(\"f\");\n f(x, y, c) = input(x, y, c) + 1;\n f.bound(c, 0, 4)\n .reorder_storage(c, x, y)\n .reorder(c, x, y);\n\n f.compute_root();\n f.output_buffer().dim(2).set_bounds(0, 4).set_stride(1).dim(0).set_stride(4);\n\n Target target = get_target_from_environment();\n if (target.has_gpu_feature() || target.has_feature(Target::OpenGLCompute)) {\n f.unroll(c)\n .gpu_tile(x, y, 64, 64);\n }\n\n Func g(\"g\");\n g(x, y, c) = f(x, y, c) - 1;\n g.bound(c, 0, CHANNELS)\n .reorder_storage(c, x, y)\n .reorder(c, x, y);\n if (target.has_gpu_feature() || target.has_feature(Target::OpenGLCompute)) {\n g.unroll(c)\n .gpu_tile(x, y, 64, 64);\n }\n g.output_buffer().dim(2).set_bounds(0, 4).set_stride(1).dim(0).set_stride(4);\n\n std::string fn_name = std::string(\"two_kernels_filter\") + (argc > 1 ? argv[1] : \"\");\n g.compile_to_file(fn_name, {input}, fn_name);\n}\nFix last commit#include \"Halide.h\"\n\nusing namespace Halide;\n\nint main(int argc, char** argv) {\n ImageParam input(UInt(32), 3, \"input\");\n input.dim(2).set_bounds(0, 4).set_stride(1).dim(0).set_stride(4);\n\n Var x, y, c;\n Func f(\"f\");\n f(x, y, c) = input(x, y, c) + 1;\n f.bound(c, 0, 4)\n .reorder_storage(c, x, y)\n .reorder(c, x, y);\n\n f.compute_root();\n f.output_buffer().dim(2).set_bounds(0, 4).set_stride(1).dim(0).set_stride(4);\n\n Target target = get_target_from_environment();\n if (target.has_gpu_feature() || target.has_feature(Target::OpenGLCompute)) {\n f.unroll(c)\n .gpu_tile(x, y, 64, 64);\n }\n\n Func g(\"g\");\n g(x, y, c) = f(x, y, c) - 1;\n g.bound(c, 0, 4)\n .reorder_storage(c, x, y)\n .reorder(c, x, y);\n if (target.has_gpu_feature() || target.has_feature(Target::OpenGLCompute)) {\n g.unroll(c)\n .gpu_tile(x, y, 64, 64);\n }\n g.output_buffer().dim(2).set_bounds(0, 4).set_stride(1).dim(0).set_stride(4);\n\n std::string fn_name = std::string(\"two_kernels_filter\") + (argc > 1 ? argv[1] : \"\");\n g.compile_to_file(fn_name, {input}, fn_name);\n}\n<|endoftext|>"} {"text":"removing locally defined struct text_list<|endoftext|>"} {"text":"\/\/ -*- mode: c++; coding: utf-8 -*-\n\/*! @file exact.cpp\n @brief Inplementation of ExactModel class\n*\/\n#include \"exact.hpp\"\n#include \"util.hpp\"\n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace likeligrid {\n\nconst std::vector ExactModel::STEPS_ = {0.32, 0.16, 0.08, 0.04, 0.02, 0.01};\nconst std::vector ExactModel::BREAKS_ = {5, 5, 5, 5, 5, 5};\nbool ExactModel::SIGINT_RAISED_ = false;\n\nExactModel::ExactModel(const std::string& infile,\n const size_t max_sites,\n const unsigned int concurrency)\n : ExactModel(wtl::izfstream(infile), max_sites, concurrency) {HERE;}\n\nExactModel::ExactModel(\n std::istream& ist,\n const size_t max_sites,\n const unsigned int concurrency)\n : concurrency_(concurrency) {HERE;\n\n nlohmann::json jso;\n ist >> jso;\n names_ = jso[\"pathway\"].get>();\n const size_t npath = names_.size();\n annot_.reserve(npath);\n for (const std::string& s: jso[\"annotation\"]) {\n annot_.emplace_back(s);\n }\n std::cerr << \"annot_: \" << annot_ << std::endl;\n\n const size_t nsam = jso[\"sample\"].size();\n std::vector all_genotypes;\n all_genotypes.reserve(nsam);\n for (const std::string& s: jso[\"sample\"]) {\n all_genotypes.emplace_back(s);\n }\n\n genot_.reserve(nsam);\n const size_t ngene = jso[\"sample\"].at(0).get().size();\n nsam_with_s_.assign(ngene + 1, 0); \/\/ at most\n std::valarray s_gene(ngene);\n for (const auto& bits: all_genotypes) {\n const size_t s = bits.count();\n ++nsam_with_s_[s];\n if (s > max_sites) continue;\n genot_.push_back(bits);\n for (size_t j=0; j> axes(names_.size(), wtl::lin_spaced(200, 2.0, 0.01));\n wtl::ozfstream fout(\"uniaxis.tsv.gz\");\n run_impl(fout, wtl::itertools::uniaxis(axes, mle_params_));\n }\n for (const auto& p: find_intersections(*this)) {\n std::cerr << p.first << \": \" << p.second << std::endl;\n const auto axes = make_vicinity(p.second, 5, 0.02);\n wtl::ozfstream fout(\"limit-\" + p.first + \".tsv.gz\");\n \/\/TODO: if exists\n run_impl(fout, wtl::itertools::product(axes));\n }\n}\n\nvoid ExactModel::run_impl(std::ostream& ost, wtl::itertools::Generator>&& gen) const {HERE;\n std::cerr << skip_ << \" to \" << gen.max_count() << std::endl;\n if (skip_ == 0) {\n ost << \"##max_count=\" << gen.max_count() << \"\\n\";\n ost << \"##max_sites=\" << nsam_with_s_.size() - 1 << \"\\n\";\n ost << \"##step=\" << STEPS_.at(stage_) << \"\\n\";\n ost << \"loglik\\t\" << wtl::join(names_, \"\\t\") << \"\\n\";\n ost.flush();\n }\n\n wtl::Semaphore semaphore(concurrency_);\n auto task = [this,&semaphore](const std::valarray th_path) {\n \/\/ argument is copied for thread\n auto buffer = wtl::make_oss();\n buffer << calc_loglik(th_path) << \"\\t\"\n << wtl::str_join(th_path, \"\\t\") << \"\\n\";\n semaphore.unlock();\n return buffer.str();\n };\n\n std::deque> futures;\n const auto min_interval = std::chrono::seconds(2);\n auto next_time = std::chrono::system_clock::now() + min_interval;\n size_t stars = 0;\n for (const auto& th_path: gen(skip_)) {\n semaphore.lock();\n futures.push_back(std::async(std::launch::async, task, th_path));\n auto now = std::chrono::system_clock::now();\n if (now > next_time) {\n next_time = now + min_interval;\n size_t progress = 0;\n while (wtl::is_ready(futures.front())) {\n ost << futures.front().get();\n futures.pop_front();\n ++progress;\n }\n if (progress > 0) {\n ost.flush();\n for (size_t n= 0.2 * gen.percent(); stars to_indices(const bits_t& bits) {\n std::valarray indices(bits.count());\n for (size_t i=0, j=0; i& coefs, const bits_t& bits) {\n double p = 1.0;\n for (size_t i=0; i& w_gene,\n const std::valarray& th_path,\n const std::vector& annot,\n const size_t max_sites):\n w_gene_(w_gene),\n th_path_(th_path),\n annot_(annot),\n max_sites_(max_sites),\n denoms_(max_sites + 1)\n {\n const size_t ngene = w_gene.size();\n effects_.reserve(ngene);\n for (size_t j=0; j log() const {return std::log(denoms_);}\n\n double lnp_sample(const bits_t& genotype) const {\n double p = 0.0;\n const double p_basic = slice_prod(w_gene_, genotype);\n auto mut_route = to_indices(genotype);\n do {\n p += p_basic * discount(mut_route);\n } while (std::next_permutation(std::begin(mut_route), std::end(mut_route)));\n return std::log(p);\n }\n\n private:\n void mutate(const bits_t& genotype, const bits_t& pathtype, const double anc_p) {\n const auto s = genotype.count() + 1;\n for (size_t j=0; j& mut_route) const {\n double p = 1.0;\n bits_t pathtype;\n for (const auto j: mut_route) {\n const auto& mut_path = effects_[j];\n p *= discount_if_subset(pathtype, mut_path);\n pathtype |= mut_path;\n }\n return p;\n }\n\n bits_t translate(const size_t& mut_idx) const {\n bits_t mut_path;\n for (size_t j=0; j& w_gene_;\n const std::valarray& th_path_;\n const std::vector& annot_;\n const size_t max_sites_;\n std::valarray denoms_;\n std::vector effects_;\n};\n\ndouble ExactModel::calc_loglik(const std::valarray& th_path) const {\n const size_t max_sites = nsam_with_s_.size() - 1;\n Denoms subcalc(w_gene_, th_path, annot_, max_sites);\n double loglik = 0.0;\n for (const auto& genotype: genot_) {\n loglik += subcalc.lnp_sample(genotype);\n }\n const auto lnD = subcalc.log();\n \/\/ std::cout << \"lnD: \" << lnD << std::endl;\n \/\/ -inf, 0, D2, D3, ...\n for (size_t s=2; s<=max_sites; ++s) {\n loglik -= nsam_with_s_[s] * lnD[s];\n }\n return loglik;\n}\n\nstd::string ExactModel::init_meta() {HERE;\n if (stage_ >= STEPS_.size()) return \"\";\n auto oss = wtl::make_oss(2, std::ios::fixed);\n oss << \"grid-\" << STEPS_.at(stage_) << \".tsv.gz\";\n std::string outfile = oss.str();\n try {\n wtl::izfstream ist(outfile);\n std::cerr << \"Reading: \" << outfile << std::endl;\n read_results(ist);\n if (skip_ == 0) {\n ++stage_;\n outfile = init_meta();\n }\n } catch (std::ios::failure& e) {\n if (errno != 2) throw;\n }\n return outfile;\n}\n\nvoid ExactModel::read_results(std::istream& ist) {HERE;\n size_t max_count;\n double step;\n std::tie(max_count, std::ignore, step) = read_metadata(ist);\n stage_ = guess_stage(STEPS_, step);\n std::vector colnames;\n std::valarray mle_params;\n std::tie(skip_, colnames, mle_params) = read_body(ist);\n if (skip_ == max_count) { \/\/ is complete file\n skip_ = 0;\n mle_params_.swap(mle_params);\n }\n if (names_ != colnames) {\n std::ostringstream oss;\n oss << \"Contradiction in column names:\\n\"\n << \"genotype file: \" << names_ << \"\\n\"\n << \"result file:\" << colnames;\n throw std::runtime_error(oss.str());\n }\n}\n\nvoid ExactModel::unit_test() {HERE;\n std::stringstream sst;\n sst <<\nR\"({\n \"pathway\": [\"A\", \"B\"],\n \"annotation\": [\"0011\", \"1100\"],\n \"sample\": [\"0011\", \"0101\", \"1001\", \"0110\", \"1010\", \"1100\"]\n})\";\n ExactModel model(sst, 4);\n model.run(false);\n}\n\n} \/\/ namespace likeligrid\nRound uniaxis\/\/ -*- mode: c++; coding: utf-8 -*-\n\/*! @file exact.cpp\n @brief Inplementation of ExactModel class\n*\/\n#include \"exact.hpp\"\n#include \"util.hpp\"\n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace likeligrid {\n\nconst std::vector ExactModel::STEPS_ = {0.32, 0.16, 0.08, 0.04, 0.02, 0.01};\nconst std::vector ExactModel::BREAKS_ = {5, 5, 5, 5, 5, 5};\nbool ExactModel::SIGINT_RAISED_ = false;\n\nExactModel::ExactModel(const std::string& infile,\n const size_t max_sites,\n const unsigned int concurrency)\n : ExactModel(wtl::izfstream(infile), max_sites, concurrency) {HERE;}\n\nExactModel::ExactModel(\n std::istream& ist,\n const size_t max_sites,\n const unsigned int concurrency)\n : concurrency_(concurrency) {HERE;\n\n nlohmann::json jso;\n ist >> jso;\n names_ = jso[\"pathway\"].get>();\n const size_t npath = names_.size();\n annot_.reserve(npath);\n for (const std::string& s: jso[\"annotation\"]) {\n annot_.emplace_back(s);\n }\n std::cerr << \"annot_: \" << annot_ << std::endl;\n\n const size_t nsam = jso[\"sample\"].size();\n std::vector all_genotypes;\n all_genotypes.reserve(nsam);\n for (const std::string& s: jso[\"sample\"]) {\n all_genotypes.emplace_back(s);\n }\n\n genot_.reserve(nsam);\n const size_t ngene = jso[\"sample\"].at(0).get().size();\n nsam_with_s_.assign(ngene + 1, 0); \/\/ at most\n std::valarray s_gene(ngene);\n for (const auto& bits: all_genotypes) {\n const size_t s = bits.count();\n ++nsam_with_s_[s];\n if (s > max_sites) continue;\n genot_.push_back(bits);\n for (size_t j=0; j> axes(names_.size(), axis);\n wtl::ozfstream fout(\"uniaxis.tsv.gz\");\n run_impl(fout, wtl::itertools::uniaxis(axes, mle_params_));\n }\n for (const auto& p: find_intersections(*this)) {\n std::cerr << p.first << \": \" << p.second << std::endl;\n const auto axes = make_vicinity(p.second, 5, 0.02);\n wtl::ozfstream fout(\"limit-\" + p.first + \".tsv.gz\");\n \/\/TODO: if exists\n run_impl(fout, wtl::itertools::product(axes));\n }\n}\n\nvoid ExactModel::run_impl(std::ostream& ost, wtl::itertools::Generator>&& gen) const {HERE;\n std::cerr << skip_ << \" to \" << gen.max_count() << std::endl;\n if (skip_ == 0) {\n ost << \"##max_count=\" << gen.max_count() << \"\\n\";\n ost << \"##max_sites=\" << nsam_with_s_.size() - 1 << \"\\n\";\n ost << \"##step=\" << STEPS_.at(stage_) << \"\\n\";\n ost << \"loglik\\t\" << wtl::join(names_, \"\\t\") << \"\\n\";\n ost.flush();\n }\n\n wtl::Semaphore semaphore(concurrency_);\n auto task = [this,&semaphore](const std::valarray th_path) {\n \/\/ argument is copied for thread\n auto buffer = wtl::make_oss();\n buffer << calc_loglik(th_path) << \"\\t\"\n << wtl::str_join(th_path, \"\\t\") << \"\\n\";\n semaphore.unlock();\n return buffer.str();\n };\n\n std::deque> futures;\n const auto min_interval = std::chrono::seconds(2);\n auto next_time = std::chrono::system_clock::now() + min_interval;\n size_t stars = 0;\n for (const auto& th_path: gen(skip_)) {\n semaphore.lock();\n futures.push_back(std::async(std::launch::async, task, th_path));\n auto now = std::chrono::system_clock::now();\n if (now > next_time) {\n next_time = now + min_interval;\n size_t progress = 0;\n while (wtl::is_ready(futures.front())) {\n ost << futures.front().get();\n futures.pop_front();\n ++progress;\n }\n if (progress > 0) {\n ost.flush();\n for (size_t n= 0.2 * gen.percent(); stars to_indices(const bits_t& bits) {\n std::valarray indices(bits.count());\n for (size_t i=0, j=0; i& coefs, const bits_t& bits) {\n double p = 1.0;\n for (size_t i=0; i& w_gene,\n const std::valarray& th_path,\n const std::vector& annot,\n const size_t max_sites):\n w_gene_(w_gene),\n th_path_(th_path),\n annot_(annot),\n max_sites_(max_sites),\n denoms_(max_sites + 1)\n {\n const size_t ngene = w_gene.size();\n effects_.reserve(ngene);\n for (size_t j=0; j log() const {return std::log(denoms_);}\n\n double lnp_sample(const bits_t& genotype) const {\n double p = 0.0;\n const double p_basic = slice_prod(w_gene_, genotype);\n auto mut_route = to_indices(genotype);\n do {\n p += p_basic * discount(mut_route);\n } while (std::next_permutation(std::begin(mut_route), std::end(mut_route)));\n return std::log(p);\n }\n\n private:\n void mutate(const bits_t& genotype, const bits_t& pathtype, const double anc_p) {\n const auto s = genotype.count() + 1;\n for (size_t j=0; j& mut_route) const {\n double p = 1.0;\n bits_t pathtype;\n for (const auto j: mut_route) {\n const auto& mut_path = effects_[j];\n p *= discount_if_subset(pathtype, mut_path);\n pathtype |= mut_path;\n }\n return p;\n }\n\n bits_t translate(const size_t& mut_idx) const {\n bits_t mut_path;\n for (size_t j=0; j& w_gene_;\n const std::valarray& th_path_;\n const std::vector& annot_;\n const size_t max_sites_;\n std::valarray denoms_;\n std::vector effects_;\n};\n\ndouble ExactModel::calc_loglik(const std::valarray& th_path) const {\n const size_t max_sites = nsam_with_s_.size() - 1;\n Denoms subcalc(w_gene_, th_path, annot_, max_sites);\n double loglik = 0.0;\n for (const auto& genotype: genot_) {\n loglik += subcalc.lnp_sample(genotype);\n }\n const auto lnD = subcalc.log();\n \/\/ std::cout << \"lnD: \" << lnD << std::endl;\n \/\/ -inf, 0, D2, D3, ...\n for (size_t s=2; s<=max_sites; ++s) {\n loglik -= nsam_with_s_[s] * lnD[s];\n }\n return loglik;\n}\n\nstd::string ExactModel::init_meta() {HERE;\n if (stage_ >= STEPS_.size()) return \"\";\n auto oss = wtl::make_oss(2, std::ios::fixed);\n oss << \"grid-\" << STEPS_.at(stage_) << \".tsv.gz\";\n std::string outfile = oss.str();\n try {\n wtl::izfstream ist(outfile);\n std::cerr << \"Reading: \" << outfile << std::endl;\n read_results(ist);\n if (skip_ == 0) {\n ++stage_;\n outfile = init_meta();\n }\n } catch (std::ios::failure& e) {\n if (errno != 2) throw;\n }\n return outfile;\n}\n\nvoid ExactModel::read_results(std::istream& ist) {HERE;\n size_t max_count;\n double step;\n std::tie(max_count, std::ignore, step) = read_metadata(ist);\n stage_ = guess_stage(STEPS_, step);\n std::vector colnames;\n std::valarray mle_params;\n std::tie(skip_, colnames, mle_params) = read_body(ist);\n if (skip_ == max_count) { \/\/ is complete file\n skip_ = 0;\n mle_params_.swap(mle_params);\n }\n if (names_ != colnames) {\n std::ostringstream oss;\n oss << \"Contradiction in column names:\\n\"\n << \"genotype file: \" << names_ << \"\\n\"\n << \"result file:\" << colnames;\n throw std::runtime_error(oss.str());\n }\n}\n\nvoid ExactModel::unit_test() {HERE;\n std::stringstream sst;\n sst <<\nR\"({\n \"pathway\": [\"A\", \"B\"],\n \"annotation\": [\"0011\", \"1100\"],\n \"sample\": [\"0011\", \"0101\", \"1001\", \"0110\", \"1010\", \"1100\"]\n})\";\n ExactModel model(sst, 4);\n model.run(false);\n}\n\n} \/\/ namespace likeligrid\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright 2011, Kay Hayen, mailto:kayhayen@gmx.de\n\/\/\n\/\/ Part of \"Nuitka\", an optimizing Python compiler that is compatible and\n\/\/ integrates with CPython, but also works on its own.\n\/\/\n\/\/ If you submit Kay Hayen patches to this software in either form, you\n\/\/ automatically grant him a copyright assignment to the code, or in the\n\/\/ alternative a BSD license to the code, should your jurisdiction prevent\n\/\/ this. Obviously it won't affect code that comes to him indirectly or\n\/\/ code you don't submit to him.\n\/\/\n\/\/ This is to reserve my ability to re-license the code at any time, e.g.\n\/\/ the PSF. With this version of Nuitka, using it for Closed Source will\n\/\/ not be allowed.\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, version 3 of the License.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see .\n\/\/\n\/\/ Please leave the whole of this copyright notice intact.\n\/\/\n#ifndef __NUITKA_VARIABLES_TEMPORARY_H__\n#define __NUITKA_VARIABLES_TEMPORARY_H__\n\n\/\/ Wraps a PyObject * you received or acquired from another container to simplify refcount\n\/\/ handling when you're not going to use the object beyond the local scope. It will hold a\n\/\/ reference to the wrapped object as long as the PyObjectTemporary is alive, and will\n\/\/ release the reference when the wrapper is destroyed: this eliminates the need for\n\/\/ manual DECREF calls on Python objects before returning from a method call.\n\/\/\n\/\/ In effect, wrapping an object inside a PyObjectTemporary is equivalent to a deferred\n\/\/ Py_DECREF() call on the wrapped object.\n\nclass PyObjectTemporary\n{\n public:\n explicit PyObjectTemporary( PyObject *object )\n {\n assertObject( object );\n\n this->object = object;\n }\n\n ~PyObjectTemporary()\n {\n assertObject( this->object );\n\n Py_DECREF( this->object );\n }\n\n PyObject *asObject() const\n {\n assertObject( this->object );\n\n return this->object;\n }\n\n void assign( PyObject *object )\n {\n assertObject( this->object );\n\n Py_DECREF( this->object );\n\n assertObject( object );\n\n this->object = object;\n }\n\n private:\n PyObjectTemporary( const PyObjectTemporary &object ) = delete;\n\n PyObject *object;\n};\n\nclass PyObjectTempHolder\n{\n public:\n explicit PyObjectTempHolder( PyObject *object )\n {\n assertObject( object );\n\n this->object = object;\n }\n\n ~PyObjectTempHolder()\n {\n Py_XDECREF( this->object );\n }\n\n PyObject *asObject()\n {\n assertObject( this->object );\n\n PyObject *result = this->object;\n this->object = NULL;\n return result;\n }\n\n private:\n PyObjectTempHolder( const PyObjectTempHolder &object ) = delete;\n\n PyObject *object;\n};\n\n#endif\nMinor comment improvement\/\/\n\/\/ Copyright 2011, Kay Hayen, mailto:kayhayen@gmx.de\n\/\/\n\/\/ Part of \"Nuitka\", an optimizing Python compiler that is compatible and\n\/\/ integrates with CPython, but also works on its own.\n\/\/\n\/\/ If you submit Kay Hayen patches to this software in either form, you\n\/\/ automatically grant him a copyright assignment to the code, or in the\n\/\/ alternative a BSD license to the code, should your jurisdiction prevent\n\/\/ this. Obviously it won't affect code that comes to him indirectly or\n\/\/ code you don't submit to him.\n\/\/\n\/\/ This is to reserve my ability to re-license the code at any time, e.g.\n\/\/ the PSF. With this version of Nuitka, using it for Closed Source will\n\/\/ not be allowed.\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, version 3 of the License.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see .\n\/\/\n\/\/ Please leave the whole of this copyright notice intact.\n\/\/\n#ifndef __NUITKA_VARIABLES_TEMPORARY_H__\n#define __NUITKA_VARIABLES_TEMPORARY_H__\n\n\/\/ Wraps a \"PyObject *\" you received or acquired from another container to simplify refcount\n\/\/ handling when you're not going to use the object beyond the local scope. It will hold a\n\/\/ reference to the wrapped object as long as the PyObjectTemporary is alive, and will\n\/\/ release the reference when the wrapper is destroyed: this eliminates the need for\n\/\/ manual DECREF calls on Python objects before returning from a method call.\n\/\/\n\/\/ In effect, wrapping an object inside a PyObjectTemporary is equivalent to a deferred\n\/\/ Py_DECREF() call on the wrapped object.\n\nclass PyObjectTemporary\n{\n public:\n explicit PyObjectTemporary( PyObject *object )\n {\n assertObject( object );\n\n this->object = object;\n }\n\n ~PyObjectTemporary()\n {\n assertObject( this->object );\n\n Py_DECREF( this->object );\n }\n\n PyObject *asObject() const\n {\n assertObject( this->object );\n\n return this->object;\n }\n\n void assign( PyObject *object )\n {\n assertObject( this->object );\n\n Py_DECREF( this->object );\n\n assertObject( object );\n\n this->object = object;\n }\n\n private:\n PyObjectTemporary( const PyObjectTemporary &object ) = delete;\n\n PyObject *object;\n};\n\nclass PyObjectTempHolder\n{\n public:\n explicit PyObjectTempHolder( PyObject *object )\n {\n assertObject( object );\n\n this->object = object;\n }\n\n ~PyObjectTempHolder()\n {\n Py_XDECREF( this->object );\n }\n\n PyObject *asObject()\n {\n assertObject( this->object );\n\n PyObject *result = this->object;\n this->object = NULL;\n return result;\n }\n\n private:\n PyObjectTempHolder( const PyObjectTempHolder &object ) = delete;\n\n PyObject *object;\n};\n\n#endif\n<|endoftext|>"} {"text":"\/** This file is part of Contacts daemon\n **\n ** Copyright (c) 2010-2011 Nokia Corporation and\/or its subsidiary(-ies).\n **\n ** Contact: Nokia Corporation (info@qt.nokia.com)\n **\n ** GNU Lesser General Public License Usage\n ** This file may be used under the terms of the GNU Lesser General Public License\n ** version 2.1 as published by the Free Software Foundation and appearing in the\n ** file LICENSE.LGPL included in the packaging of this file. Please review the\n ** following information to ensure the GNU Lesser General Public License version\n ** 2.1 requirements will be met:\n ** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n **\n ** In addition, as a special exception, Nokia gives you certain additional rights.\n ** These rights are described in the Nokia Qt LGPL Exception version 1.1, included\n ** in the file LGPL_EXCEPTION.txt in this package.\n **\n ** Other Usage\n ** Alternatively, this file may be used in accordance with the terms and\n ** conditions contained in a signed written agreement between you and Nokia.\n **\/\n\n#include \"cdbirthdaycontroller.h\"\n#include \"cdbirthdaycalendar.h\"\n#include \"cdbirthdayplugin.h\"\n#include \"debug.h\"\n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\nQTM_USE_NAMESPACE\n\nCUBI_USE_NAMESPACE\nCUBI_USE_NAMESPACE_RESOURCES\n\nusing namespace Contactsd;\n\n\/\/ The logic behind this class was strongly influenced by QctTrackerChangeListener in\n\/\/ qtcontacts-tracker.\nCDBirthdayController::CDBirthdayController(QSparqlConnection &connection,\n QObject *parent)\n : QObject(parent)\n , mSparqlConnection(connection)\n , mCalendar(0)\n , mManager(0)\n{\n const QLatin1String trackerManagerName = QLatin1String(\"tracker\");\n\n mManager = new QContactManager(trackerManagerName, QMap(), this);\n\n if (mManager->managerName() != trackerManagerName) {\n debug() << Q_FUNC_INFO << \"Tracker plugin not found\";\n return;\n }\n\n fetchTrackerIds();\n\n if (not stampFileExists()) {\n \/\/ Delete the calendar database.\n mCalendar = new CDBirthdayCalendar(CDBirthdayCalendar::FullSync, this);\n\n updateAllBirthdays();\n } else {\n \/\/ Use the existing calendar database.\n mCalendar = new CDBirthdayCalendar(CDBirthdayCalendar::Incremental, this);\n }\n}\n\nCDBirthdayController::~CDBirthdayController()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tracker ID fetching\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nCDBirthdayController::fetchTrackerIds()\n{\n \/\/ keep in sync with the enum in the header and NTrackerIds\n const QList resources = QList()\n << nco::birthDate::resource()\n << rdf::type::resource()\n << nco::PersonContact::resource()\n << nco::ContactGroup::resource();\n\n Select select;\n\n foreach (const ResourceValue &value, resources) {\n select.addProjection(Functions::trackerId.apply(value));\n }\n\n if (not mSparqlConnection.isValid()) {\n debug() << Q_FUNC_INFO << \"SPARQL connection is not valid\";\n return;\n }\n\n QScopedPointer result(mSparqlConnection.exec(QSparqlQuery(select.sparql())));\n\n if (result->hasError()) {\n debug() << Q_FUNC_INFO << \"Could not fetch Tracker IDs:\" << result->lastError().message();\n return;\n }\n\n connect(result.take(), SIGNAL(finished()), this, SLOT(onTrackerIdsFetched()));\n}\n\nvoid\nCDBirthdayController::onTrackerIdsFetched()\n{\n QSparqlResult *result = qobject_cast(sender());\n\n if (result == 0) {\n debug() << Q_FUNC_INFO << \"Invalid result\";\n return;\n }\n\n if (result->hasError()) {\n debug() << Q_FUNC_INFO << \"Could not fetch Tracker IDs:\" << result->lastError().message();\n } else if (not result->next()) {\n debug() << Q_FUNC_INFO << \"No results returned\";\n return;\n } else {\n const QSparqlResultRow row = result->current();\n\n for (int i = 0; i < NTrackerIds; ++i) {\n mTrackerIds[i] = row.value(i).toInt();\n }\n }\n\n \/\/ Provide hint we are done with this result.\n result->deleteLater();\n\n debug() << Q_FUNC_INFO << \"Tracker IDs fetched, connecting the change notifier\";\n\n connectChangeNotifier();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Contact monitor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nCDBirthdayController::connectChangeNotifier()\n{\n const QStringList contactClassIris = QStringList()\n << nco::PersonContact::iri()\n << nco::ContactGroup::iri();\n\n foreach (const QString &iri, contactClassIris) {\n connect(new TrackerChangeNotifier(iri, this),\n SIGNAL(changed(QList,\n QList)),\n SLOT(onGraphChanged(QList,\n QList)));\n }\n}\n\nvoid\nCDBirthdayController::onGraphChanged(const QList& deletions,\n const QList& insertions)\n{\n mDeleteNotifications += deletions;\n mInsertNotifications += insertions;\n\n if (isDebugEnabled()) {\n TrackerChangeNotifier const * const notifier = qobject_cast(sender());\n\n if (notifier == 0) {\n warning() << Q_FUNC_INFO << \"Error casting birthday change notifier\";\n return;\n }\n\n debug() << notifier->watchedClass() << \"birthday: deletions:\" << deletions;\n debug() << notifier->watchedClass() << \"birthday: insertions:\" << insertions;\n }\n\n processNotificationQueues();\n}\n\nvoid\nCDBirthdayController::processNotifications(QList ¬ifications,\n QSet &propertyChanges,\n QSet &resourceChanges)\n{\n foreach (const TrackerChangeNotifier::Quad &quad, notifications) {\n if (quad.predicate == mTrackerIds[NcoBirthDate]) {\n propertyChanges += quad.subject;\n continue;\n }\n\n if (quad.predicate == mTrackerIds[RdfType]) {\n if (quad.object == mTrackerIds[NcoPersonContact]\n || quad.object == mTrackerIds[NcoContactGroup]) {\n resourceChanges += quad.subject;\n }\n }\n }\n\n \/\/ Remove the processed notifications.\n notifications.clear();\n}\n\nvoid\nCDBirthdayController::processNotificationQueues()\n{\n QSet insertedContacts;\n QSet deletedContacts;\n QSet birthdayChangedIds;\n\n \/\/ Process notification queues to determine contacts with changed birthdays.\n processNotifications(mDeleteNotifications, birthdayChangedIds, deletedContacts);\n processNotifications(mInsertNotifications, birthdayChangedIds, insertedContacts);\n\n if (isDebugEnabled()) {\n debug() << \"changed birthdates: \" << birthdayChangedIds.count() << birthdayChangedIds;\n }\n\n \/\/ Remove the birthdays for contacts that are not there anymore\n foreach (QContactLocalId id, deletedContacts) {\n mCalendar->deleteBirthday(id);\n }\n\n \/\/ Update the calendar with the birthday changes.\n if (not birthdayChangedIds.isEmpty()) {\n fetchContacts(birthdayChangedIds.toList());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Full sync logic\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool\nCDBirthdayController::stampFileExists()\n{\n const QFile cacheFile(stampFilePath(), this);\n\n return cacheFile.exists();\n}\n\nvoid\nCDBirthdayController::createStampFile()\n{\n QFile cacheFile(stampFilePath(), this);\n\n if (not cacheFile.exists()) {\n if (not cacheFile.open(QIODevice::WriteOnly)) {\n warning() << Q_FUNC_INFO << \"Unable to create birthday plugin stamp file \"\n << cacheFile.fileName() << \" with error \" << cacheFile.errorString();\n } else {\n cacheFile.close();\n }\n }\n}\n\nQString\nCDBirthdayController::stampFilePath() const\n{\n return BasePlugin::cacheFileName(QLatin1String(\"calendar.stamp\"));\n}\n\nvoid\nCDBirthdayController::updateAllBirthdays()\n{\n QContactFetchHint fetchHint;\n static const QStringList detailDefinitions = QStringList() << QContactBirthday::DefinitionName\n << QContactDisplayLabel::DefinitionName;\n fetchHint.setDetailDefinitionsHint(detailDefinitions);\n\n \/\/ Filter on any contact with a birthday.\n QContactDetailFilter fetchFilter;\n fetchFilter.setDetailDefinitionName(QContactBirthday::DefinitionName);\n\n QContactFetchRequest * const fetchRequest = new QContactFetchRequest(this);\n fetchRequest->setManager(mManager);\n fetchRequest->setFetchHint(fetchHint);\n fetchRequest->setFilter(fetchFilter);\n\n connect(fetchRequest,\n SIGNAL(stateChanged(QContactAbstractRequest::State)),\n SLOT(onFullSyncRequestStateChanged(QContactAbstractRequest::State)));\n\n if (not fetchRequest->start()) {\n warning() << Q_FUNC_INFO << \"Unable to start contact birthdays fetch request\";\n delete fetchRequest;\n return;\n }\n\n debug() << \"Contact birthdays fetch request started\";\n}\n\nvoid\nCDBirthdayController::onFullSyncRequestStateChanged(QContactAbstractRequest::State newState)\n{\n QContactFetchRequest * const fetchRequest = qobject_cast(sender());\n\n if (not processFetchRequest(fetchRequest, newState)) {\n return;\n }\n\n updateBirthdays(fetchRequest->contacts());\n\n \/\/ Create the stamp file only after a successful full sync.\n createStampFile();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Incremental sync logic\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nCDBirthdayController::fetchContacts(const QList &contactIds)\n{\n QContactFetchHint fetchHint;\n static const QStringList detailDefinitions = QStringList() << QContactBirthday::DefinitionName\n << QContactDisplayLabel::DefinitionName;\n fetchHint.setDetailDefinitionsHint(detailDefinitions);\n\n QContactLocalIdFilter fetchFilter;\n fetchFilter.setIds(contactIds);\n\n QContactFetchRequest * const fetchRequest = new QContactFetchRequest(this);\n fetchRequest->setManager(mManager);\n fetchRequest->setFetchHint(fetchHint);\n fetchRequest->setFilter(fetchFilter);\n\n connect(fetchRequest,\n SIGNAL(stateChanged(QContactAbstractRequest::State)),\n SLOT(onFetchRequestStateChanged(QContactAbstractRequest::State)));\n\n if (not fetchRequest->start()) {\n warning() << Q_FUNC_INFO << \"Unable to start birthday contact fetch request\";\n delete fetchRequest;\n return;\n }\n\n debug() << \"Birthday contacts fetch request started\";\n}\n\nvoid\nCDBirthdayController::onFetchRequestStateChanged(QContactAbstractRequest::State newState)\n{\n QContactFetchRequest * const fetchRequest = qobject_cast(sender());\n\n if (not processFetchRequest(fetchRequest, newState)) {\n return;\n }\n\n updateBirthdays(fetchRequest->contacts());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Common sync logic\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool\nCDBirthdayController::processFetchRequest(QContactFetchRequest * const fetchRequest,\n QContactAbstractRequest::State newState)\n{\n if (fetchRequest == 0) {\n warning() << Q_FUNC_INFO << \"Invalid fetch request\";\n return false;\n }\n\n bool success = false;\n\n switch (newState) {\n case QContactAbstractRequest::FinishedState:\n debug() << \"Birthday contacts fetch request finished\";\n\n if (fetchRequest->error() != QContactManager::NoError) {\n warning() << Q_FUNC_INFO << \"Error during birthday contact fetch request, code: \"\n << fetchRequest->error();\n } else {\n success = true;\n }\n\n break;\n\n case QContactAbstractRequest::CanceledState:\n break;\n\n default:\n return false;\n }\n\n \/\/ Provide hint we are done with this request.\n fetchRequest->deleteLater();\n\n return success;\n}\n\nvoid\nCDBirthdayController::updateBirthdays(const QList &changedBirthdays)\n{\n foreach (const QContact &contact, changedBirthdays) {\n const QContactBirthday contactBirthday = contact.detail();\n const QContactDisplayLabel contactDisplayLabel = contact.detail();\n const QDate calendarBirthday = mCalendar->birthdayDate(contact.localId());\n const QString calendarSummary = mCalendar->summary(contact.localId());\n\n \/\/ Display label or birthdate was removed from the contact, so delete it from the calendar.\n if (contactDisplayLabel.label().isNull() || contactBirthday.date().isNull()) {\n if (isDebugEnabled()) {\n debug() << \"Contact: \" << contact << \" removed birthday or displayLabel, so delete the calendar event\";\n }\n\n mCalendar->deleteBirthday(contact.localId());\n \/\/ Display label or birthdate was changed on the contact, so update the calendar.\n } else if ((contactDisplayLabel.label() != calendarSummary) ||\n (contactBirthday.date() != calendarBirthday)) {\n if (isDebugEnabled()) {\n debug() << \"Contact with calendar birthday: \" << contactBirthday.date()\n << \" and calendar displayLabel: \" << calendarSummary\n << \" changed details to: \" << contact << \", so update the calendar event\";\n }\n\n mCalendar->updateBirthday(contact);\n }\n }\n}\nChanges: Merge common logic in contact fetching callbacks\/** This file is part of Contacts daemon\n **\n ** Copyright (c) 2010-2011 Nokia Corporation and\/or its subsidiary(-ies).\n **\n ** Contact: Nokia Corporation (info@qt.nokia.com)\n **\n ** GNU Lesser General Public License Usage\n ** This file may be used under the terms of the GNU Lesser General Public License\n ** version 2.1 as published by the Free Software Foundation and appearing in the\n ** file LICENSE.LGPL included in the packaging of this file. Please review the\n ** following information to ensure the GNU Lesser General Public License version\n ** 2.1 requirements will be met:\n ** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n **\n ** In addition, as a special exception, Nokia gives you certain additional rights.\n ** These rights are described in the Nokia Qt LGPL Exception version 1.1, included\n ** in the file LGPL_EXCEPTION.txt in this package.\n **\n ** Other Usage\n ** Alternatively, this file may be used in accordance with the terms and\n ** conditions contained in a signed written agreement between you and Nokia.\n **\/\n\n#include \"cdbirthdaycontroller.h\"\n#include \"cdbirthdaycalendar.h\"\n#include \"cdbirthdayplugin.h\"\n#include \"debug.h\"\n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\nQTM_USE_NAMESPACE\n\nCUBI_USE_NAMESPACE\nCUBI_USE_NAMESPACE_RESOURCES\n\nusing namespace Contactsd;\n\n\/\/ The logic behind this class was strongly influenced by QctTrackerChangeListener in\n\/\/ qtcontacts-tracker.\nCDBirthdayController::CDBirthdayController(QSparqlConnection &connection,\n QObject *parent)\n : QObject(parent)\n , mSparqlConnection(connection)\n , mCalendar(0)\n , mManager(0)\n{\n const QLatin1String trackerManagerName = QLatin1String(\"tracker\");\n\n mManager = new QContactManager(trackerManagerName, QMap(), this);\n\n if (mManager->managerName() != trackerManagerName) {\n debug() << Q_FUNC_INFO << \"Tracker plugin not found\";\n return;\n }\n\n fetchTrackerIds();\n\n if (not stampFileExists()) {\n \/\/ Delete the calendar database.\n mCalendar = new CDBirthdayCalendar(CDBirthdayCalendar::FullSync, this);\n\n updateAllBirthdays();\n } else {\n \/\/ Use the existing calendar database.\n mCalendar = new CDBirthdayCalendar(CDBirthdayCalendar::Incremental, this);\n }\n}\n\nCDBirthdayController::~CDBirthdayController()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tracker ID fetching\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nCDBirthdayController::fetchTrackerIds()\n{\n \/\/ keep in sync with the enum in the header and NTrackerIds\n const QList resources = QList()\n << nco::birthDate::resource()\n << rdf::type::resource()\n << nco::PersonContact::resource()\n << nco::ContactGroup::resource();\n\n Select select;\n\n foreach (const ResourceValue &value, resources) {\n select.addProjection(Functions::trackerId.apply(value));\n }\n\n if (not mSparqlConnection.isValid()) {\n debug() << Q_FUNC_INFO << \"SPARQL connection is not valid\";\n return;\n }\n\n QScopedPointer result(mSparqlConnection.exec(QSparqlQuery(select.sparql())));\n\n if (result->hasError()) {\n debug() << Q_FUNC_INFO << \"Could not fetch Tracker IDs:\" << result->lastError().message();\n return;\n }\n\n connect(result.take(), SIGNAL(finished()), this, SLOT(onTrackerIdsFetched()));\n}\n\nvoid\nCDBirthdayController::onTrackerIdsFetched()\n{\n QSparqlResult *result = qobject_cast(sender());\n\n if (result == 0) {\n debug() << Q_FUNC_INFO << \"Invalid result\";\n return;\n }\n\n if (result->hasError()) {\n debug() << Q_FUNC_INFO << \"Could not fetch Tracker IDs:\" << result->lastError().message();\n } else if (not result->next()) {\n debug() << Q_FUNC_INFO << \"No results returned\";\n return;\n } else {\n const QSparqlResultRow row = result->current();\n\n for (int i = 0; i < NTrackerIds; ++i) {\n mTrackerIds[i] = row.value(i).toInt();\n }\n }\n\n \/\/ Provide hint we are done with this result.\n result->deleteLater();\n\n debug() << Q_FUNC_INFO << \"Tracker IDs fetched, connecting the change notifier\";\n\n connectChangeNotifier();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Contact monitor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nCDBirthdayController::connectChangeNotifier()\n{\n const QStringList contactClassIris = QStringList()\n << nco::PersonContact::iri()\n << nco::ContactGroup::iri();\n\n foreach (const QString &iri, contactClassIris) {\n connect(new TrackerChangeNotifier(iri, this),\n SIGNAL(changed(QList,\n QList)),\n SLOT(onGraphChanged(QList,\n QList)));\n }\n}\n\nvoid\nCDBirthdayController::onGraphChanged(const QList& deletions,\n const QList& insertions)\n{\n mDeleteNotifications += deletions;\n mInsertNotifications += insertions;\n\n if (isDebugEnabled()) {\n TrackerChangeNotifier const * const notifier = qobject_cast(sender());\n\n if (notifier == 0) {\n warning() << Q_FUNC_INFO << \"Error casting birthday change notifier\";\n return;\n }\n\n debug() << notifier->watchedClass() << \"birthday: deletions:\" << deletions;\n debug() << notifier->watchedClass() << \"birthday: insertions:\" << insertions;\n }\n\n processNotificationQueues();\n}\n\nvoid\nCDBirthdayController::processNotifications(QList ¬ifications,\n QSet &propertyChanges,\n QSet &resourceChanges)\n{\n foreach (const TrackerChangeNotifier::Quad &quad, notifications) {\n if (quad.predicate == mTrackerIds[NcoBirthDate]) {\n propertyChanges += quad.subject;\n continue;\n }\n\n if (quad.predicate == mTrackerIds[RdfType]) {\n if (quad.object == mTrackerIds[NcoPersonContact]\n || quad.object == mTrackerIds[NcoContactGroup]) {\n resourceChanges += quad.subject;\n }\n }\n }\n\n \/\/ Remove the processed notifications.\n notifications.clear();\n}\n\nvoid\nCDBirthdayController::processNotificationQueues()\n{\n QSet insertedContacts;\n QSet deletedContacts;\n QSet birthdayChangedIds;\n\n \/\/ Process notification queues to determine contacts with changed birthdays.\n processNotifications(mDeleteNotifications, birthdayChangedIds, deletedContacts);\n processNotifications(mInsertNotifications, birthdayChangedIds, insertedContacts);\n\n if (isDebugEnabled()) {\n debug() << \"changed birthdates: \" << birthdayChangedIds.count() << birthdayChangedIds;\n }\n\n \/\/ Remove the birthdays for contacts that are not there anymore\n foreach (QContactLocalId id, deletedContacts) {\n mCalendar->deleteBirthday(id);\n }\n\n \/\/ Update the calendar with the birthday changes.\n if (not birthdayChangedIds.isEmpty()) {\n fetchContacts(birthdayChangedIds.toList());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Full sync logic\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool\nCDBirthdayController::stampFileExists()\n{\n const QFile cacheFile(stampFilePath(), this);\n\n return cacheFile.exists();\n}\n\nvoid\nCDBirthdayController::createStampFile()\n{\n QFile cacheFile(stampFilePath(), this);\n\n if (not cacheFile.exists()) {\n if (not cacheFile.open(QIODevice::WriteOnly)) {\n warning() << Q_FUNC_INFO << \"Unable to create birthday plugin stamp file \"\n << cacheFile.fileName() << \" with error \" << cacheFile.errorString();\n } else {\n cacheFile.close();\n }\n }\n}\n\nQString\nCDBirthdayController::stampFilePath() const\n{\n return BasePlugin::cacheFileName(QLatin1String(\"calendar.stamp\"));\n}\n\nvoid\nCDBirthdayController::updateAllBirthdays()\n{\n QContactFetchHint fetchHint;\n static const QStringList detailDefinitions = QStringList() << QContactBirthday::DefinitionName\n << QContactDisplayLabel::DefinitionName;\n fetchHint.setDetailDefinitionsHint(detailDefinitions);\n\n \/\/ Filter on any contact with a birthday.\n QContactDetailFilter fetchFilter;\n fetchFilter.setDetailDefinitionName(QContactBirthday::DefinitionName);\n\n QContactFetchRequest * const fetchRequest = new QContactFetchRequest(this);\n fetchRequest->setManager(mManager);\n fetchRequest->setFetchHint(fetchHint);\n fetchRequest->setFilter(fetchFilter);\n\n connect(fetchRequest,\n SIGNAL(stateChanged(QContactAbstractRequest::State)),\n SLOT(onFullSyncRequestStateChanged(QContactAbstractRequest::State)));\n\n if (not fetchRequest->start()) {\n warning() << Q_FUNC_INFO << \"Unable to start contact birthdays fetch request\";\n delete fetchRequest;\n return;\n }\n\n debug() << \"Contact birthdays fetch request started\";\n}\n\nvoid\nCDBirthdayController::onFullSyncRequestStateChanged(QContactAbstractRequest::State newState)\n{\n if (processFetchRequest(qobject_cast(sender()), newState)) {\n \/\/ Create the stamp file only after a successful full sync.\n createStampFile();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Incremental sync logic\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nCDBirthdayController::fetchContacts(const QList &contactIds)\n{\n QContactFetchHint fetchHint;\n static const QStringList detailDefinitions = QStringList() << QContactBirthday::DefinitionName\n << QContactDisplayLabel::DefinitionName;\n fetchHint.setDetailDefinitionsHint(detailDefinitions);\n\n QContactLocalIdFilter fetchFilter;\n fetchFilter.setIds(contactIds);\n\n QContactFetchRequest * const fetchRequest = new QContactFetchRequest(this);\n fetchRequest->setManager(mManager);\n fetchRequest->setFetchHint(fetchHint);\n fetchRequest->setFilter(fetchFilter);\n\n connect(fetchRequest,\n SIGNAL(stateChanged(QContactAbstractRequest::State)),\n SLOT(onFetchRequestStateChanged(QContactAbstractRequest::State)));\n\n if (not fetchRequest->start()) {\n warning() << Q_FUNC_INFO << \"Unable to start birthday contact fetch request\";\n delete fetchRequest;\n return;\n }\n\n debug() << \"Birthday contacts fetch request started\";\n}\n\nvoid\nCDBirthdayController::onFetchRequestStateChanged(QContactAbstractRequest::State newState)\n{\n processFetchRequest(qobject_cast(sender()), newState);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Common sync logic\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool\nCDBirthdayController::processFetchRequest(QContactFetchRequest *const fetchRequest,\n QContactAbstractRequest::State newState)\n{\n if (fetchRequest == 0) {\n warning() << Q_FUNC_INFO << \"Invalid fetch request\";\n return false;\n }\n\n bool success = false;\n\n switch (newState) {\n case QContactAbstractRequest::FinishedState:\n debug() << \"Birthday contacts fetch request finished\";\n\n if (fetchRequest->error() != QContactManager::NoError) {\n warning() << Q_FUNC_INFO << \"Error during birthday contact fetch request, code: \"\n << fetchRequest->error();\n } else {\n updateBirthdays(fetchRequest->contacts());\n success = true;\n }\n\n break;\n\n case QContactAbstractRequest::CanceledState:\n break;\n\n default:\n return false;\n }\n\n \/\/ Provide hint we are done with this request.\n fetchRequest->deleteLater();\n\n return success;\n}\n\nvoid\nCDBirthdayController::updateBirthdays(const QList &changedBirthdays)\n{\n foreach (const QContact &contact, changedBirthdays) {\n const QContactBirthday contactBirthday = contact.detail();\n const QContactDisplayLabel contactDisplayLabel = contact.detail();\n const QDate calendarBirthday = mCalendar->birthdayDate(contact.localId());\n const QString calendarSummary = mCalendar->summary(contact.localId());\n\n \/\/ Display label or birthdate was removed from the contact, so delete it from the calendar.\n if (contactDisplayLabel.label().isNull() || contactBirthday.date().isNull()) {\n if (isDebugEnabled()) {\n debug() << \"Contact: \" << contact << \" removed birthday or displayLabel, so delete the calendar event\";\n }\n\n mCalendar->deleteBirthday(contact.localId());\n \/\/ Display label or birthdate was changed on the contact, so update the calendar.\n } else if ((contactDisplayLabel.label() != calendarSummary) ||\n (contactBirthday.date() != calendarBirthday)) {\n if (isDebugEnabled()) {\n debug() << \"Contact with calendar birthday: \" << contactBirthday.date()\n << \" and calendar displayLabel: \" << calendarSummary\n << \" changed details to: \" << contact << \", so update the calendar event\";\n }\n\n mCalendar->updateBirthday(contact);\n }\n }\n}\n<|endoftext|>"} {"text":"\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (people-users@projects.maemo.org)\n**\n** This file is part of contactsd.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at people-users@projects.maemo.org.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"test-expectation.h\"\n#include \"debug.h\"\n\n\/\/ --- TestExpectation ---\n\nvoid TestExpectation::verify(Event event, const QList &contactIds)\n{\n new TestFetchContacts(contactIds, event, this);\n}\n\nvoid TestExpectation::verify(Event event, const QList &contacts)\n{\n Q_UNUSED(event);\n Q_UNUSED(contacts);\n\n emitFinished();\n}\n\nvoid TestExpectation::verify(Event event, const QList &contactIds, QContactManager::Error error)\n{\n Q_UNUSED(event);\n Q_UNUSED(contactIds);\n Q_UNUSED(error);\n\n QVERIFY2(false, \"Error fetching contacts\");\n emitFinished();\n}\n\nvoid TestExpectation::emitFinished()\n{\n Q_EMIT finished();\n}\n\n\/\/ --- TestFetchContacts ---\n\nTestFetchContacts::TestFetchContacts(const QList &contactIds,\n Event event, TestExpectation *exp) : QObject(exp),\n mContactIds(contactIds), mEvent(event), mExp(exp)\n{\n QContactFetchByIdRequest *request = new QContactFetchByIdRequest();\n connect(request,\n SIGNAL(resultsAvailable()),\n SLOT(onContactsFetched()));\n request->setManager(mExp->contactManager());\n request->setLocalIds(contactIds);\n QVERIFY(request->start());\n}\n\nvoid TestFetchContacts::onContactsFetched()\n{\n QContactFetchByIdRequest *req = qobject_cast(sender());\n if (req == 0 || !req->isFinished()) {\n return;\n }\n\n if (req->error() == QContactManager::NoError) {\n \/\/ For some reason, we get VoiceMail signals sometimes. Ignore them.\n QList contacts;\n Q_FOREACH (const QContact &contact, req->contacts()) {\n if (contact.detail().tag() != QLatin1String(\"voicemail\")) {\n contacts << contact;\n }\n }\n mExp->verify(mEvent, contacts);\n } else {\n mExp->verify(mEvent, mContactIds, req->error());\n }\n\n deleteLater();\n req->deleteLater();\n}\n\n\/\/ --- TestExpectationInit ---\n\nvoid TestExpectationInit::verify(Event event, const QList &contacts)\n{\n QCOMPARE(event, EventChanged);\n QCOMPARE(contacts.count(), 1);\n QCOMPARE(contacts[0].localId(), contactManager()->selfContactId());\n emitFinished();\n}\n\n\/\/ --- TestExpectationCleanup ---\n\nTestExpectationCleanup::TestExpectationCleanup(int nContacts) :\n mNContacts(nContacts), mSelfChanged(false)\n{\n}\n\nvoid TestExpectationCleanup::verify(Event event, const QList &contacts)\n{\n QCOMPARE(event, EventChanged);\n QCOMPARE(contacts.count(), 1);\n QCOMPARE(contacts[0].localId(), contactManager()->selfContactId());\n mNContacts--;\n mSelfChanged = true;\n\n maybeEmitFinished();\n}\n\nvoid TestExpectationCleanup::verify(Event event, const QList &contactIds, QContactManager::Error error)\n{\n QCOMPARE(event, EventRemoved);\n QCOMPARE(error, QContactManager::DoesNotExistError);\n mNContacts -= contactIds.count();\n\n maybeEmitFinished();\n}\n\nvoid TestExpectationCleanup::maybeEmitFinished()\n{\n QVERIFY(mNContacts >= 0);\n if (mNContacts == 0 && mSelfChanged) {\n emitFinished();\n }\n}\n\n\/\/ --- TestExpectationContact ---\n\nTestExpectationContact::TestExpectationContact(Event event, QString accountUri):\n mAccountUri(accountUri), mEvent(event), mFlags(0), mPresence(TP_TESTS_CONTACTS_CONNECTION_STATUS_UNSET),\n mContactInfo(0)\n{\n}\n\nvoid TestExpectationContact::verify(Event event, const QList &contacts)\n{\n QCOMPARE(event, mEvent);\n QCOMPARE(contacts.count(), 1);\n mContact = contacts[0];\n verify(contacts[0]);\n emitFinished();\n}\n\nvoid TestExpectationContact::verify(Event event, const QList &contactIds, QContactManager::Error error)\n{\n QCOMPARE(event, EventRemoved);\n QCOMPARE(contactIds.count(), 1);\n QCOMPARE(error, QContactManager::DoesNotExistError);\n emitFinished();\n}\n\nvoid TestExpectationContact::verify(QContact contact)\n{\n debug() << contact;\n\n if (!mAccountUri.isEmpty()) {\n const QString uri = QString(\"telepathy:%1!%2\").arg(ACCOUNT_PATH).arg(mAccountUri);\n QList details = contact.details(\"DetailUri\", uri);\n QCOMPARE(details.count(), 1);\n QCOMPARE(details[0].value(\"AccountPath\"), QString(ACCOUNT_PATH));\n }\n\n if (mFlags & VerifyAlias) {\n QString label = contact.detail().label();\n QCOMPARE(label, mAlias);\n }\n\n if (mFlags & VerifyPresence) {\n QContactPresence::PresenceState presence;\n if (mAccountUri.isEmpty()) {\n QContactGlobalPresence presenceDetail = contact.detail();\n presence = presenceDetail.presenceState();\n } else {\n const QString uri = QString(\"presence:%1!%2\").arg(ACCOUNT_PATH).arg(mAccountUri);\n QList details = contact.details(\"DetailUri\", uri);\n QCOMPARE(details.count(), 1);\n presence = details[0].presenceState();\n }\n\n switch (mPresence) {\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_AVAILABLE:\n QCOMPARE(presence, QContactPresence::PresenceAvailable);\n break;\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_BUSY:\n QCOMPARE(presence, QContactPresence::PresenceBusy);\n break;\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_AWAY:\n QCOMPARE(presence, QContactPresence::PresenceAway);\n break;\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_OFFLINE:\n QCOMPARE(presence, QContactPresence::PresenceOffline);\n break;\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_UNKNOWN:\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_ERROR:\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_UNSET:\n QCOMPARE(presence, QContactPresence::PresenceUnknown);\n break;\n }\n }\n\n if (mFlags & VerifyAvatar) {\n QString avatarFileName = contact.detail().imageUrl().path();\n if (mAvatarData.isEmpty()) {\n QVERIFY2(avatarFileName.isEmpty(), \"Expected empty avatar filename\");\n } else {\n QFile file(avatarFileName);\n file.open(QIODevice::ReadOnly);\n QCOMPARE(file.readAll(), mAvatarData);\n file.close();\n }\n }\n\n if (mFlags & VerifyAuthorization) {\n const QString uri = QString(\"presence:%1!%2\").arg(ACCOUNT_PATH).arg(mAccountUri);\n QList details = contact.details(\"DetailUri\", uri);\n QCOMPARE(details.count(), 1);\n QCOMPARE(details[0].value(\"AuthStatusFrom\"), mSubscriptionState);\n QCOMPARE(details[0].value(\"AuthStatusTo\"), mPublishState);\n }\n\n if (mFlags & VerifyInfo) {\n uint nMatchedField = 0;\n\n Q_FOREACH (const QContactDetail &detail, contact.details()) {\n if (detail.definitionName() == \"PhoneNumber\") {\n QContactPhoneNumber phoneNumber = static_cast(detail);\n verifyContactInfo(\"tel\", QStringList() << phoneNumber.number());\n nMatchedField++;\n }\n else if (detail.definitionName() == \"Address\") {\n QContactAddress address = static_cast(detail);\n verifyContactInfo(\"adr\", QStringList() << address.postOfficeBox()\n << QString(\"unmapped\") \/\/ extended address is not mapped\n << address.street()\n << address.locality()\n << address.region()\n << address.postcode()\n << address.country());\n nMatchedField++;\n }\n else if (detail.definitionName() == \"EmailAddress\") {\n QContactEmailAddress emailAddress = static_cast(detail);\n verifyContactInfo(\"email\", QStringList() << emailAddress.emailAddress());\n nMatchedField++;\n }\n }\n\n if (mContactInfo != NULL) {\n QCOMPARE(nMatchedField, mContactInfo->len);\n }\n }\n\n if (mFlags & VerifyLocalId) {\n QCOMPARE(contact.localId(), mLocalId);\n }\n}\n\nvoid TestExpectationContact::verifyContactInfo(QString name, const QStringList values) const\n{\n QVERIFY2(mContactInfo != NULL, \"Found ContactInfo field, was expecting none\");\n\n bool found = false;\n for (uint i = 0; i < mContactInfo->len; i++) {\n gchar *c_name;\n gchar **c_parameters;\n gchar **c_values;\n\n tp_value_array_unpack((GValueArray*) g_ptr_array_index(mContactInfo, i),\n 3, &c_name, &c_parameters, &c_values);\n\n \/* if c_values_len < values.count() it could still be OK if all\n * additional values are empty. *\/\n gint c_values_len = g_strv_length(c_values);\n if (QString(c_name) != name || c_values_len > values.count()) {\n continue;\n }\n\n bool match = true;\n for (int j = 0; j < values.count(); j++) {\n if (values[j] == QString(\"unmapped\")) {\n continue;\n }\n if ((j < c_values_len && values[j] != QString(c_values[j])) ||\n (j >= c_values_len && !values[j].isEmpty())) {\n match = false;\n break;\n }\n }\n\n if (match) {\n found = true;\n break;\n }\n }\n\n QVERIFY2(found, \"Unexpected ContactInfo field\");\n}\n\n\/\/ --- TestExpectationDisconnect ---\n\nTestExpectationDisconnect::TestExpectationDisconnect(int nContacts) :\n TestExpectationContact(EventChanged), mNContacts(nContacts), mSelfChanged(false)\n{\n}\n\nvoid TestExpectationDisconnect::verify(Event event, const QList &contacts)\n{\n QCOMPARE(event, EventChanged);\n\n Q_FOREACH (const QContact contact, contacts) {\n if (contact.localId() == contactManager()->selfContactId()) {\n verifyPresence(TP_TESTS_CONTACTS_CONNECTION_STATUS_OFFLINE);\n mSelfChanged = true;\n } else {\n verifyPresence(TP_TESTS_CONTACTS_CONNECTION_STATUS_UNKNOWN);\n }\n TestExpectationContact::verify(contact);\n }\n\n mNContacts -= contacts.count();\n QVERIFY(mNContacts >= 0);\n if (mNContacts == 0 && mSelfChanged) {\n emitFinished();\n }\n}\n\n\/\/ --- TestExpectationMerge ---\n\nTestExpectationMerge::TestExpectationMerge(const QContactLocalId masterId,\n const QList mergeIds, const QList expectations)\n : mMasterId(masterId), mMergeIds(mergeIds), mGotMergedContact(false),\n mContactExpectations(expectations)\n{\n}\n\nvoid TestExpectationMerge::verify(Event event, const QList &contacts)\n{\n QCOMPARE(event, EventChanged);\n QCOMPARE(contacts.count(), 1);\n QCOMPARE(contacts[0].localId(), mMasterId);\n mGotMergedContact = true;\n\n Q_FOREACH (TestExpectationContact *exp, mContactExpectations) {\n exp->verify(contacts[0]);\n }\n\n maybeEmitFinished();\n}\n\n\nvoid TestExpectationMerge::verify(Event event, const QList &contactIds,\n QContactManager::Error error)\n{\n QCOMPARE(event, EventRemoved);\n QCOMPARE(error, QContactManager::DoesNotExistError);\n\n Q_FOREACH (QContactLocalId localId, contactIds) {\n QVERIFY(mMergeIds.contains(localId));\n mMergeIds.removeOne(localId);\n }\n\n maybeEmitFinished();\n}\n\nvoid TestExpectationMerge::maybeEmitFinished()\n{\n if (mMergeIds.isEmpty() && mGotMergedContact) {\n emitFinished();\n }\n}\nUnit tests: always print fetched contacts and really ignore events for voicemail\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (people-users@projects.maemo.org)\n**\n** This file is part of contactsd.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at people-users@projects.maemo.org.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"test-expectation.h\"\n#include \"debug.h\"\n\n\/\/ --- TestExpectation ---\n\nvoid TestExpectation::verify(Event event, const QList &contactIds)\n{\n new TestFetchContacts(contactIds, event, this);\n}\n\nvoid TestExpectation::verify(Event event, const QList &contacts)\n{\n Q_UNUSED(event);\n Q_UNUSED(contacts);\n\n emitFinished();\n}\n\nvoid TestExpectation::verify(Event event, const QList &contactIds, QContactManager::Error error)\n{\n Q_UNUSED(event);\n Q_UNUSED(contactIds);\n Q_UNUSED(error);\n\n QVERIFY2(false, \"Error fetching contacts\");\n emitFinished();\n}\n\nvoid TestExpectation::emitFinished()\n{\n Q_EMIT finished();\n}\n\n\/\/ --- TestFetchContacts ---\n\nTestFetchContacts::TestFetchContacts(const QList &contactIds,\n Event event, TestExpectation *exp) : QObject(exp),\n mContactIds(contactIds), mEvent(event), mExp(exp)\n{\n QContactFetchByIdRequest *request = new QContactFetchByIdRequest();\n connect(request,\n SIGNAL(resultsAvailable()),\n SLOT(onContactsFetched()));\n request->setManager(mExp->contactManager());\n request->setLocalIds(contactIds);\n QVERIFY(request->start());\n}\n\nvoid TestFetchContacts::onContactsFetched()\n{\n QContactFetchByIdRequest *req = qobject_cast(sender());\n if (req == 0 || !req->isFinished()) {\n return;\n }\n\n if (req->error() == QContactManager::NoError) {\n QList contacts;\n Q_FOREACH (const QContact &contact, req->contacts()) {\n debug() << \"Contact fetched:\\n\\n\" << contact << \"\\n\";\n\n \/\/ For some reason, we get VoiceMail signals sometimes. Ignore them.\n if (contact.detail().tag() == QLatin1String(\"voicemail\")) {\n debug() << \"Ignoring voicemail contact\";\n continue;\n }\n\n contacts << contact;\n }\n if (!contacts.isEmpty()) {\n mExp->verify(mEvent, contacts);\n }\n } else {\n mExp->verify(mEvent, mContactIds, req->error());\n }\n\n deleteLater();\n req->deleteLater();\n}\n\n\/\/ --- TestExpectationInit ---\n\nvoid TestExpectationInit::verify(Event event, const QList &contacts)\n{\n QCOMPARE(event, EventChanged);\n QCOMPARE(contacts.count(), 1);\n QCOMPARE(contacts[0].localId(), contactManager()->selfContactId());\n emitFinished();\n}\n\n\/\/ --- TestExpectationCleanup ---\n\nTestExpectationCleanup::TestExpectationCleanup(int nContacts) :\n mNContacts(nContacts), mSelfChanged(false)\n{\n}\n\nvoid TestExpectationCleanup::verify(Event event, const QList &contacts)\n{\n QCOMPARE(event, EventChanged);\n QCOMPARE(contacts.count(), 1);\n QCOMPARE(contacts[0].localId(), contactManager()->selfContactId());\n mNContacts--;\n mSelfChanged = true;\n\n maybeEmitFinished();\n}\n\nvoid TestExpectationCleanup::verify(Event event, const QList &contactIds, QContactManager::Error error)\n{\n QCOMPARE(event, EventRemoved);\n QCOMPARE(error, QContactManager::DoesNotExistError);\n mNContacts -= contactIds.count();\n\n maybeEmitFinished();\n}\n\nvoid TestExpectationCleanup::maybeEmitFinished()\n{\n QVERIFY(mNContacts >= 0);\n if (mNContacts == 0 && mSelfChanged) {\n emitFinished();\n }\n}\n\n\/\/ --- TestExpectationContact ---\n\nTestExpectationContact::TestExpectationContact(Event event, QString accountUri):\n mAccountUri(accountUri), mEvent(event), mFlags(0), mPresence(TP_TESTS_CONTACTS_CONNECTION_STATUS_UNSET),\n mContactInfo(0)\n{\n}\n\nvoid TestExpectationContact::verify(Event event, const QList &contacts)\n{\n QCOMPARE(event, mEvent);\n QCOMPARE(contacts.count(), 1);\n mContact = contacts[0];\n verify(contacts[0]);\n emitFinished();\n}\n\nvoid TestExpectationContact::verify(Event event, const QList &contactIds, QContactManager::Error error)\n{\n QCOMPARE(event, EventRemoved);\n QCOMPARE(contactIds.count(), 1);\n QCOMPARE(error, QContactManager::DoesNotExistError);\n emitFinished();\n}\n\nvoid TestExpectationContact::verify(QContact contact)\n{\n if (!mAccountUri.isEmpty()) {\n const QString uri = QString(\"telepathy:%1!%2\").arg(ACCOUNT_PATH).arg(mAccountUri);\n QList details = contact.details(\"DetailUri\", uri);\n QCOMPARE(details.count(), 1);\n QCOMPARE(details[0].value(\"AccountPath\"), QString(ACCOUNT_PATH));\n }\n\n if (mFlags & VerifyAlias) {\n QString label = contact.detail().label();\n QCOMPARE(label, mAlias);\n }\n\n if (mFlags & VerifyPresence) {\n QContactPresence::PresenceState presence;\n if (mAccountUri.isEmpty()) {\n QContactGlobalPresence presenceDetail = contact.detail();\n presence = presenceDetail.presenceState();\n } else {\n const QString uri = QString(\"presence:%1!%2\").arg(ACCOUNT_PATH).arg(mAccountUri);\n QList details = contact.details(\"DetailUri\", uri);\n QCOMPARE(details.count(), 1);\n presence = details[0].presenceState();\n }\n\n switch (mPresence) {\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_AVAILABLE:\n QCOMPARE(presence, QContactPresence::PresenceAvailable);\n break;\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_BUSY:\n QCOMPARE(presence, QContactPresence::PresenceBusy);\n break;\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_AWAY:\n QCOMPARE(presence, QContactPresence::PresenceAway);\n break;\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_OFFLINE:\n QCOMPARE(presence, QContactPresence::PresenceOffline);\n break;\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_UNKNOWN:\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_ERROR:\n case TP_TESTS_CONTACTS_CONNECTION_STATUS_UNSET:\n QCOMPARE(presence, QContactPresence::PresenceUnknown);\n break;\n }\n }\n\n if (mFlags & VerifyAvatar) {\n QString avatarFileName = contact.detail().imageUrl().path();\n if (mAvatarData.isEmpty()) {\n QVERIFY2(avatarFileName.isEmpty(), \"Expected empty avatar filename\");\n } else {\n QFile file(avatarFileName);\n file.open(QIODevice::ReadOnly);\n QCOMPARE(file.readAll(), mAvatarData);\n file.close();\n }\n }\n\n if (mFlags & VerifyAuthorization) {\n const QString uri = QString(\"presence:%1!%2\").arg(ACCOUNT_PATH).arg(mAccountUri);\n QList details = contact.details(\"DetailUri\", uri);\n QCOMPARE(details.count(), 1);\n QCOMPARE(details[0].value(\"AuthStatusFrom\"), mSubscriptionState);\n QCOMPARE(details[0].value(\"AuthStatusTo\"), mPublishState);\n }\n\n if (mFlags & VerifyInfo) {\n uint nMatchedField = 0;\n\n Q_FOREACH (const QContactDetail &detail, contact.details()) {\n if (detail.definitionName() == \"PhoneNumber\") {\n QContactPhoneNumber phoneNumber = static_cast(detail);\n verifyContactInfo(\"tel\", QStringList() << phoneNumber.number());\n nMatchedField++;\n }\n else if (detail.definitionName() == \"Address\") {\n QContactAddress address = static_cast(detail);\n verifyContactInfo(\"adr\", QStringList() << address.postOfficeBox()\n << QString(\"unmapped\") \/\/ extended address is not mapped\n << address.street()\n << address.locality()\n << address.region()\n << address.postcode()\n << address.country());\n nMatchedField++;\n }\n else if (detail.definitionName() == \"EmailAddress\") {\n QContactEmailAddress emailAddress = static_cast(detail);\n verifyContactInfo(\"email\", QStringList() << emailAddress.emailAddress());\n nMatchedField++;\n }\n }\n\n if (mContactInfo != NULL) {\n QCOMPARE(nMatchedField, mContactInfo->len);\n }\n }\n\n if (mFlags & VerifyLocalId) {\n QCOMPARE(contact.localId(), mLocalId);\n }\n}\n\nvoid TestExpectationContact::verifyContactInfo(QString name, const QStringList values) const\n{\n QVERIFY2(mContactInfo != NULL, \"Found ContactInfo field, was expecting none\");\n\n bool found = false;\n for (uint i = 0; i < mContactInfo->len; i++) {\n gchar *c_name;\n gchar **c_parameters;\n gchar **c_values;\n\n tp_value_array_unpack((GValueArray*) g_ptr_array_index(mContactInfo, i),\n 3, &c_name, &c_parameters, &c_values);\n\n \/* if c_values_len < values.count() it could still be OK if all\n * additional values are empty. *\/\n gint c_values_len = g_strv_length(c_values);\n if (QString(c_name) != name || c_values_len > values.count()) {\n continue;\n }\n\n bool match = true;\n for (int j = 0; j < values.count(); j++) {\n if (values[j] == QString(\"unmapped\")) {\n continue;\n }\n if ((j < c_values_len && values[j] != QString(c_values[j])) ||\n (j >= c_values_len && !values[j].isEmpty())) {\n match = false;\n break;\n }\n }\n\n if (match) {\n found = true;\n break;\n }\n }\n\n QVERIFY2(found, \"Unexpected ContactInfo field\");\n}\n\n\/\/ --- TestExpectationDisconnect ---\n\nTestExpectationDisconnect::TestExpectationDisconnect(int nContacts) :\n TestExpectationContact(EventChanged), mNContacts(nContacts), mSelfChanged(false)\n{\n}\n\nvoid TestExpectationDisconnect::verify(Event event, const QList &contacts)\n{\n QCOMPARE(event, EventChanged);\n\n Q_FOREACH (const QContact contact, contacts) {\n if (contact.localId() == contactManager()->selfContactId()) {\n verifyPresence(TP_TESTS_CONTACTS_CONNECTION_STATUS_OFFLINE);\n mSelfChanged = true;\n } else {\n verifyPresence(TP_TESTS_CONTACTS_CONNECTION_STATUS_UNKNOWN);\n }\n TestExpectationContact::verify(contact);\n }\n\n mNContacts -= contacts.count();\n QVERIFY(mNContacts >= 0);\n if (mNContacts == 0 && mSelfChanged) {\n emitFinished();\n }\n}\n\n\/\/ --- TestExpectationMerge ---\n\nTestExpectationMerge::TestExpectationMerge(const QContactLocalId masterId,\n const QList mergeIds, const QList expectations)\n : mMasterId(masterId), mMergeIds(mergeIds), mGotMergedContact(false),\n mContactExpectations(expectations)\n{\n}\n\nvoid TestExpectationMerge::verify(Event event, const QList &contacts)\n{\n QCOMPARE(event, EventChanged);\n QCOMPARE(contacts.count(), 1);\n QCOMPARE(contacts[0].localId(), mMasterId);\n mGotMergedContact = true;\n\n Q_FOREACH (TestExpectationContact *exp, mContactExpectations) {\n exp->verify(contacts[0]);\n }\n\n maybeEmitFinished();\n}\n\n\nvoid TestExpectationMerge::verify(Event event, const QList &contactIds,\n QContactManager::Error error)\n{\n QCOMPARE(event, EventRemoved);\n QCOMPARE(error, QContactManager::DoesNotExistError);\n\n Q_FOREACH (QContactLocalId localId, contactIds) {\n QVERIFY(mMergeIds.contains(localId));\n mMergeIds.removeOne(localId);\n }\n\n maybeEmitFinished();\n}\n\nvoid TestExpectationMerge::maybeEmitFinished()\n{\n if (mMergeIds.isEmpty() && mGotMergedContact) {\n emitFinished();\n }\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"client.h\"\n\nclient::client() :\n m_mouseLat(0.0f),\n m_mouseLon(0.0f),\n m_origin(0.0f, 150.0f, 0.0f),\n m_velocity(0.0f, 0.0f, 0.0f),\n m_isOnGround(false),\n m_isOnWall(false)\n{\n\n}\n\nu::map &getKeyState(int key = 0, bool keyDown = false, bool keyUp = false);\nvoid getMouseDelta(int *deltaX, int *deltaY);\n\nbool client::tryUnstick(const kdMap &map, float radius) {\n static const m::vec3 offsets[] = {\n m::vec3(-1.0f, 1.0f,-1.0f),\n m::vec3( 1.0f, 1.0f,-1.0f),\n m::vec3( 1.0f, 1.0f, 1.0f),\n m::vec3(-1.0f, 1.0f, 1.0f),\n m::vec3(-1.0f,-1.0f,-1.0f),\n m::vec3( 1.0f,-1.0f,-1.0f),\n m::vec3( 1.0f,-1.0f, 1.0f),\n m::vec3(-1.0f,-1.0f, 1.0f)\n };\n const float radiusScale = radius * 0.1f;\n for (size_t j = 1; j < 4; j++) {\n for (size_t i = 0; i < sizeof(offsets)\/sizeof(offsets[0]); i++) {\n m::vec3 tryPosition = m_origin + j * radiusScale * offsets[i];\n if (map.isSphereStuck(tryPosition, radius))\n continue;\n m_origin = tryPosition;\n return true;\n }\n }\n return false;\n}\n\nvoid client::update(const kdMap &map, float dt) {\n static constexpr float kMaxVelocity = 80.0f;\n static constexpr m::vec3 kGravity(0.0f, -98.0f, 0.0f);\n static constexpr float kRadius = 5.0f;\n\n kdSphereTrace trace;\n trace.radius = kRadius;\n\n m::vec3 velocity = m_velocity;\n m::vec3 originalVelocity = m_velocity;\n m::vec3 primalVelocity = m_velocity;\n m::vec3 newVelocity;\n velocity.maxLength(kMaxVelocity);\n\n m::vec3 planes[kdMap::kMaxClippingPlanes];\n m::vec3 pos = m_origin;\n float timeLeft = dt;\n float allFraction = 0.0f;\n size_t numBumps = kdMap::kMaxBumps;\n size_t numPlanes = 0;\n\n bool wallHit = false;\n bool groundHit = false;\n for (size_t bumpCount = 0; bumpCount < numBumps; bumpCount++) {\n if (velocity == m::vec3(0.0f, 0.0f, 0.0f))\n break;\n\n trace.start = pos;\n trace.dir = timeLeft * velocity;\n map.traceSphere(&trace);\n\n float f = m::clamp(trace.fraction, 0.0f, 1.0f);\n allFraction += f;\n\n if (f > 0.0f) {\n pos += trace.dir * f * kdMap::kFractionScale;\n originalVelocity = velocity;\n numPlanes = 0;\n }\n\n if (f == 1.0f)\n break;\n\n wallHit = true;\n\n timeLeft = timeLeft * (1.0f - f);\n\n if (trace.plane.n[1] > 0.7f)\n groundHit = true;\n\n if (numPlanes >= kdMap::kMaxClippingPlanes) {\n velocity = m::vec3(0.0f, 0.0f, 0.0f);\n break;\n }\n\n \/\/ next clipping plane\n planes[numPlanes++] = trace.plane.n;\n\n size_t i, j;\n for (i = 0; i < numPlanes; i++) {\n kdMap::clipVelocity(originalVelocity, planes[i], newVelocity, kdMap::kOverClip);\n for (j = 0; j < numPlanes; j++)\n if (j != i && !(planes[i] == planes[j]))\n if (newVelocity * planes[j] < 0.0f)\n break;\n if (j == numPlanes)\n break;\n }\n\n \/\/ did we make it through the entire plane set?\n if (i != numPlanes)\n velocity = newVelocity;\n else {\n \/\/ go along the planes crease\n if (numPlanes != 2) {\n velocity = m::vec3(0.0f, 0.0f, 0.0f);\n break;\n }\n m::vec3 dir = planes[0] ^ planes[1];\n float d = dir * velocity;\n velocity = dir * d;\n }\n\n if (velocity * primalVelocity <= 0.0f) {\n velocity = m::vec3(0.0f, 0.0f, 0.0f);\n break;\n }\n }\n\n if (allFraction == 0.0f) {\n velocity = m::vec3(0.0f, 0.0f, 0.0f);\n }\n\n m_isOnGround = groundHit;\n m_isOnWall = wallHit;\n if (groundHit) {\n velocity.y = 0.0f;\n } else {\n velocity += kGravity * dt;\n }\n\n \/\/ we could be stuck\n if (map.isSphereStuck(pos, kRadius)) {\n m_origin = pos;\n tryUnstick(map, kRadius);\n }\n\n m_origin = pos;\n m_velocity = velocity;\n\n u::vector commands;\n inputGetCommands(commands);\n inputMouseMove();\n\n move(commands);\n}\n\nvoid client::move(const u::vector &commands) {\n m::vec3 velocity = m_velocity;\n m::vec3 direction;\n m::vec3 side;\n m::vec3 up;\n m::vec3 newDirection(0.0f, 0.0f, 0.0f);\n m::vec3 jump(0.0f, 0.0f, 0.0f);\n m::quat rotation = m_rotation;\n\n rotation.getOrient(&direction, &up, &side);\n\n \/\/ at half of the 45 degrees in either direction invert the sign\n \/\/ We do it between two points to prevent a situation where the\n \/\/ camera is just at the right axis thus preventing movement.\n up = (m::toDegree(direction.y) > 45.0f \/ 2.0f) ? -up : up;\n m::vec3 upCamera;\n for (auto &it : commands) {\n switch (it) {\n case kCommandForward:\n newDirection += direction + up;\n break;\n case kCommandBackward:\n newDirection -= direction + up;\n break;\n case kCommandLeft:\n newDirection -= side;\n break;\n case kCommandRight:\n newDirection += side;\n break;\n case kCommandJump:\n jump = m::vec3(0.0f, 0.25f, 0.0f);\n break;\n }\n }\n\n const float kClientSpeed = 60.0f; \/\/ cm\/s\n const float kJumpSpeed = 130.0f; \/\/ cm\/s\n const float kStopSpeed = 90.0f; \/\/ -cm\/s\n\n newDirection.y = 0.0f;\n if (newDirection.absSquared() > 0.1f)\n newDirection.setLength(kClientSpeed);\n newDirection.y += velocity.y;\n if (m_isOnGround) {\n newDirection += jump * kJumpSpeed;\n }\n if (commands.size() == 0) {\n m::vec3 slowDown = m_velocity * kStopSpeed * 0.01f;\n slowDown.y = 0.0f;\n newDirection += slowDown;\n }\n m_lastDirection = direction;\n m_velocity = newDirection;\n}\n\nvoid client::inputMouseMove(void) {\n static const float kSensitivity = 0.50f \/ 6.0f;\n static const bool kInvert = true;\n const float invert = kInvert ? -1.0f : 1.0f;\n\n int deltaX;\n int deltaY;\n getMouseDelta(&deltaX, &deltaY);\n\n m_mouseLat -= (float)deltaY * kSensitivity * invert;\n m_mouseLat = m::clamp(m_mouseLat, -89.0f, 89.0f);\n\n m_mouseLon -= (float)deltaX * kSensitivity * invert;\n m_mouseLon = m::angleMod(m_mouseLon);\n\n m::quat qlat(m::vec3::xAxis, m_mouseLat * m::kDegToRad);\n m::quat qlon(m::vec3::yAxis, m_mouseLon * m::kDegToRad);\n\n setRotation(qlon * qlat);\n}\n\nvoid client::inputGetCommands(u::vector &commands) {\n u::map &keyState = getKeyState();\n commands.clear();\n if (keyState[SDLK_w]) commands.push_back(kCommandForward);\n if (keyState[SDLK_s]) commands.push_back(kCommandBackward);\n if (keyState[SDLK_a]) commands.push_back(kCommandLeft);\n if (keyState[SDLK_d]) commands.push_back(kCommandRight);\n if (keyState[SDLK_SPACE]) commands.push_back(kCommandJump);\n}\n\nvoid client::setRotation(const m::quat &rotation) {\n m_rotation = rotation;\n}\n\nvoid client::getDirection(m::vec3 *direction, m::vec3 *up, m::vec3 *side) const {\n return m_rotation.getOrient(direction, up, side);\n}\n\nconst m::quat &client::getRotation(void) const {\n return m_rotation;\n}\n\nm::vec3 client::getPosition(void) const {\n \/\/ adjust for eye height\n return m::vec3(m_origin.x, m_origin.y + 5.5f, m_origin.z);\n}\nuse the to functions instead#include \n\n#include \"client.h\"\n\nclient::client() :\n m_mouseLat(0.0f),\n m_mouseLon(0.0f),\n m_origin(0.0f, 150.0f, 0.0f),\n m_velocity(0.0f, 0.0f, 0.0f),\n m_isOnGround(false),\n m_isOnWall(false)\n{\n\n}\n\nu::map &getKeyState(int key = 0, bool keyDown = false, bool keyUp = false);\nvoid getMouseDelta(int *deltaX, int *deltaY);\n\nbool client::tryUnstick(const kdMap &map, float radius) {\n static const m::vec3 offsets[] = {\n m::vec3(-1.0f, 1.0f,-1.0f),\n m::vec3( 1.0f, 1.0f,-1.0f),\n m::vec3( 1.0f, 1.0f, 1.0f),\n m::vec3(-1.0f, 1.0f, 1.0f),\n m::vec3(-1.0f,-1.0f,-1.0f),\n m::vec3( 1.0f,-1.0f,-1.0f),\n m::vec3( 1.0f,-1.0f, 1.0f),\n m::vec3(-1.0f,-1.0f, 1.0f)\n };\n const float radiusScale = radius * 0.1f;\n for (size_t j = 1; j < 4; j++) {\n for (size_t i = 0; i < sizeof(offsets)\/sizeof(offsets[0]); i++) {\n m::vec3 tryPosition = m_origin + j * radiusScale * offsets[i];\n if (map.isSphereStuck(tryPosition, radius))\n continue;\n m_origin = tryPosition;\n return true;\n }\n }\n return false;\n}\n\nvoid client::update(const kdMap &map, float dt) {\n static constexpr float kMaxVelocity = 80.0f;\n static constexpr m::vec3 kGravity(0.0f, -98.0f, 0.0f);\n static constexpr float kRadius = 5.0f;\n\n kdSphereTrace trace;\n trace.radius = kRadius;\n\n m::vec3 velocity = m_velocity;\n m::vec3 originalVelocity = m_velocity;\n m::vec3 primalVelocity = m_velocity;\n m::vec3 newVelocity;\n velocity.maxLength(kMaxVelocity);\n\n m::vec3 planes[kdMap::kMaxClippingPlanes];\n m::vec3 pos = m_origin;\n float timeLeft = dt;\n float allFraction = 0.0f;\n size_t numBumps = kdMap::kMaxBumps;\n size_t numPlanes = 0;\n\n bool wallHit = false;\n bool groundHit = false;\n for (size_t bumpCount = 0; bumpCount < numBumps; bumpCount++) {\n if (velocity == m::vec3(0.0f, 0.0f, 0.0f))\n break;\n\n trace.start = pos;\n trace.dir = timeLeft * velocity;\n map.traceSphere(&trace);\n\n float f = m::clamp(trace.fraction, 0.0f, 1.0f);\n allFraction += f;\n\n if (f > 0.0f) {\n pos += trace.dir * f * kdMap::kFractionScale;\n originalVelocity = velocity;\n numPlanes = 0;\n }\n\n if (f == 1.0f)\n break;\n\n wallHit = true;\n\n timeLeft = timeLeft * (1.0f - f);\n\n if (trace.plane.n[1] > 0.7f)\n groundHit = true;\n\n if (numPlanes >= kdMap::kMaxClippingPlanes) {\n velocity = m::vec3(0.0f, 0.0f, 0.0f);\n break;\n }\n\n \/\/ next clipping plane\n planes[numPlanes++] = trace.plane.n;\n\n size_t i, j;\n for (i = 0; i < numPlanes; i++) {\n kdMap::clipVelocity(originalVelocity, planes[i], newVelocity, kdMap::kOverClip);\n for (j = 0; j < numPlanes; j++)\n if (j != i && !(planes[i] == planes[j]))\n if (newVelocity * planes[j] < 0.0f)\n break;\n if (j == numPlanes)\n break;\n }\n\n \/\/ did we make it through the entire plane set?\n if (i != numPlanes)\n velocity = newVelocity;\n else {\n \/\/ go along the planes crease\n if (numPlanes != 2) {\n velocity = m::vec3(0.0f, 0.0f, 0.0f);\n break;\n }\n m::vec3 dir = planes[0] ^ planes[1];\n float d = dir * velocity;\n velocity = dir * d;\n }\n\n if (velocity * primalVelocity <= 0.0f) {\n velocity = m::vec3(0.0f, 0.0f, 0.0f);\n break;\n }\n }\n\n if (allFraction == 0.0f) {\n velocity = m::vec3(0.0f, 0.0f, 0.0f);\n }\n\n m_isOnGround = groundHit;\n m_isOnWall = wallHit;\n if (groundHit) {\n velocity.y = 0.0f;\n } else {\n velocity += kGravity * dt;\n }\n\n \/\/ we could be stuck\n if (map.isSphereStuck(pos, kRadius)) {\n m_origin = pos;\n tryUnstick(map, kRadius);\n }\n\n m_origin = pos;\n m_velocity = velocity;\n\n u::vector commands;\n inputGetCommands(commands);\n inputMouseMove();\n\n move(commands);\n}\n\nvoid client::move(const u::vector &commands) {\n m::vec3 velocity = m_velocity;\n m::vec3 direction;\n m::vec3 side;\n m::vec3 up;\n m::vec3 newDirection(0.0f, 0.0f, 0.0f);\n m::vec3 jump(0.0f, 0.0f, 0.0f);\n m::quat rotation = m_rotation;\n\n rotation.getOrient(&direction, &up, &side);\n\n \/\/ at half of the 45 degrees in either direction invert the sign\n \/\/ We do it between two points to prevent a situation where the\n \/\/ camera is just at the right axis thus preventing movement.\n up = (m::toDegree(direction.y) > 45.0f \/ 2.0f) ? -up : up;\n m::vec3 upCamera;\n for (auto &it : commands) {\n switch (it) {\n case kCommandForward:\n newDirection += direction + up;\n break;\n case kCommandBackward:\n newDirection -= direction + up;\n break;\n case kCommandLeft:\n newDirection -= side;\n break;\n case kCommandRight:\n newDirection += side;\n break;\n case kCommandJump:\n jump = m::vec3(0.0f, 0.25f, 0.0f);\n break;\n }\n }\n\n const float kClientSpeed = 60.0f; \/\/ cm\/s\n const float kJumpSpeed = 130.0f; \/\/ cm\/s\n const float kStopSpeed = 90.0f; \/\/ -cm\/s\n\n newDirection.y = 0.0f;\n if (newDirection.absSquared() > 0.1f)\n newDirection.setLength(kClientSpeed);\n newDirection.y += velocity.y;\n if (m_isOnGround) {\n newDirection += jump * kJumpSpeed;\n }\n if (commands.size() == 0) {\n m::vec3 slowDown = m_velocity * kStopSpeed * 0.01f;\n slowDown.y = 0.0f;\n newDirection += slowDown;\n }\n m_lastDirection = direction;\n m_velocity = newDirection;\n}\n\nvoid client::inputMouseMove(void) {\n static const float kSensitivity = 0.50f \/ 6.0f;\n static const bool kInvert = true;\n const float invert = kInvert ? -1.0f : 1.0f;\n\n int deltaX;\n int deltaY;\n getMouseDelta(&deltaX, &deltaY);\n\n m_mouseLat -= (float)deltaY * kSensitivity * invert;\n m_mouseLat = m::clamp(m_mouseLat, -89.0f, 89.0f);\n\n m_mouseLon -= (float)deltaX * kSensitivity * invert;\n m_mouseLon = m::angleMod(m_mouseLon);\n\n m::quat qlat(m::vec3::xAxis, m::toRadian(m_mouseLat));\n m::quat qlon(m::vec3::yAxis, m::toRadian(m_mouseLon));\n\n setRotation(qlon * qlat);\n}\n\nvoid client::inputGetCommands(u::vector &commands) {\n u::map &keyState = getKeyState();\n commands.clear();\n if (keyState[SDLK_w]) commands.push_back(kCommandForward);\n if (keyState[SDLK_s]) commands.push_back(kCommandBackward);\n if (keyState[SDLK_a]) commands.push_back(kCommandLeft);\n if (keyState[SDLK_d]) commands.push_back(kCommandRight);\n if (keyState[SDLK_SPACE]) commands.push_back(kCommandJump);\n}\n\nvoid client::setRotation(const m::quat &rotation) {\n m_rotation = rotation;\n}\n\nvoid client::getDirection(m::vec3 *direction, m::vec3 *up, m::vec3 *side) const {\n return m_rotation.getOrient(direction, up, side);\n}\n\nconst m::quat &client::getRotation(void) const {\n return m_rotation;\n}\n\nm::vec3 client::getPosition(void) const {\n \/\/ adjust for eye height\n return m::vec3(m_origin.x, m_origin.y + 5.5f, m_origin.z);\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2013, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"DouglasPeucker.h\"\n\n#include \"..\/DataStructures\/Range.h\"\n#include \"..\/DataStructures\/SegmentInformation.h\"\n\n#include \n\n#include \n\n#include \n\n#include \n\nnamespace\n{\nstruct CoordinatePairCalculator\n{\n CoordinatePairCalculator() = delete;\n CoordinatePairCalculator(const FixedPointCoordinate &coordinate_a,\n const FixedPointCoordinate &coordinate_b)\n {\n \/\/ initialize distance calculator with two fixed coordinates a, b\n const float RAD = 0.017453292519943295769236907684886f;\n first_lat = (coordinate_a.lat \/ COORDINATE_PRECISION) * RAD;\n first_lon = (coordinate_a.lon \/ COORDINATE_PRECISION) * RAD;\n second_lat = (coordinate_b.lat \/ COORDINATE_PRECISION) * RAD;\n second_lon = (coordinate_b.lon \/ COORDINATE_PRECISION) * RAD;\n }\n\n int operator()(FixedPointCoordinate &other) const\n {\n \/\/ set third coordinate c\n const float RAD = 0.017453292519943295769236907684886f;\n const float earth_radius = 6372797.560856f;\n const float float_lat1 = (other.lat \/ COORDINATE_PRECISION) * RAD;\n const float float_lon1 = (other.lon \/ COORDINATE_PRECISION) * RAD;\n\n \/\/ compute distance (a,c)\n const float x_value_1 = (first_lon - float_lon1) * cos((float_lat1 + first_lat) \/ 2.f);\n const float y_value_1 = first_lat - float_lat1;\n const float dist1 = sqrt(std::pow(x_value_1, 2) + std::pow(y_value_1, 2)) * earth_radius;\n\n \/\/ compute distance (b,c)\n const float x_value_2 = (second_lon - float_lon1) * cos((float_lat1 + second_lat) \/ 2.f);\n const float y_value_2 = second_lat - float_lat1;\n const float dist2 = sqrt(std::pow(x_value_2, 2) + std::pow(y_value_2, 2)) * earth_radius;\n\n \/\/ return the minimum\n return static_cast(std::min(dist1, dist2));\n }\n\n float first_lat;\n float first_lon;\n float second_lat;\n float second_lon;\n};\n}\n\nvoid DouglasPeucker::Run(std::vector &input_geometry, const unsigned zoom_level)\n{\n Run(std::begin(input_geometry), std::end(input_geometry), zoom_level);\n}\n\nvoid DouglasPeucker::Run(RandomAccessIt begin, RandomAccessIt end, const unsigned zoom_level)\n{\n unsigned size = std::distance(begin, end);\n if (size < 2)\n {\n return;\n }\n\n begin->necessary = true;\n std::prev(end)->necessary = true;\n\n {\n BOOST_ASSERT_MSG(zoom_level < 19, \"unsupported zoom level\");\n RandomAccessIt left_border = begin;\n RandomAccessIt right_border = std::next(begin);\n \/\/ Sweep over array and identify those ranges that need to be checked\n do\n {\n \/\/ traverse list until new border element found\n if (right_border->necessary)\n {\n \/\/ sanity checks\n BOOST_ASSERT(left_border->necessary);\n BOOST_ASSERT(right_border->necessary);\n recursion_stack.emplace(left_border, right_border);\n left_border = right_border;\n }\n ++right_border;\n } while (right_border != end);\n }\n\n \/\/ mark locations as 'necessary' by divide-and-conquer\n while (!recursion_stack.empty())\n {\n \/\/ pop next element\n const GeometryRange pair = recursion_stack.top();\n recursion_stack.pop();\n \/\/ sanity checks\n BOOST_ASSERT_MSG(pair.first->necessary, \"left border must be necessary\");\n BOOST_ASSERT_MSG(pair.second->necessary, \"right border must be necessary\");\n BOOST_ASSERT_MSG(std::distance(pair.second, end) > 0, \"right border outside of geometry\");\n BOOST_ASSERT_MSG(std::distance(pair.first, pair.second) >= 0, \"left border on the wrong side\");\n\n int max_int_distance = 0;\n auto farthest_entry_it = pair.second;\n const CoordinatePairCalculator dist_calc(pair.first->location, pair.second->location);\n\n \/\/ sweep over range to find the maximum\n for (auto it = std::next(pair.first); it != pair.second; ++it)\n {\n const int distance = dist_calc(it->location);\n \/\/ found new feasible maximum?\n if (distance > max_int_distance && distance > DOUGLAS_PEUCKER_THRESHOLDS[zoom_level])\n {\n farthest_entry_it = it;\n max_int_distance = distance;\n }\n }\n\n\n \/\/ check if maximum violates a zoom level dependent threshold\n if (max_int_distance > DOUGLAS_PEUCKER_THRESHOLDS[zoom_level])\n {\n \/\/ mark idx as necessary\n farthest_entry_it->necessary = true;\n if (1 < std::distance(pair.first, farthest_entry_it))\n {\n recursion_stack.emplace(pair.first, farthest_entry_it);\n }\n if (1 < std::distance(farthest_entry_it, pair.second))\n {\n recursion_stack.emplace(farthest_entry_it, pair.second);\n }\n }\n }\n}\nreformatting\/*\n\nCopyright (c) 2013, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"DouglasPeucker.h\"\n\n#include \"..\/DataStructures\/Range.h\"\n#include \"..\/DataStructures\/SegmentInformation.h\"\n\n#include \n\n#include \n\n#include \n\n#include \n\nnamespace\n{\nstruct CoordinatePairCalculator\n{\n CoordinatePairCalculator() = delete;\n CoordinatePairCalculator(const FixedPointCoordinate &coordinate_a,\n const FixedPointCoordinate &coordinate_b)\n {\n \/\/ initialize distance calculator with two fixed coordinates a, b\n const float RAD = 0.017453292519943295769236907684886f;\n first_lat = (coordinate_a.lat \/ COORDINATE_PRECISION) * RAD;\n first_lon = (coordinate_a.lon \/ COORDINATE_PRECISION) * RAD;\n second_lat = (coordinate_b.lat \/ COORDINATE_PRECISION) * RAD;\n second_lon = (coordinate_b.lon \/ COORDINATE_PRECISION) * RAD;\n }\n\n int operator()(FixedPointCoordinate &other) const\n {\n \/\/ set third coordinate c\n const float RAD = 0.017453292519943295769236907684886f;\n const float earth_radius = 6372797.560856f;\n const float float_lat1 = (other.lat \/ COORDINATE_PRECISION) * RAD;\n const float float_lon1 = (other.lon \/ COORDINATE_PRECISION) * RAD;\n\n \/\/ compute distance (a,c)\n const float x_value_1 = (first_lon - float_lon1) * cos((float_lat1 + first_lat) \/ 2.f);\n const float y_value_1 = first_lat - float_lat1;\n const float dist1 = sqrt(std::pow(x_value_1, 2) + std::pow(y_value_1, 2)) * earth_radius;\n\n \/\/ compute distance (b,c)\n const float x_value_2 = (second_lon - float_lon1) * cos((float_lat1 + second_lat) \/ 2.f);\n const float y_value_2 = second_lat - float_lat1;\n const float dist2 = sqrt(std::pow(x_value_2, 2) + std::pow(y_value_2, 2)) * earth_radius;\n\n \/\/ return the minimum\n return static_cast(std::min(dist1, dist2));\n }\n\n float first_lat;\n float first_lon;\n float second_lat;\n float second_lon;\n};\n}\n\nvoid DouglasPeucker::Run(std::vector &input_geometry, const unsigned zoom_level)\n{\n Run(std::begin(input_geometry), std::end(input_geometry), zoom_level);\n}\n\nvoid DouglasPeucker::Run(RandomAccessIt begin, RandomAccessIt end, const unsigned zoom_level)\n{\n unsigned size = std::distance(begin, end);\n if (size < 2)\n {\n return;\n }\n\n begin->necessary = true;\n std::prev(end)->necessary = true;\n\n {\n BOOST_ASSERT_MSG(zoom_level < 19, \"unsupported zoom level\");\n RandomAccessIt left_border = begin;\n RandomAccessIt right_border = std::next(begin);\n \/\/ Sweep over array and identify those ranges that need to be checked\n do\n {\n \/\/ traverse list until new border element found\n if (right_border->necessary)\n {\n \/\/ sanity checks\n BOOST_ASSERT(left_border->necessary);\n BOOST_ASSERT(right_border->necessary);\n recursion_stack.emplace(left_border, right_border);\n left_border = right_border;\n }\n ++right_border;\n } while (right_border != end);\n }\n\n \/\/ mark locations as 'necessary' by divide-and-conquer\n while (!recursion_stack.empty())\n {\n \/\/ pop next element\n const GeometryRange pair = recursion_stack.top();\n recursion_stack.pop();\n \/\/ sanity checks\n BOOST_ASSERT_MSG(pair.first->necessary, \"left border must be necessary\");\n BOOST_ASSERT_MSG(pair.second->necessary, \"right border must be necessary\");\n BOOST_ASSERT_MSG(std::distance(pair.second, end) > 0, \"right border outside of geometry\");\n BOOST_ASSERT_MSG(std::distance(pair.first, pair.second) >= 0,\n \"left border on the wrong side\");\n\n int max_int_distance = 0;\n auto farthest_entry_it = pair.second;\n const CoordinatePairCalculator dist_calc(pair.first->location, pair.second->location);\n\n \/\/ sweep over range to find the maximum\n for (auto it = std::next(pair.first); it != pair.second; ++it)\n {\n const int distance = dist_calc(it->location);\n \/\/ found new feasible maximum?\n if (distance > max_int_distance && distance > DOUGLAS_PEUCKER_THRESHOLDS[zoom_level])\n {\n farthest_entry_it = it;\n max_int_distance = distance;\n }\n }\n\n \/\/ check if maximum violates a zoom level dependent threshold\n if (max_int_distance > DOUGLAS_PEUCKER_THRESHOLDS[zoom_level])\n {\n \/\/ mark idx as necessary\n farthest_entry_it->necessary = true;\n if (1 < std::distance(pair.first, farthest_entry_it))\n {\n recursion_stack.emplace(pair.first, farthest_entry_it);\n }\n if (1 < std::distance(farthest_entry_it, pair.second))\n {\n recursion_stack.emplace(farthest_entry_it, pair.second);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"#include \"dafs\/node.hpp\"\n\nnamespace dafs\n{\n Node::Node()\n : slot_minus(dafs::Root(\"p-minus\")),\n slot_zero(dafs::Root(\"p-zero\")),\n slot_plus(dafs::Root(\"p-plus\"))\n {\n }\n\n\n dafs::Partition&\n Node::GetPartition(Slot slot)\n {\n switch (slot)\n {\n case Slot::Minus:\n {\n return slot_minus;\n }\n case Slot::Zero:\n {\n return slot_zero;\n }\n case Slot::Plus:\n {\n return slot_plus;\n }\n }\n }\n\n\n dafs::Partition&\n Node::GetPartition(Identity identity)\n {\n return slot_zero;\n }\n}\nImplement identity to partition association#include \"dafs\/node.hpp\"\n\nnamespace dafs\n{\n Node::Node()\n : slot_minus(dafs::Root(\"p-minus\")),\n slot_zero(dafs::Root(\"p-zero\")),\n slot_plus(dafs::Root(\"p-plus\"))\n {\n }\n\n\n dafs::Partition&\n Node::GetPartition(Slot slot)\n {\n switch (slot)\n {\n case Slot::Minus:\n {\n return slot_minus;\n }\n case Slot::Zero:\n {\n return slot_zero;\n }\n case Slot::Plus:\n {\n return slot_plus;\n }\n }\n }\n\n\n dafs::Partition&\n Node::GetPartition(Identity identity)\n {\n if (identity < slot_minus.GetIdentity())\n {\n return slot_minus;\n }\n else if (slot_plus.GetIdentity() < identity)\n {\n return slot_plus;\n }\n else\n {\n return slot_zero;\n }\n }\n}\n<|endoftext|>"} {"text":"\/* ****************************************************************************\n*\n* FILE main_samsonWorker.cpp\n*\n* AUTHOR Ken Zangelin\n*\n* CREATION DATE Dec 14 2010\n*\n*\/\n#include \"parseArgs\/parseArgs.h\"\n#include \"parseArgs\/paIsSet.h\"\n#include \"logMsg\/logMsg.h\"\n#include \"parseArgs\/paConfig.h\"\n#include \"logMsg\/traceLevels.h\"\n\n#include \n\n\n#include \"au\/LockDebugger.h\" \/\/ au::LockDebugger\n#include \"au\/ThreadManager.h\"\n\n#include \"engine\/MemoryManager.h\"\n#include \"engine\/Engine.h\"\n#include \"engine\/DiskManager.h\"\n#include \"engine\/ProcessManager.h\"\n\n#include \"samson\/common\/samsonVersion.h\"\n#include \"samson\/common\/samsonVars.h\"\n#include \"samson\/common\/SamsonSetup.h\"\n#include \"samson\/common\/daemonize.h\"\n#include \"samson\/common\/MemoryCheck.h\"\n#include \"samson\/network\/WorkerNetwork.h\"\n#include \"samson\/worker\/SamsonWorker.h\"\n#include \"samson\/isolated\/SharedMemoryManager.h\"\n#include \"samson\/stream\/BlockManager.h\"\n#include \"samson\/module\/ModulesManager.h\"\n\n\n\n\/* ****************************************************************************\n*\n* Option variables\n*\/\nSAMSON_ARG_VARS;\n\nbool fg;\nbool noLog;\nint valgrind;\nint port;\nint web_port;\n\n\n\n\/* ****************************************************************************\n*\n* parse arguments\n*\/\nPaArgument paArgs[] =\n{\n SAMSON_ARGS,\n { \"-fg\", &fg, \"SAMSON_WORKER_FOREGROUND\", PaBool, PaOpt, false, false, true, \"don't start as daemon\" },\n { \"-port\", &port, \"\", PaInt, PaOpt, SAMSON_WORKER_PORT, 1, 9999, \"Port to receive new connections\" },\n { \"-web_port\", &web_port, \"\", PaInt, PaOpt, SAMSON_WORKER_WEB_PORT, 1, 9999, \"Port to receive new connections\" },\n { \"-nolog\", &noLog, \"SAMSON_WORKER_NO_LOG\", PaBool, PaOpt, false, false, true, \"no logging\" },\n { \"-valgrind\", &valgrind, \"SAMSON_WORKER_VALGRIND\", PaInt, PaOpt, 0, 0, 20, \"help valgrind debug process\" },\n\n PA_END_OF_ARGS\n};\n\n\n\n\/* ****************************************************************************\n*\n* global variables\n*\/\nint logFd = -1;\nsamson::SamsonWorker* worker = NULL;\nau::LockDebugger* lockDebugger = NULL;\nengine::SharedMemoryManager* smManager = NULL;\n\n\n\n\/* ****************************************************************************\n*\n* man texts -\n*\/\nstatic const char* manSynopsis = \" [OPTION]\";\nstatic const char* manShortDescription = \"samsond is the main process in a SAMSON system.\\n\\n\";\nstatic const char* manDescription =\n \"\\n\"\n \"samsond is the main process in a SAMSON system. All the nodes in the cluster has its own samsonWorker process\\n\"\n \"All samsond processes are responsible for processing a segment of available data\"\n \"All clients of the platform ( delila's ) are connected to all samsonWorkers in the system\"\n \"See samson documentation to get more information about how to get a SAMSON system up and running\"\n \"\\n\";\n\nstatic const char* manExitStatus = \"0 if OK\\n 1-255 error\\n\";\nstatic const char* manAuthor = \"Written by Andreu Urruela, Ken Zangelin and J.Gregorio Escalada.\";\nstatic const char* manReportingBugs = \"bugs to samson-dev@tid.es\\n\";\nstatic const char* manCopyright = \"Copyright (C) 2011 Telefonica Investigacion y Desarrollo\";\nstatic const char* manVersion = SAMSON_VERSION;\n\n\nvoid captureSIGINT( int s )\n{\n s = 3;\n LM_X(1, (\"Signal SIGINT\"));\n}\n\nvoid captureSIGPIPE( int s )\n{\n s = 3;\n LM_M((\"Captured SIGPIPE\"));\n}\n\nvoid captureSIGTERM( int s )\n{\n s = 3;\n LM_M((\"Captured SIGTERM\"));\n\n LM_M((\"Cleaning up\"));\n std::string pid_file_name = au::str(\"%s\/samsond.pid\" , paLogFilePath );\n if ( remove (pid_file_name.c_str()) != 0)\n {\n LM_W((\"Error deleting the pid file %s\", pid_file_name.c_str() ));\n }\n exit(1);\n}\n\n\n\nvoid cleanup(void)\n{\n google::protobuf::ShutdownProtobufLibrary();\n\n printf(\"Shutting down worker components (worker at %p)\\n\", worker);\n if (worker)\n {\n printf(\"deleting worker\\n\");\n delete worker;\n }\n\n printf(\"Shutting down LockDebugger\\n\");\n au::LockDebugger::destroy();\n\n if (smManager != NULL)\n {\n printf(\"Shutting down Shared Memory Manager\\n\");\n delete smManager;\n smManager = NULL;\n }\n\n printf(\"Shutting down SamsonSetup\\n\");\n samson::SamsonSetup::destroy();\n\n printf(\"destroying ProcessManager\\n\");\n engine::ProcessManager::destroy();\n\n printf(\"destroying DiskManager\\n\");\n engine::DiskManager::destroy();\n\n printf(\"destroying MemoryManager\\n\");\n engine::MemoryManager::destroy();\n\n printf(\"destroying Engine\\n\");\n engine::Engine::destroy();\n\n printf(\"destroying ModulesManager\\n\");\n samson::ModulesManager::destroy();\n\n paConfigCleanup();\n lmCleanProgName();\n}\n\n\nstatic void valgrindExit(int v)\n{\n if (v == valgrind)\n {\n LM_M((\"Valgrind option is %d - I exit\", v));\n exit(0);\n }\n}\n\n\n\n\/* ****************************************************************************\n*\n* main - \n*\/\nint main(int argC, const char *argV[])\n{\n atexit(cleanup);\n\n paConfig(\"builtin prefix\", (void*) \"SS_WORKER_\");\n paConfig(\"usage and exit on any warning\", (void*) true);\n\n \/\/ Andreu: samsonWorker is not a console in foreground (debug) mode ( to ask to status with commands )\n paConfig(\"log to screen\", (void*) \"only errors\");\n \/\/paConfig(\"log to screen\", (void*) (void*) false);\n \n paConfig(\"log file line format\", (void*) \"TYPE:DATE:EXEC-AUX\/FILE[LINE](p.PID)(t.TID) FUNC: TEXT\");\n paConfig(\"screen line format\", (void*) \"TYPE@TIME EXEC: TEXT\");\n paConfig(\"log to file\", (void*) true);\n\n paConfig(\"man synopsis\", (void*) manSynopsis);\n paConfig(\"man shortdescription\", (void*) manShortDescription);\n paConfig(\"man description\", (void*) manDescription);\n paConfig(\"man exitstatus\", (void*) manExitStatus);\n paConfig(\"man author\", (void*) manAuthor);\n paConfig(\"man reportingbugs\", (void*) manReportingBugs);\n paConfig(\"man copyright\", (void*) manCopyright);\n paConfig(\"man version\", (void*) manVersion);\n\n const char* extra = paIsSetSoGet(argC, (char**) argV, \"-port\");\n paParse(paArgs, argC, (char**) argV, 1, false, extra);\n\n valgrindExit(1);\n\n lmAux((char*) \"father\");\n\n LM_V((\"Started with arguments:\"));\n for (int ix = 0; ix < argC; ix++)\n LM_V((\" %02d: '%s'\", ix, argV[ix]));\n\n logFd = lmFirstDiskFileDescriptor();\n \n \/\/ Capturing SIGPIPE\n if (signal(SIGPIPE, captureSIGPIPE) == SIG_ERR)\n LM_W((\"SIGPIPE cannot be handled\"));\n\n if (signal(SIGINT, captureSIGINT) == SIG_ERR)\n LM_W((\"SIGINT cannot be handled\"));\n\n if (signal(SIGTERM, captureSIGTERM) == SIG_ERR)\n LM_W((\"SIGTERM cannot be handled\"));\n\n \/\/ Init basic setup stuff (necessary for memory check)\n lockDebugger = au::LockDebugger::shared(); \/\/ VALGRIND complains ...\n samson::SamsonSetup::init(samsonHome, samsonWorking); \/\/ Load setup and create default directories\n \n valgrindExit(2);\n\n \/\/ Check to see if the current memory configuration is ok or not\n if (samson::MemoryCheck() == false)\n LM_X(1,(\"Insufficient memory configured. Check %ssamsonWorkerLog for more information.\", paLogFilePath));\n \n if (fg == false)\n {\n std::cout << \"OK. samsonWorker is now working in background.\\n\";\n daemonize();\n }\n\n valgrindExit(3);\n \/\/ ------------------------------------------------------ \n \/\/ Write pid in \/var\/log\/samson\/samsond.pid\n \/\/ ------------------------------------------------------\n\n char pid_file_name[256];\n snprintf(pid_file_name, sizeof(pid_file_name), \"%s\/samsond.pid\", paLogFilePath);\n FILE *file = fopen(pid_file_name, \"w\");\n if (!file)\n LM_X(1, (\"Error opening file '%s' to store pid\", pid_file_name));\n int pid = (int) getpid();\n if (fprintf(file, \"%d\" , pid) == 0)\n LM_X(1,(\"Error writing pid %d to file %s\", pid, pid_file_name));\n fclose(file);\n \/\/ ------------------------------------------------------ \n \n \/\/ Make sure this singleton is created just once\n LM_D((\"createWorkingDirectories\"));\n samson::SamsonSetup::shared()->createWorkingDirectories(); \/\/ Create working directories\n \n valgrindExit(4);\n LM_D((\"engine::Engine::init\"));\n engine::Engine::init();\n\n valgrindExit(5);\n LM_D((\"engine::SharedMemoryManager::init\"));\n engine::SharedMemoryManager::init(samson::SamsonSetup::shared()->getInt(\"general.num_processess\") , samson::SamsonSetup::shared()->getUInt64(\"general.shared_memory_size_per_buffer\")); \/\/ VALGRIND complains ...\n smManager = engine::SharedMemoryManager::shared();\n\n valgrindExit(6);\n LM_D((\"engine::DiskManager::init\"));\n engine::DiskManager::init(1);\n\n valgrindExit(7);\n LM_D((\"engine::ProcessManager::init\"));\n engine::ProcessManager::init(samson::SamsonSetup::shared()->getInt(\"general.num_processess\"));\n\n valgrindExit(8);\n LM_D((\"engine::MemoryManager::init\"));\n engine::MemoryManager::init(samson::SamsonSetup::shared()->getUInt64(\"general.memory\"));\n\n valgrindExit(9);\n LM_D((\"samson::ModulesManager::init\"));\n samson::ModulesManager::init();\n\n valgrindExit(10);\n LM_D((\"samson::stream::BlockManager::init\"));\n samson::stream::BlockManager::init();\n\n valgrindExit(11);\n\n \/\/ Instance of network object and initialization\n \/\/ --------------------------------------------------------------------\n samson::WorkerNetwork* networkP = new samson::WorkerNetwork(port, web_port);\n \n valgrindExit(12);\n\n \/\/ Instance of SamsonWorker object (network contains at least the number of workers)\n \/\/ -----------------------------------------------------------------------------------\n worker = new samson::SamsonWorker(networkP);\n\n LM_M((\"Worker Running\"));\n LM_D((\"worker at %p\", worker));\n valgrindExit(13);\n\n if (fg == false)\n {\n while (true)\n sleep(10);\n }\n\n worker->runConsole();\n \n LM_D((\"Worker Cleanup\"));\n \n if (worker)\n delete worker;\n \n google::protobuf::ShutdownProtobufLibrary();\n \n \/\/ ------------------------------------------------------------------------\n \/\/ Close everything\n \/\/ ------------------------------------------------------------------------\n \n samson::ModulesManager::destroy();\n \n engine::ProcessManager::destroy();\n engine::DiskManager::destroy();\n engine::MemoryManager::destroy();\n engine::Engine::destroy();\n \n samson::SamsonSetup::destroy();\n \n \n \/\/ Check background threads\n au::StringVector background_threads = au::ThreadManager::shared()->getThreadNames();\n if( background_threads.size() > 0 )\n {\n LM_W((\"Still %lu background threads running (%s)\" , background_threads.size() , background_threads.str().c_str() ));\n std::cerr << au::ThreadManager::shared()->str();\n }\n else\n LM_M((\"Finished correctly with 0 background processes\"));\n\n return 0;\n}\nSAMSON-988 NETDATANA-92 Changing samsond.pid from paLogFilePath to paLogDir (this last one is controlled by SS_WORKER_LOG_DIR\/* ****************************************************************************\n*\n* FILE main_samsonWorker.cpp\n*\n* AUTHOR Ken Zangelin\n*\n* CREATION DATE Dec 14 2010\n*\n*\/\n#include \"parseArgs\/parseArgs.h\"\n#include \"parseArgs\/paIsSet.h\"\n#include \"logMsg\/logMsg.h\"\n#include \"parseArgs\/paConfig.h\"\n#include \"logMsg\/traceLevels.h\"\n\n#include \n\n\n#include \"au\/LockDebugger.h\" \/\/ au::LockDebugger\n#include \"au\/ThreadManager.h\"\n\n#include \"engine\/MemoryManager.h\"\n#include \"engine\/Engine.h\"\n#include \"engine\/DiskManager.h\"\n#include \"engine\/ProcessManager.h\"\n\n#include \"samson\/common\/samsonVersion.h\"\n#include \"samson\/common\/samsonVars.h\"\n#include \"samson\/common\/SamsonSetup.h\"\n#include \"samson\/common\/daemonize.h\"\n#include \"samson\/common\/MemoryCheck.h\"\n#include \"samson\/network\/WorkerNetwork.h\"\n#include \"samson\/worker\/SamsonWorker.h\"\n#include \"samson\/isolated\/SharedMemoryManager.h\"\n#include \"samson\/stream\/BlockManager.h\"\n#include \"samson\/module\/ModulesManager.h\"\n\n\n\n\/* ****************************************************************************\n*\n* Option variables\n*\/\nSAMSON_ARG_VARS;\n\nbool fg;\nbool noLog;\nint valgrind;\nint port;\nint web_port;\n\n\n\n\/* ****************************************************************************\n*\n* parse arguments\n*\/\nPaArgument paArgs[] =\n{\n SAMSON_ARGS,\n { \"-fg\", &fg, \"SAMSON_WORKER_FOREGROUND\", PaBool, PaOpt, false, false, true, \"don't start as daemon\" },\n { \"-port\", &port, \"\", PaInt, PaOpt, SAMSON_WORKER_PORT, 1, 9999, \"Port to receive new connections\" },\n { \"-web_port\", &web_port, \"\", PaInt, PaOpt, SAMSON_WORKER_WEB_PORT, 1, 9999, \"Port to receive new connections\" },\n { \"-nolog\", &noLog, \"SAMSON_WORKER_NO_LOG\", PaBool, PaOpt, false, false, true, \"no logging\" },\n { \"-valgrind\", &valgrind, \"SAMSON_WORKER_VALGRIND\", PaInt, PaOpt, 0, 0, 20, \"help valgrind debug process\" },\n\n PA_END_OF_ARGS\n};\n\n\n\n\/* ****************************************************************************\n*\n* global variables\n*\/\nint logFd = -1;\nsamson::SamsonWorker* worker = NULL;\nau::LockDebugger* lockDebugger = NULL;\nengine::SharedMemoryManager* smManager = NULL;\n\n\n\n\/* ****************************************************************************\n*\n* man texts -\n*\/\nstatic const char* manSynopsis = \" [OPTION]\";\nstatic const char* manShortDescription = \"samsond is the main process in a SAMSON system.\\n\\n\";\nstatic const char* manDescription =\n \"\\n\"\n \"samsond is the main process in a SAMSON system. All the nodes in the cluster has its own samsonWorker process\\n\"\n \"All samsond processes are responsible for processing a segment of available data\"\n \"All clients of the platform ( delila's ) are connected to all samsonWorkers in the system\"\n \"See samson documentation to get more information about how to get a SAMSON system up and running\"\n \"\\n\";\n\nstatic const char* manExitStatus = \"0 if OK\\n 1-255 error\\n\";\nstatic const char* manAuthor = \"Written by Andreu Urruela, Ken Zangelin and J.Gregorio Escalada.\";\nstatic const char* manReportingBugs = \"bugs to samson-dev@tid.es\\n\";\nstatic const char* manCopyright = \"Copyright (C) 2011 Telefonica Investigacion y Desarrollo\";\nstatic const char* manVersion = SAMSON_VERSION;\n\n\nvoid captureSIGINT( int s )\n{\n s = 3;\n LM_X(1, (\"Signal SIGINT\"));\n}\n\nvoid captureSIGPIPE( int s )\n{\n s = 3;\n LM_M((\"Captured SIGPIPE\"));\n}\n\nvoid captureSIGTERM( int s )\n{\n s = 3;\n LM_M((\"Captured SIGTERM\"));\n\n LM_M((\"Cleaning up\"));\n std::string pid_file_name = au::str(\"%s\/samsond.pid\" , paLogDir );\n if ( remove (pid_file_name.c_str()) != 0)\n {\n LM_W((\"Error deleting the pid file %s\", pid_file_name.c_str() ));\n }\n exit(1);\n}\n\n\n\nvoid cleanup(void)\n{\n google::protobuf::ShutdownProtobufLibrary();\n\n printf(\"Shutting down worker components (worker at %p)\\n\", worker);\n if (worker)\n {\n printf(\"deleting worker\\n\");\n delete worker;\n }\n\n printf(\"Shutting down LockDebugger\\n\");\n au::LockDebugger::destroy();\n\n if (smManager != NULL)\n {\n printf(\"Shutting down Shared Memory Manager\\n\");\n delete smManager;\n smManager = NULL;\n }\n\n printf(\"Shutting down SamsonSetup\\n\");\n samson::SamsonSetup::destroy();\n\n printf(\"destroying ProcessManager\\n\");\n engine::ProcessManager::destroy();\n\n printf(\"destroying DiskManager\\n\");\n engine::DiskManager::destroy();\n\n printf(\"destroying MemoryManager\\n\");\n engine::MemoryManager::destroy();\n\n printf(\"destroying Engine\\n\");\n engine::Engine::destroy();\n\n printf(\"destroying ModulesManager\\n\");\n samson::ModulesManager::destroy();\n\n paConfigCleanup();\n lmCleanProgName();\n}\n\n\nstatic void valgrindExit(int v)\n{\n if (v == valgrind)\n {\n LM_M((\"Valgrind option is %d - I exit\", v));\n exit(0);\n }\n}\n\n\n\n\/* ****************************************************************************\n*\n* main - \n*\/\nint main(int argC, const char *argV[])\n{\n atexit(cleanup);\n\n paConfig(\"builtin prefix\", (void*) \"SS_WORKER_\");\n paConfig(\"usage and exit on any warning\", (void*) true);\n\n \/\/ Andreu: samsonWorker is not a console in foreground (debug) mode ( to ask to status with commands )\n paConfig(\"log to screen\", (void*) \"only errors\");\n \/\/paConfig(\"log to screen\", (void*) (void*) false);\n \n paConfig(\"log file line format\", (void*) \"TYPE:DATE:EXEC-AUX\/FILE[LINE](p.PID)(t.TID) FUNC: TEXT\");\n paConfig(\"screen line format\", (void*) \"TYPE@TIME EXEC: TEXT\");\n paConfig(\"log to file\", (void*) true);\n\n paConfig(\"man synopsis\", (void*) manSynopsis);\n paConfig(\"man shortdescription\", (void*) manShortDescription);\n paConfig(\"man description\", (void*) manDescription);\n paConfig(\"man exitstatus\", (void*) manExitStatus);\n paConfig(\"man author\", (void*) manAuthor);\n paConfig(\"man reportingbugs\", (void*) manReportingBugs);\n paConfig(\"man copyright\", (void*) manCopyright);\n paConfig(\"man version\", (void*) manVersion);\n\n const char* extra = paIsSetSoGet(argC, (char**) argV, \"-port\");\n paParse(paArgs, argC, (char**) argV, 1, false, extra);\n\n valgrindExit(1);\n\n lmAux((char*) \"father\");\n\n LM_V((\"Started with arguments:\"));\n for (int ix = 0; ix < argC; ix++)\n LM_V((\" %02d: '%s'\", ix, argV[ix]));\n\n logFd = lmFirstDiskFileDescriptor();\n \n \/\/ Capturing SIGPIPE\n if (signal(SIGPIPE, captureSIGPIPE) == SIG_ERR)\n LM_W((\"SIGPIPE cannot be handled\"));\n\n if (signal(SIGINT, captureSIGINT) == SIG_ERR)\n LM_W((\"SIGINT cannot be handled\"));\n\n if (signal(SIGTERM, captureSIGTERM) == SIG_ERR)\n LM_W((\"SIGTERM cannot be handled\"));\n\n \/\/ Init basic setup stuff (necessary for memory check)\n lockDebugger = au::LockDebugger::shared(); \/\/ VALGRIND complains ...\n samson::SamsonSetup::init(samsonHome, samsonWorking); \/\/ Load setup and create default directories\n \n valgrindExit(2);\n\n \/\/ Check to see if the current memory configuration is ok or not\n if (samson::MemoryCheck() == false)\n LM_X(1,(\"Insufficient memory configured. Check %ssamsonWorkerLog for more information.\", paLogDir));\n \n if (fg == false)\n {\n std::cout << \"OK. samsonWorker is now working in background.\\n\";\n daemonize();\n }\n\n valgrindExit(3);\n \/\/ ------------------------------------------------------ \n \/\/ Write pid in \/var\/log\/samson\/samsond.pid\n \/\/ ------------------------------------------------------\n\n char pid_file_name[256];\n snprintf(pid_file_name, sizeof(pid_file_name), \"%s\/samsond.pid\", paLogDir);\n FILE *file = fopen(pid_file_name, \"w\");\n if (!file)\n LM_X(1, (\"Error opening file '%s' to store pid\", pid_file_name));\n int pid = (int) getpid();\n if (fprintf(file, \"%d\" , pid) == 0)\n LM_X(1,(\"Error writing pid %d to file %s\", pid, pid_file_name));\n fclose(file);\n \/\/ ------------------------------------------------------ \n \n \/\/ Make sure this singleton is created just once\n LM_D((\"createWorkingDirectories\"));\n samson::SamsonSetup::shared()->createWorkingDirectories(); \/\/ Create working directories\n \n valgrindExit(4);\n LM_D((\"engine::Engine::init\"));\n engine::Engine::init();\n\n valgrindExit(5);\n LM_D((\"engine::SharedMemoryManager::init\"));\n engine::SharedMemoryManager::init(samson::SamsonSetup::shared()->getInt(\"general.num_processess\") , samson::SamsonSetup::shared()->getUInt64(\"general.shared_memory_size_per_buffer\")); \/\/ VALGRIND complains ...\n smManager = engine::SharedMemoryManager::shared();\n\n valgrindExit(6);\n LM_D((\"engine::DiskManager::init\"));\n engine::DiskManager::init(1);\n\n valgrindExit(7);\n LM_D((\"engine::ProcessManager::init\"));\n engine::ProcessManager::init(samson::SamsonSetup::shared()->getInt(\"general.num_processess\"));\n\n valgrindExit(8);\n LM_D((\"engine::MemoryManager::init\"));\n engine::MemoryManager::init(samson::SamsonSetup::shared()->getUInt64(\"general.memory\"));\n\n valgrindExit(9);\n LM_D((\"samson::ModulesManager::init\"));\n samson::ModulesManager::init();\n\n valgrindExit(10);\n LM_D((\"samson::stream::BlockManager::init\"));\n samson::stream::BlockManager::init();\n\n valgrindExit(11);\n\n \/\/ Instance of network object and initialization\n \/\/ --------------------------------------------------------------------\n samson::WorkerNetwork* networkP = new samson::WorkerNetwork(port, web_port);\n \n valgrindExit(12);\n\n \/\/ Instance of SamsonWorker object (network contains at least the number of workers)\n \/\/ -----------------------------------------------------------------------------------\n worker = new samson::SamsonWorker(networkP);\n\n LM_M((\"Worker Running\"));\n LM_D((\"worker at %p\", worker));\n valgrindExit(13);\n\n if (fg == false)\n {\n while (true)\n sleep(10);\n }\n\n worker->runConsole();\n \n LM_D((\"Worker Cleanup\"));\n \n if (worker)\n delete worker;\n \n google::protobuf::ShutdownProtobufLibrary();\n \n \/\/ ------------------------------------------------------------------------\n \/\/ Close everything\n \/\/ ------------------------------------------------------------------------\n \n samson::ModulesManager::destroy();\n \n engine::ProcessManager::destroy();\n engine::DiskManager::destroy();\n engine::MemoryManager::destroy();\n engine::Engine::destroy();\n \n samson::SamsonSetup::destroy();\n \n \n \/\/ Check background threads\n au::StringVector background_threads = au::ThreadManager::shared()->getThreadNames();\n if( background_threads.size() > 0 )\n {\n LM_W((\"Still %lu background threads running (%s)\" , background_threads.size() , background_threads.str().c_str() ));\n std::cerr << au::ThreadManager::shared()->str();\n }\n else\n LM_M((\"Finished correctly with 0 background processes\"));\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file PrimeSieve-lock.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2013 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef PRIMESIEVE_LOCK_HPP\n#define PRIMESIEVE_LOCK_HPP\n\n#include \"config.hpp\"\n#include \"PrimeSieve.hpp\"\n\nnamespace primesieve {\n\n\/\/\/ Block the current PrimeSieve (or ParallelPrimeSieve) thread\n\/\/\/ until it can set a lock, then continue execution.\n\/\/\/\nclass LockGuard {\npublic:\n LockGuard(PrimeSieve& ps) : ps_(ps) { ps_.setLock(); }\n ~LockGuard() { ps_.unsetLock(); }\nprivate:\n PrimeSieve& ps_;\n DISALLOW_COPY_AND_ASSIGN(LockGuard);\n};\n\n} \/\/ namespace primesieve\n\n#endif\nUpdate comment\/\/\/\n\/\/\/ @file PrimeSieve-lock.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2017 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef PRIMESIEVE_LOCK_HPP\n#define PRIMESIEVE_LOCK_HPP\n\n#include \"config.hpp\"\n#include \"PrimeSieve.hpp\"\n\nnamespace primesieve {\n\n\/\/\/ Block the current PrimeSieve (or ParallelPrimeSieve) thread\n\/\/\/ until it can set a lock, then continue execution.\n\/\/\/\nclass LockGuard {\npublic:\n LockGuard(PrimeSieve& ps) : ps_(ps) { ps_.setLock(); }\n ~LockGuard() { ps_.unsetLock(); }\nprivate:\n PrimeSieve& ps_;\n DISALLOW_COPY_AND_ASSIGN(LockGuard);\n};\n\n} \/\/ namespace\n\n#endif\n<|endoftext|>"} {"text":"#ifndef __PLUGINSETTINGS_HPP__\n#define __PLUGINSETTINGS_HPP__\n\n#include \"plugin.hpp\"\n\nclass PluginSettings\n{\n\tHANDLE handle;\n\tFARAPISETTINGSCONTROL SettingsControl;\n\npublic:\n\n\tPluginSettings(const GUID &guid, FARAPISETTINGSCONTROL SettingsControl)\n\t{\n\t\tthis->SettingsControl = SettingsControl;\n\t\thandle = INVALID_HANDLE_VALUE;\n\n\t\tFarSettingsCreate settings={sizeof(FarSettingsCreate),guid,handle};\n\t\tif (SettingsControl(INVALID_HANDLE_VALUE,SCTL_CREATE,0,&settings))\n\t\t\thandle = settings.Handle;\n\t}\n\n\t~PluginSettings()\n\t{\n\t\tSettingsControl(handle,SCTL_FREE,0,{});\n\t}\n\n\tint CreateSubKey(size_t Root, const wchar_t *Name)\n\t{\n\t\tFarSettingsValue value={sizeof(FarSettingsValue),Root,Name};\n\t\treturn (int)SettingsControl(handle,SCTL_CREATESUBKEY,0,&value);\n\t}\n\n\tint OpenSubKey(size_t Root, const wchar_t *Name)\n\t{\n\t\tFarSettingsValue value={sizeof(FarSettingsValue),Root,Name};\n\t\treturn (int)SettingsControl(handle,SCTL_OPENSUBKEY,0,&value);\n\t}\n\n\tbool DeleteSubKey(size_t Root)\n\t{\n\t\tFarSettingsValue value={sizeof(FarSettingsValue),Root,nullptr};\n\t\treturn (int)SettingsControl(handle,SCTL_DELETE,0,&value) ? true : false;\n\t}\n\n\tbool DeleteValue(size_t Root, const wchar_t *Name)\n\t{\n\t\tFarSettingsValue value={sizeof(FarSettingsValue),Root,Name};\n\t\treturn (int)SettingsControl(handle,SCTL_DELETE,0,&value) ? true : false;\n\t}\n\n\tconst wchar_t *Get(size_t Root, const wchar_t *Name, const wchar_t *Default)\n\t{\n\t\tFarSettingsItem item={sizeof(FarSettingsItem),Root,Name,FST_STRING};\n\t\tif (SettingsControl(handle,SCTL_GET,0,&item))\n\t\t{\n\t\t\treturn item.String;\n\t\t}\n\t\treturn Default;\n\t}\n\n\tvoid Get(size_t Root, const wchar_t *Name, wchar_t *Value, size_t Size, const wchar_t *Default)\n\t{\n\t\tlstrcpyn(Value, Get(Root,Name,Default), (int)Size);\n\t}\n\n\tunsigned __int64 Get(size_t Root, const wchar_t *Name, unsigned __int64 Default)\n\t{\n\t\tFarSettingsItem item={sizeof(FarSettingsItem),Root,Name,FST_QWORD};\n\t\tif (SettingsControl(handle,SCTL_GET,0,&item))\n\t\t{\n\t\t\treturn item.Number;\n\t\t}\n\t\treturn Default;\n\t}\n\n\t__int64 Get(size_t Root, const wchar_t *Name, __int64 Default) { return (__int64)Get(Root,Name,(unsigned __int64)Default); }\n\tint Get(size_t Root, const wchar_t *Name, int Default) { return (int)Get(Root,Name,(unsigned __int64)Default); }\n\tunsigned int Get(size_t Root, const wchar_t *Name, unsigned int Default) { return (unsigned int)Get(Root,Name,(unsigned __int64)Default); }\n\tDWORD Get(size_t Root, const wchar_t *Name, DWORD Default) { return (DWORD)Get(Root,Name,(unsigned __int64)Default); }\n\tbool Get(size_t Root, const wchar_t *Name, bool Default) { return Get(Root,Name,Default?1ull:0ull)?true:false; }\n\n\tsize_t Get(size_t Root, const wchar_t *Name, void *Value, size_t Size)\n\t{\n\t\tFarSettingsItem item={sizeof(FarSettingsItem),Root,Name,FST_DATA};\n\t\tif (SettingsControl(handle,SCTL_GET,0,&item))\n\t\t{\n\t\t\tSize = (item.Data.Size>Size)?Size:item.Data.Size;\n\t\t\tmemcpy(Value,item.Data.Data,Size);\n\t\t\treturn Size;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool Set(size_t Root, const wchar_t *Name, const wchar_t *Value)\n\t{\n\t\tFarSettingsItem item={sizeof(FarSettingsItem),Root,Name,FST_STRING};\n\t\titem.String=Value;\n\t\treturn SettingsControl(handle,SCTL_SET,0,&item)!=FALSE;\n\t}\n\n\tbool Set(size_t Root, const wchar_t *Name, unsigned __int64 Value)\n\t{\n\t\tFarSettingsItem item={sizeof(FarSettingsItem),Root,Name,FST_QWORD};\n\t\titem.Number=Value;\n\t\treturn SettingsControl(handle,SCTL_SET,0,&item)!=FALSE;\n\t}\n\n\tbool Set(size_t Root, const wchar_t *Name, __int64 Value) { return Set(Root,Name,(unsigned __int64)Value); }\n\tbool Set(size_t Root, const wchar_t *Name, int Value) { return Set(Root,Name,(unsigned __int64)Value); }\n\tbool Set(size_t Root, const wchar_t *Name, unsigned int Value) { return Set(Root,Name,(unsigned __int64)Value); }\n\tbool Set(size_t Root, const wchar_t *Name, DWORD Value) { return Set(Root,Name,(unsigned __int64)Value); }\n\tbool Set(size_t Root, const wchar_t *Name, bool Value) { return Set(Root,Name,Value?1ull:0ull); }\n\n\tbool Set(size_t Root, const wchar_t *Name, const void *Value, size_t Size)\n\t{\n\t\tFarSettingsItem item={sizeof(FarSettingsItem),Root,Name,FST_DATA};\n\t\titem.Data.Size=Size;\n\t\titem.Data.Data=Value;\n\t\treturn SettingsControl(handle,SCTL_SET,0,&item)!=FALSE;\n\t}\n};\n\n#endif\nplugins: can build some plugins with 'old' compilers (supported c++11, but not supported c++17)#ifndef __PLUGINSETTINGS_HPP__\n#define __PLUGINSETTINGS_HPP__\n\n#include \"plugin.hpp\"\n\nclass PluginSettings\n{\n\tHANDLE handle;\n\tFARAPISETTINGSCONTROL SettingsControl;\n\npublic:\n\n\tPluginSettings(const GUID &guid, FARAPISETTINGSCONTROL SettingsControl)\n\t{\n\t\tthis->SettingsControl = SettingsControl;\n\t\thandle = INVALID_HANDLE_VALUE;\n\n\t\tFarSettingsCreate settings={sizeof(FarSettingsCreate),guid,handle};\n\t\tif (SettingsControl(INVALID_HANDLE_VALUE,SCTL_CREATE,0,&settings))\n\t\t\thandle = settings.Handle;\n\t}\n\n\t~PluginSettings()\n\t{\n\t\tSettingsControl(handle,SCTL_FREE,0,nullptr);\n\t}\n\n\tint CreateSubKey(size_t Root, const wchar_t *Name)\n\t{\n\t\tFarSettingsValue value={sizeof(FarSettingsValue),Root,Name};\n\t\treturn (int)SettingsControl(handle,SCTL_CREATESUBKEY,0,&value);\n\t}\n\n\tint OpenSubKey(size_t Root, const wchar_t *Name)\n\t{\n\t\tFarSettingsValue value={sizeof(FarSettingsValue),Root,Name};\n\t\treturn (int)SettingsControl(handle,SCTL_OPENSUBKEY,0,&value);\n\t}\n\n\tbool DeleteSubKey(size_t Root)\n\t{\n\t\tFarSettingsValue value={sizeof(FarSettingsValue),Root,nullptr};\n\t\treturn (int)SettingsControl(handle,SCTL_DELETE,0,&value) ? true : false;\n\t}\n\n\tbool DeleteValue(size_t Root, const wchar_t *Name)\n\t{\n\t\tFarSettingsValue value={sizeof(FarSettingsValue),Root,Name};\n\t\treturn (int)SettingsControl(handle,SCTL_DELETE,0,&value) ? true : false;\n\t}\n\n\tconst wchar_t *Get(size_t Root, const wchar_t *Name, const wchar_t *Default)\n\t{\n\t\tFarSettingsItem item={sizeof(FarSettingsItem),Root,Name,FST_STRING};\n\t\tif (SettingsControl(handle,SCTL_GET,0,&item))\n\t\t{\n\t\t\treturn item.String;\n\t\t}\n\t\treturn Default;\n\t}\n\n\tvoid Get(size_t Root, const wchar_t *Name, wchar_t *Value, size_t Size, const wchar_t *Default)\n\t{\n\t\tlstrcpyn(Value, Get(Root,Name,Default), (int)Size);\n\t}\n\n\tunsigned __int64 Get(size_t Root, const wchar_t *Name, unsigned __int64 Default)\n\t{\n\t\tFarSettingsItem item={sizeof(FarSettingsItem),Root,Name,FST_QWORD};\n\t\tif (SettingsControl(handle,SCTL_GET,0,&item))\n\t\t{\n\t\t\treturn item.Number;\n\t\t}\n\t\treturn Default;\n\t}\n\n\t__int64 Get(size_t Root, const wchar_t *Name, __int64 Default) { return (__int64)Get(Root,Name,(unsigned __int64)Default); }\n\tint Get(size_t Root, const wchar_t *Name, int Default) { return (int)Get(Root,Name,(unsigned __int64)Default); }\n\tunsigned int Get(size_t Root, const wchar_t *Name, unsigned int Default) { return (unsigned int)Get(Root,Name,(unsigned __int64)Default); }\n\tDWORD Get(size_t Root, const wchar_t *Name, DWORD Default) { return (DWORD)Get(Root,Name,(unsigned __int64)Default); }\n\tbool Get(size_t Root, const wchar_t *Name, bool Default) { return Get(Root,Name,Default?1ull:0ull)?true:false; }\n\n\tsize_t Get(size_t Root, const wchar_t *Name, void *Value, size_t Size)\n\t{\n\t\tFarSettingsItem item={sizeof(FarSettingsItem),Root,Name,FST_DATA};\n\t\tif (SettingsControl(handle,SCTL_GET,0,&item))\n\t\t{\n\t\t\tSize = (item.Data.Size>Size)?Size:item.Data.Size;\n\t\t\tmemcpy(Value,item.Data.Data,Size);\n\t\t\treturn Size;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool Set(size_t Root, const wchar_t *Name, const wchar_t *Value)\n\t{\n\t\tFarSettingsItem item={sizeof(FarSettingsItem),Root,Name,FST_STRING};\n\t\titem.String=Value;\n\t\treturn SettingsControl(handle,SCTL_SET,0,&item)!=FALSE;\n\t}\n\n\tbool Set(size_t Root, const wchar_t *Name, unsigned __int64 Value)\n\t{\n\t\tFarSettingsItem item={sizeof(FarSettingsItem),Root,Name,FST_QWORD};\n\t\titem.Number=Value;\n\t\treturn SettingsControl(handle,SCTL_SET,0,&item)!=FALSE;\n\t}\n\n\tbool Set(size_t Root, const wchar_t *Name, __int64 Value) { return Set(Root,Name,(unsigned __int64)Value); }\n\tbool Set(size_t Root, const wchar_t *Name, int Value) { return Set(Root,Name,(unsigned __int64)Value); }\n\tbool Set(size_t Root, const wchar_t *Name, unsigned int Value) { return Set(Root,Name,(unsigned __int64)Value); }\n\tbool Set(size_t Root, const wchar_t *Name, DWORD Value) { return Set(Root,Name,(unsigned __int64)Value); }\n\tbool Set(size_t Root, const wchar_t *Name, bool Value) { return Set(Root,Name,Value?1ull:0ull); }\n\n\tbool Set(size_t Root, const wchar_t *Name, const void *Value, size_t Size)\n\t{\n\t\tFarSettingsItem item={sizeof(FarSettingsItem),Root,Name,FST_DATA};\n\t\titem.Data.Size=Size;\n\t\titem.Data.Data=Value;\n\t\treturn SettingsControl(handle,SCTL_SET,0,&item)!=FALSE;\n\t}\n};\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"client.h\"\n#include \"duckchat.h\"\n#include \"raw.h\"\n\n\/\/ Variables\nstruct sockaddr_in client_addr;\nstruct sockaddr_in server_addr;\nint client_socket;\nstruct addrinfo *server_info;\nchar *channel;\n\n\n\/\/ Prints an error message and exits the program.\nvoid Error(const char *msg) {\n std::cerr << msg << std::endl;\n exit(1);\n}\n\n\n\/\/ Connects to the server at a the given port.\nvoid Connect(char *domain, const char *port) {\n std::cout << \"Connecting to \" << domain << std::endl;\n\n struct addrinfo hints;\n struct addrinfo *server_info_tmp;\n int status;\n\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_DGRAM;\n hints.ai_protocol = 0;\n\n if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) {\n std::cerr << \"client: unable to resolve address: \" << gai_strerror(status) << std::endl;\n exit(1);\n }\n\n \/\/ getaddrinfo() returns a list of address structures into server_info_tmp.\n \/\/ Try each address until we successfully connect().\n \/\/ If socket() (or connect()) fails, close the socket and try the next address.\n\n for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) {\n if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) {\n continue;\n }\n if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) {\n fcntl(client_socket, F_SETFL, O_NONBLOCK);\n break; \/\/ Success\n }\n close(client_socket);\n }\n\n\n\n if (server_info == NULL) {\n Error(\"client: all sockets failed to connect\");\n }\n}\n\n\n\/\/ Sends a message to all users in on the active channel.\nint RequestSay(const char *message) {\n struct request_say say;\n memset(&say, 0, sizeof(say));\n say.req_type = REQ_SAY;\n strncpy(say.req_text, message, SAY_MAX);\n strncpy(say.req_channel, channel, CHANNEL_MAX);\n\n if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to send message\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends login requests to the server.\nint RequestLogin(char *username) {\n struct request_login login;\n memset(&login, 0, sizeof(login));\n login.req_type = REQ_LOGIN;\n strncpy(login.req_username, username, USERNAME_MAX);\n\n size_t message_size = sizeof(struct request_login);\n\n if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request login\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends logout requests to the server.\nint RequestLogout() {\n struct request_logout logout;\n memset((char *) &logout, 0, sizeof(logout));\n logout.req_type = REQ_LOGOUT;\n\n size_t message_size = sizeof(struct request_logout);\n\n if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request logout\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends join requests to the server.\nint RequestJoin(char *channel) {\n struct request_join join;\n memset((char *) &join, 0, sizeof(join));\n join.req_type = REQ_JOIN;\n strncpy(join.req_channel, channel, CHANNEL_MAX);\n\n size_t message_size = sizeof(struct request_join);\n\n if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request join\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector StringSplit(std::string input) {\n std::istringstream iss(input);\n std::vector result{std::istream_iterator{iss}, std::istream_iterator{}};\n\n return result;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector SplitString(char *input, char delimiter) {\n std::vector result;\n std::string word = \"\";\n\n size_t input_size = strlen(input);\n for (size_t i = 0; i < input_size; i++) {\n if (input[i] != delimiter) {\n word += input[i];\n } else {\n result.push_back(word);\n word = \"\";\n }\n }\n result.push_back(word);\n\n return result;\n}\n\n\nvoid StripChar(char *input, char c) {\n size_t size = strlen(input);\n for (size_t i = 0; i < size; i++) {\n if (input[i] == c) {\n input[i] = '\\0';\n }\n }\n}\n\n\n\/\/ Processes the input string to decide what type of command it is.\nbool ProcessInput(std::string input) {\n std::vector inputs = StringSplit(input);\n bool result = true;\n\n if (inputs[0] == \"\/exit\") {\n RequestLogout();\n\/\/ cooked_mode();\n result = false;\n } else if (inputs[0] == \"\/list\") {\n\n } else if (inputs[0] == \"\/join\") {\n\n } else if (inputs[0] == \"\/leave\") {\n\n } else if (inputs[0] == \"\/who\") {\n\n } else if (inputs[0] == \"\/switch\") {\n\n } else {\n std::cout << \"\\n*Unknown command\" << std::endl;\n }\n\n return result;\n}\n\n\nint main(int argc, char *argv[]) {\n char *domain;\n char *port_str;\n int port_num;\n char *username;\n char *input;\n char tmp_buffer[SAY_MAX];\n memset(&tmp_buffer, 0, SAY_MAX);\n\n char stdin_buffer[SAY_MAX + 1];\n char *stdin_buffer_position = stdin_buffer;\n\n\/\/ struct timeval timeout;\n fd_set read_set;\n\/\/ int file_desc = 0;\n int result;\n char receive_buffer[kBufferSize];\n memset(&receive_buffer, 0, kBufferSize);\n\n\/\/ char stdin_buffer[kBufferSize];\n\/\/ memset(&stdin_buffer, 0, kBufferSize);\n\n if (argc < 4) {\n Error(\"usage: client [server name] [port] [username]\");\n }\n\n domain = argv[1];\n port_str = argv[2];\n port_num = atoi(argv[2]);\n username = argv[3];\n\n if (strlen(domain) > UNIX_PATH_MAX) {\n Error(\"client: server name must be less than 108 characters\");\n }\n\n if (port_num < 0 || port_num > 65535) {\n Error(\"client: port number must be between 0 and 65535\");\n }\n\n if (strlen(username) > USERNAME_MAX) {\n Error(\"client: username must be less than 32 characters\");\n }\n\n Connect(domain, port_str);\n\n RequestLogin(username);\n\n channel = (char *) \"Common\";\n RequestJoin(channel);\n\n \/\/ TODO handle response from send\n\n if (raw_mode() != 0){\n Error(\"client: error using raw mode\");\n }\n\n std::cout << \">\" << std::flush;\n\n while (1) {\n FD_ZERO(&read_set);\n FD_SET(client_socket, &read_set);\n FD_SET(STDIN_FILENO, &read_set);\n\n if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) {\n Error(\"client: problem using select\");\n }\n\n if (result > 0) {\n if (FD_ISSET(STDIN_FILENO, &read_set)) {\n\/\/ char c = (char) getchar();\n\/\/ *bufPosition++ = c;\n\/\/ std::cout << c << std::endl;\n\/\/ fflush(stdout);\n\n\/\/ int read_stdin_size = read(STDIN_FILENO, stdin_buffer, kBufferSize);\n\n\/\/ input = NewInputString();\n\n char c = (char) getchar();\n if (c == '\\n') {\n *stdin_buffer_position++ = '\\0';\n stdin_buffer_position = stdin_buffer;\n printf(\"\\n\");\n fflush(stdout);\n input = stdin_buffer;\n if (input[0] == '\/') {\n std::cout << \"input[0] == '\/'\" << std::endl;\n ProcessInput(input);\n } else {\n \/\/ Send chat messages\n\/\/ StripChar(stdin_buffer, '\\n');\n RequestSay(input);\n }\n\n } else if (stdin_buffer_position != stdin_buffer + SAY_MAX) {\n *stdin_buffer_position++ = c;\n printf(\"%c\", c);\n fflush(stdout);\n }\n\/\/\n\/\/ const char *DELIM = \" \\n\";\n\/\/ char *tok = (char*) malloc(sizeof(char) * (strlen(input) + 1));\n\/\/ strcpy(tok, input);\n\/\/ char *command = strtok(tok, DELIM);\n\/\/ free(tok);\n\/\/\n\/\/ if (command != NULL) {\n\/\/ if (input[0] == '\/') {\n\/\/ ProcessInput(input);\n\/\/ } else {\n\/\/ \/\/ Send chat messages\n\/\/\/\/ StripChar(stdin_buffer, '\\n');\n\/\/ RequestSay(input);\n\/\/ }\n\/\/ }\n\/\/\n\/\/ memset(&stdin_buffer, 0, kBufferSize);\n } \/\/ end of if STDIN_FILENO\n\n if (FD_ISSET(client_socket, &read_set)) {\n \/\/ Socket has data\n int read_size = read(client_socket, receive_buffer, kBufferSize);\n\n if (read_size != 0) {\n \/\/ TODO capture user input, store, clean input, then print buffer, afterward replace input\n struct text message;\n memcpy(&message, receive_buffer, sizeof(struct text));\n text_t text_type = message.txt_type;\n\n switch (text_type) {\n case TXT_SAY:\n struct text_say say;\n memcpy(&say, receive_buffer, sizeof(struct text_say));\n\/\/ std::cin.readsome(tmp_buffer, sizeof(tmp_buffer));\n std::cout << \"\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\";\n std::cout << \"[\" << say.txt_channel << \"]\" << \"[\" << say.txt_username << \"]: \" << say.txt_text << std::endl;\n std::cout << \">\" << tmp_buffer << std::flush;\n memset(&tmp_buffer, 0, SAY_MAX);\n break;\n default:\n break;\n }\n }\n\n memset(&receive_buffer, 0, SAY_MAX);\n } \/\/ end of if client_socket\n\n } \/\/ end of if result\n\n } \/\/ end of while\n\n return 0;\n}fix \/exit#include \n#include \n#include \n\n#include \"client.h\"\n#include \"duckchat.h\"\n#include \"raw.h\"\n\n\/\/ Variables\nstruct sockaddr_in client_addr;\nstruct sockaddr_in server_addr;\nint client_socket;\nstruct addrinfo *server_info;\nchar *channel;\n\n\n\/\/ Prints an error message and exits the program.\nvoid Error(const char *msg) {\n std::cerr << msg << std::endl;\n exit(1);\n}\n\n\n\/\/ Connects to the server at a the given port.\nvoid Connect(char *domain, const char *port) {\n std::cout << \"Connecting to \" << domain << std::endl;\n\n struct addrinfo hints;\n struct addrinfo *server_info_tmp;\n int status;\n\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_DGRAM;\n hints.ai_protocol = 0;\n\n if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) {\n std::cerr << \"client: unable to resolve address: \" << gai_strerror(status) << std::endl;\n exit(1);\n }\n\n \/\/ getaddrinfo() returns a list of address structures into server_info_tmp.\n \/\/ Try each address until we successfully connect().\n \/\/ If socket() (or connect()) fails, close the socket and try the next address.\n\n for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) {\n if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) {\n continue;\n }\n if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) {\n fcntl(client_socket, F_SETFL, O_NONBLOCK);\n break; \/\/ Success\n }\n close(client_socket);\n }\n\n\n\n if (server_info == NULL) {\n Error(\"client: all sockets failed to connect\");\n }\n}\n\n\n\/\/ Sends a message to all users in on the active channel.\nint RequestSay(const char *message) {\n struct request_say say;\n memset(&say, 0, sizeof(say));\n say.req_type = REQ_SAY;\n strncpy(say.req_text, message, SAY_MAX);\n strncpy(say.req_channel, channel, CHANNEL_MAX);\n\n if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to send message\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends login requests to the server.\nint RequestLogin(char *username) {\n struct request_login login;\n memset(&login, 0, sizeof(login));\n login.req_type = REQ_LOGIN;\n strncpy(login.req_username, username, USERNAME_MAX);\n\n size_t message_size = sizeof(struct request_login);\n\n if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request login\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends logout requests to the server.\nint RequestLogout() {\n struct request_logout logout;\n memset((char *) &logout, 0, sizeof(logout));\n logout.req_type = REQ_LOGOUT;\n\n size_t message_size = sizeof(struct request_logout);\n\n if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request logout\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends join requests to the server.\nint RequestJoin(char *channel) {\n struct request_join join;\n memset((char *) &join, 0, sizeof(join));\n join.req_type = REQ_JOIN;\n strncpy(join.req_channel, channel, CHANNEL_MAX);\n\n size_t message_size = sizeof(struct request_join);\n\n if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request join\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector StringSplit(std::string input) {\n std::istringstream iss(input);\n std::vector result{std::istream_iterator{iss}, std::istream_iterator{}};\n\n return result;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector SplitString(char *input, char delimiter) {\n std::vector result;\n std::string word = \"\";\n\n size_t input_size = strlen(input);\n for (size_t i = 0; i < input_size; i++) {\n if (input[i] != delimiter) {\n word += input[i];\n } else {\n result.push_back(word);\n word = \"\";\n }\n }\n result.push_back(word);\n\n return result;\n}\n\n\nvoid StripChar(char *input, char c) {\n size_t size = strlen(input);\n for (size_t i = 0; i < size; i++) {\n if (input[i] == c) {\n input[i] = '\\0';\n }\n }\n}\n\n\n\/\/ Processes the input string to decide what type of command it is.\nbool ProcessInput(std::string input) {\n std::vector inputs = StringSplit(input);\n bool result = true;\n\n if (inputs[0] == \"\/exit\") {\n RequestLogout();\n cooked_mode();\n result = false;\n } else if (inputs[0] == \"\/list\") {\n\n } else if (inputs[0] == \"\/join\") {\n\n } else if (inputs[0] == \"\/leave\") {\n\n } else if (inputs[0] == \"\/who\") {\n\n } else if (inputs[0] == \"\/switch\") {\n\n } else {\n std::cout << \"\\n*Unknown command\" << std::endl;\n }\n\n return result;\n}\n\n\nint main(int argc, char *argv[]) {\n char *domain;\n char *port_str;\n int port_num;\n char *username;\n char *input;\n char tmp_buffer[SAY_MAX];\n memset(&tmp_buffer, 0, SAY_MAX);\n\n char stdin_buffer[SAY_MAX + 1];\n char *stdin_buffer_position = stdin_buffer;\n\n\/\/ struct timeval timeout;\n fd_set read_set;\n\/\/ int file_desc = 0;\n int result;\n char receive_buffer[kBufferSize];\n memset(&receive_buffer, 0, kBufferSize);\n\n\/\/ char stdin_buffer[kBufferSize];\n\/\/ memset(&stdin_buffer, 0, kBufferSize);\n\n if (argc < 4) {\n Error(\"usage: client [server name] [port] [username]\");\n }\n\n domain = argv[1];\n port_str = argv[2];\n port_num = atoi(argv[2]);\n username = argv[3];\n\n if (strlen(domain) > UNIX_PATH_MAX) {\n Error(\"client: server name must be less than 108 characters\");\n }\n\n if (port_num < 0 || port_num > 65535) {\n Error(\"client: port number must be between 0 and 65535\");\n }\n\n if (strlen(username) > USERNAME_MAX) {\n Error(\"client: username must be less than 32 characters\");\n }\n\n Connect(domain, port_str);\n\n RequestLogin(username);\n\n channel = (char *) \"Common\";\n RequestJoin(channel);\n\n \/\/ TODO handle response from send\n\n if (raw_mode() != 0){\n Error(\"client: error using raw mode\");\n }\n\n std::cout << \">\" << std::flush;\n\n while (1) {\n FD_ZERO(&read_set);\n FD_SET(client_socket, &read_set);\n FD_SET(STDIN_FILENO, &read_set);\n\n if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) {\n Error(\"client: problem using select\");\n }\n\n if (result > 0) {\n if (FD_ISSET(STDIN_FILENO, &read_set)) {\n char c = (char) getchar();\n if (c == '\\n') {\n\/\/ *stdin_buffer_position++ = '\\0';\n stdin_buffer_position = stdin_buffer;\n printf(\"\\n\");\n fflush(stdout);\n input = stdin_buffer;\n if (input[0] == '\/') {\n if (!ProcessInput(input)) {\n break;\n }\n } else {\n \/\/ Send chat messages\n\/\/ StripChar(stdin_buffer, '\\n');\n RequestSay(input);\n }\n\n } else if (stdin_buffer_position != stdin_buffer + SAY_MAX) {\n *stdin_buffer_position++ = c;\n std::cout << c << std::endl;\n fflush(stdout);\n }\n\n\/\/ if (input != NULL) {\n\/\/ if (input[0] == '\/') {\n\/\/ ProcessInput(input);\n\/\/ } else {\n\/\/ \/\/ Send chat messages\n\/\/\/\/ StripChar(stdin_buffer, '\\n');\n\/\/ RequestSay(input);\n\/\/ }\n\/\/ }\n\/\/\n\/\/ memset(&stdin_buffer, 0, kBufferSize);\n } \/\/ end of if STDIN_FILENO\n\n if (FD_ISSET(client_socket, &read_set)) {\n \/\/ Socket has data\n int read_size = read(client_socket, receive_buffer, kBufferSize);\n\n if (read_size != 0) {\n \/\/ TODO capture user input, store, clean input, then print buffer, afterward replace input\n struct text message;\n memcpy(&message, receive_buffer, sizeof(struct text));\n text_t text_type = message.txt_type;\n\n switch (text_type) {\n case TXT_SAY:\n struct text_say say;\n memcpy(&say, receive_buffer, sizeof(struct text_say));\n\/\/ std::cin.readsome(tmp_buffer, sizeof(tmp_buffer));\n std::cout << \"\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\";\n std::cout << \"[\" << say.txt_channel << \"]\" << \"[\" << say.txt_username << \"]: \" << say.txt_text << std::endl;\n std::cout << \">\" << tmp_buffer << std::flush;\n memset(&tmp_buffer, 0, SAY_MAX);\n break;\n default:\n break;\n }\n }\n\n memset(&receive_buffer, 0, SAY_MAX);\n } \/\/ end of if client_socket\n\n } \/\/ end of if result\n\n } \/\/ end of while\n\n return 0;\n}<|endoftext|>"} {"text":"#include \"cinder\/app\/AppNative.h\"\n#include \"cinder\/app\/RendererGl.h\"\n\n#include \"cinder\/Rand.h\"\n\n#include \"cinder\/gl\/gl.h\"\n#include \"cinder\/gl\/Context.h\"\n#include \"cinder\/gl\/Shader.h\"\n#include \"cinder\/gl\/Vbo.h\"\n#include \"cinder\/gl\/Vao.h\"\n#include \"cinder\/gl\/GlslProg.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\n\/**\n Particle type holds information for rendering and simulation.\n Used to buffer initial simulation values.\n *\/\nstruct Particle\n{\n\tvec3\tpos;\n\tvec3\tppos;\n\tvec3\thome;\n\tColorA color;\t\/\/ Q: how to specify type of default attributes to Cinder? e.g. switch to Color8u\n\tfloat\tdamping;\n};\n\n\/\/ Home many particles to create. (600k default)\nconst int NUM_PARTICLES = 600e3;\n\n\/**\n\tSimple particle simulation with Verlet integration and mouse interaction.\n\tA sphere of particles is deformed by mouse interaction.\n\tSimulation is run using transform feedback on the GPU.\n\tparticleUpdate.vs defines the simulation update step.\n\tDesigned to have the same behavior as ParticleSphereCPU.\n *\/\nclass ParticleSphereGPUApp : public AppNative {\n public:\n\tvoid prepareSettings( Settings *settings ) override;\n\tvoid setup() override;\n\tvoid update() override;\n\tvoid draw() override;\n private:\n\tgl::GlslProgRef mRenderProg;\n\tgl::GlslProgRef mUpdateProg;\n\n\t\/\/ Descriptions of particle data layout.\n\tgl::VaoRef\t\tmAttributes[2];\n\t\/\/ Buffers holding raw particle data on GPU.\n\tgl::VboRef\t\tmParticleBuffer[2];\n\n\t\/\/ Current source and destination buffers for transform feedback.\n\t\/\/ Source and destination are swapped each frame after update.\n\tstd::uint32_t\tmSourceIndex\t\t= 0;\n\tstd::uint32_t\tmDestinationIndex\t= 1;\n\n\t\/\/ Mouse state suitable for passing as uniforms to update program\n\tbool\t\t\tmMouseDown = false;\n\tfloat\t\t\tmMouseForce = 0.0f;\n\tvec3\t\t\tmMousePos = vec3( 0, 0, 0 );\n};\n\nvoid ParticleSphereGPUApp::prepareSettings( Settings *settings )\n{\n\tsettings->setWindowSize( 1280, 720 );\n}\n\nvoid ParticleSphereGPUApp::setup()\n{\n\t\/\/ Create initial particle layout.\n\tvector particles;\n\tparticles.assign( NUM_PARTICLES, Particle() );\n\tconst float azimuth = 256.0f * M_PI \/ particles.size();\n\tconst float inclination = M_PI \/ particles.size();\n\tconst float radius = 180.0f;\n\tvec3 center = vec3( getWindowCenter(), 0.0f );\n\tfor( int i = 0; i < particles.size(); ++i )\n\t{\t\/\/ assign starting values to particles.\n\t\tfloat x = radius * sin( inclination * i ) * cos( azimuth * i );\n\t\tfloat y = radius * cos( inclination * i );\n\t\tfloat z = radius * sin( inclination * i ) * sin( azimuth * i );\n\n\t\tauto &p = particles.at( i );\n\t\tp.pos = center + vec3( x, y, z );\n\t\tp.home = p.pos;\n\t\tp.ppos = p.home + Rand::randVec3f() * 10.0f; \/\/ random initial velocity\n\t\tp.damping = Rand::randFloat( 0.965f, 0.985f );\n\t\tp.color = Color( CM_HSV, lmap( i, 0.0f, particles.size(), 0.0f, 0.66f ), 1.0f, 1.0f );\n\t}\n\n\t\/\/ Create particle buffers on GPU and copy data into the first buffer.\n\t\/\/ Mark as static since we only write from the CPU once.\n\tmParticleBuffer[mSourceIndex] = gl::Vbo::create( GL_ARRAY_BUFFER, particles.size() * sizeof(Particle), particles.data(), GL_STATIC_DRAW );\n\tmParticleBuffer[mDestinationIndex] = gl::Vbo::create( GL_ARRAY_BUFFER, particles.size() * sizeof(Particle), nullptr, GL_STATIC_DRAW );\n\n\t\/\/ Create a default color shader.\n\tmRenderProg = gl::getStockShader( gl::ShaderDef().color() );\n\n\tfor( int i = 0; i < 2; ++i )\n\t{\t\/\/ Describe the particle layout for OpenGL.\n\t\tmAttributes[i] = gl::Vao::create();\n\t\tmAttributes[i]->bind();\n\n\t\t\/\/ Define attributes as offsets into the bound particle buffer\n\t\tmParticleBuffer[i]->bind();\n\t\tgl::enableVertexAttribArray( 0 );\n\t\tgl::enableVertexAttribArray( 1 );\n\t\tgl::enableVertexAttribArray( 2 );\n\t\tgl::enableVertexAttribArray( 3 );\n\t\tgl::enableVertexAttribArray( 4 );\n\t\tgl::vertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, sizeof(Particle), (const GLvoid*)offsetof(Particle, pos) );\n\t\tgl::vertexAttribPointer( 1, 4, GL_FLOAT, GL_FALSE, sizeof(Particle), (const GLvoid*)offsetof(Particle, color) );\n\t\tgl::vertexAttribPointer( 2, 3, GL_FLOAT, GL_FALSE, sizeof(Particle), (const GLvoid*)offsetof(Particle, ppos) );\n\t\tgl::vertexAttribPointer( 3, 3, GL_FLOAT, GL_FALSE, sizeof(Particle), (const GLvoid*)offsetof(Particle, home) );\n\t\tgl::vertexAttribPointer( 4, 1, GL_FLOAT, GL_FALSE, sizeof(Particle), (const GLvoid*)offsetof(Particle, damping) );\n\t\tmAttributes[i]->unbind();\n\t}\n\n\t\/\/ Load our update program.\n\t\/\/ Match up our attribute locations with the description we gave.\n\tmUpdateProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( \"particleUpdate.vs\" ) )\n\t\t.feedbackFormat( GL_INTERLEAVED_ATTRIBS )\n\t\t.feedbackVaryings( { \"position\", \"pposition\", \"home\", \"color\", \"damping\" } )\n\t\t.attribLocation( \"iPosition\", 0 )\n\t\t.attribLocation( \"iColor\", 1 )\n\t\t.attribLocation( \"iPPosition\", 2 )\n\t\t.attribLocation( \"iHome\", 3 )\n\t\t.attribLocation( \"iDamping\", 4 )\n\t\t\t\t\t\t\t\t\t );\n\n\t\/\/ Listen to mouse events so we can send data as uniforms.\n\tgetWindow()->getSignalMouseDown().connect( [this]( MouseEvent event )\n\t\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\t mMouseDown = true;\n\t\t\t\t\t\t\t\t\t\t\t\t mMouseForce = 500.0f;\n\t\t\t\t\t\t\t\t\t\t\t\t mMousePos = vec3( event.getX(), event.getY(), 0.0f );\n\t\t\t\t\t\t\t\t\t\t\t } );\n\tgetWindow()->getSignalMouseDrag().connect( [this]( MouseEvent event )\n\t\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\t mMousePos = vec3( event.getX(), event.getY(), 0.0f );\n\t\t\t\t\t\t\t\t\t\t\t } );\n\tgetWindow()->getSignalMouseUp().connect( [this]( MouseEvent event )\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tmMouseForce = 0.0f;\n\t\t\t\t\t\t\t\t\t\t\t\tmMouseDown = false;\n\t\t\t\t\t\t\t\t\t\t\t} );\n}\n\nvoid ParticleSphereGPUApp::update()\n{\n\t\/\/ Update particles on the GPU\n\tgl::ScopedGlslProg prog( mUpdateProg );\n\tgl::ScopedState rasterizer( GL_RASTERIZER_DISCARD, true );\t\/\/ turn off fragment stage\n\tmUpdateProg->uniform( \"uMouseForce\", mMouseForce );\n\tmUpdateProg->uniform( \"uMousePos\", mMousePos );\n\n\t\/\/ Bind the source data (Attributes refer to specific buffers).\n\tgl::ScopedVao source( mAttributes[mSourceIndex] );\n\t\/\/ Bind destination as buffer base.\n\tgl::bindBufferBase( GL_TRANSFORM_FEEDBACK_BUFFER, 0, mParticleBuffer[mDestinationIndex] );\n\tgl::beginTransformFeedback( GL_POINTS );\n\n\t\/\/ Draw source into destination, performing our vertex transformations.\n\tgl::drawArrays( GL_POINTS, 0, NUM_PARTICLES );\n\n\tgl::endTransformFeedback();\n\n\t\/\/ Swap source and destination for next loop\n\tstd::swap( mSourceIndex, mDestinationIndex );\n\n\t\/\/ Update mouse force.\n\tif( mMouseDown ) {\n\t\tmMouseForce = 150.0f;\n\t}\n}\n\nvoid ParticleSphereGPUApp::draw()\n{\n\tgl::clear( Color( 0, 0, 0 ) );\n\tgl::setMatricesWindowPersp( getWindowSize() );\n\n\tgl::ScopedGlslProg render( mRenderProg );\n\tgl::ScopedVao vao( mAttributes[mSourceIndex] );\n\tgl::context()->setDefaultShaderVars();\n\tgl::drawArrays( GL_POINTS, 0, NUM_PARTICLES );\n}\n\nCINDER_APP_NATIVE( ParticleSphereGPUApp, RendererGl )\nRemoved question from source code.#include \"cinder\/app\/AppNative.h\"\n#include \"cinder\/app\/RendererGl.h\"\n\n#include \"cinder\/Rand.h\"\n\n#include \"cinder\/gl\/gl.h\"\n#include \"cinder\/gl\/Context.h\"\n#include \"cinder\/gl\/Shader.h\"\n#include \"cinder\/gl\/Vbo.h\"\n#include \"cinder\/gl\/Vao.h\"\n#include \"cinder\/gl\/GlslProg.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\n\/**\n Particle type holds information for rendering and simulation.\n Used to buffer initial simulation values.\n *\/\nstruct Particle\n{\n\tvec3\tpos;\n\tvec3\tppos;\n\tvec3\thome;\n\tColorA color;\n\tfloat\tdamping;\n};\n\n\/\/ Home many particles to create. (600k default)\nconst int NUM_PARTICLES = 600e3;\n\n\/**\n\tSimple particle simulation with Verlet integration and mouse interaction.\n\tA sphere of particles is deformed by mouse interaction.\n\tSimulation is run using transform feedback on the GPU.\n\tparticleUpdate.vs defines the simulation update step.\n\tDesigned to have the same behavior as ParticleSphereCPU.\n *\/\nclass ParticleSphereGPUApp : public AppNative {\n public:\n\tvoid prepareSettings( Settings *settings ) override;\n\tvoid setup() override;\n\tvoid update() override;\n\tvoid draw() override;\n private:\n\tgl::GlslProgRef mRenderProg;\n\tgl::GlslProgRef mUpdateProg;\n\n\t\/\/ Descriptions of particle data layout.\n\tgl::VaoRef\t\tmAttributes[2];\n\t\/\/ Buffers holding raw particle data on GPU.\n\tgl::VboRef\t\tmParticleBuffer[2];\n\n\t\/\/ Current source and destination buffers for transform feedback.\n\t\/\/ Source and destination are swapped each frame after update.\n\tstd::uint32_t\tmSourceIndex\t\t= 0;\n\tstd::uint32_t\tmDestinationIndex\t= 1;\n\n\t\/\/ Mouse state suitable for passing as uniforms to update program\n\tbool\t\t\tmMouseDown = false;\n\tfloat\t\t\tmMouseForce = 0.0f;\n\tvec3\t\t\tmMousePos = vec3( 0, 0, 0 );\n};\n\nvoid ParticleSphereGPUApp::prepareSettings( Settings *settings )\n{\n\tsettings->setWindowSize( 1280, 720 );\n}\n\nvoid ParticleSphereGPUApp::setup()\n{\n\t\/\/ Create initial particle layout.\n\tvector particles;\n\tparticles.assign( NUM_PARTICLES, Particle() );\n\tconst float azimuth = 256.0f * M_PI \/ particles.size();\n\tconst float inclination = M_PI \/ particles.size();\n\tconst float radius = 180.0f;\n\tvec3 center = vec3( getWindowCenter(), 0.0f );\n\tfor( int i = 0; i < particles.size(); ++i )\n\t{\t\/\/ assign starting values to particles.\n\t\tfloat x = radius * sin( inclination * i ) * cos( azimuth * i );\n\t\tfloat y = radius * cos( inclination * i );\n\t\tfloat z = radius * sin( inclination * i ) * sin( azimuth * i );\n\n\t\tauto &p = particles.at( i );\n\t\tp.pos = center + vec3( x, y, z );\n\t\tp.home = p.pos;\n\t\tp.ppos = p.home + Rand::randVec3f() * 10.0f; \/\/ random initial velocity\n\t\tp.damping = Rand::randFloat( 0.965f, 0.985f );\n\t\tp.color = Color( CM_HSV, lmap( i, 0.0f, particles.size(), 0.0f, 0.66f ), 1.0f, 1.0f );\n\t}\n\n\t\/\/ Create particle buffers on GPU and copy data into the first buffer.\n\t\/\/ Mark as static since we only write from the CPU once.\n\tmParticleBuffer[mSourceIndex] = gl::Vbo::create( GL_ARRAY_BUFFER, particles.size() * sizeof(Particle), particles.data(), GL_STATIC_DRAW );\n\tmParticleBuffer[mDestinationIndex] = gl::Vbo::create( GL_ARRAY_BUFFER, particles.size() * sizeof(Particle), nullptr, GL_STATIC_DRAW );\n\n\t\/\/ Create a default color shader.\n\tmRenderProg = gl::getStockShader( gl::ShaderDef().color() );\n\n\tfor( int i = 0; i < 2; ++i )\n\t{\t\/\/ Describe the particle layout for OpenGL.\n\t\tmAttributes[i] = gl::Vao::create();\n\t\tmAttributes[i]->bind();\n\n\t\t\/\/ Define attributes as offsets into the bound particle buffer\n\t\tmParticleBuffer[i]->bind();\n\t\tgl::enableVertexAttribArray( 0 );\n\t\tgl::enableVertexAttribArray( 1 );\n\t\tgl::enableVertexAttribArray( 2 );\n\t\tgl::enableVertexAttribArray( 3 );\n\t\tgl::enableVertexAttribArray( 4 );\n\t\tgl::vertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, sizeof(Particle), (const GLvoid*)offsetof(Particle, pos) );\n\t\tgl::vertexAttribPointer( 1, 4, GL_FLOAT, GL_FALSE, sizeof(Particle), (const GLvoid*)offsetof(Particle, color) );\n\t\tgl::vertexAttribPointer( 2, 3, GL_FLOAT, GL_FALSE, sizeof(Particle), (const GLvoid*)offsetof(Particle, ppos) );\n\t\tgl::vertexAttribPointer( 3, 3, GL_FLOAT, GL_FALSE, sizeof(Particle), (const GLvoid*)offsetof(Particle, home) );\n\t\tgl::vertexAttribPointer( 4, 1, GL_FLOAT, GL_FALSE, sizeof(Particle), (const GLvoid*)offsetof(Particle, damping) );\n\t\tmAttributes[i]->unbind();\n\t}\n\n\t\/\/ Load our update program.\n\t\/\/ Match up our attribute locations with the description we gave.\n\tmUpdateProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( \"particleUpdate.vs\" ) )\n\t\t.feedbackFormat( GL_INTERLEAVED_ATTRIBS )\n\t\t.feedbackVaryings( { \"position\", \"pposition\", \"home\", \"color\", \"damping\" } )\n\t\t.attribLocation( \"iPosition\", 0 )\n\t\t.attribLocation( \"iColor\", 1 )\n\t\t.attribLocation( \"iPPosition\", 2 )\n\t\t.attribLocation( \"iHome\", 3 )\n\t\t.attribLocation( \"iDamping\", 4 )\n\t\t\t\t\t\t\t\t\t );\n\n\t\/\/ Listen to mouse events so we can send data as uniforms.\n\tgetWindow()->getSignalMouseDown().connect( [this]( MouseEvent event )\n\t\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\t mMouseDown = true;\n\t\t\t\t\t\t\t\t\t\t\t\t mMouseForce = 500.0f;\n\t\t\t\t\t\t\t\t\t\t\t\t mMousePos = vec3( event.getX(), event.getY(), 0.0f );\n\t\t\t\t\t\t\t\t\t\t\t } );\n\tgetWindow()->getSignalMouseDrag().connect( [this]( MouseEvent event )\n\t\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\t mMousePos = vec3( event.getX(), event.getY(), 0.0f );\n\t\t\t\t\t\t\t\t\t\t\t } );\n\tgetWindow()->getSignalMouseUp().connect( [this]( MouseEvent event )\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tmMouseForce = 0.0f;\n\t\t\t\t\t\t\t\t\t\t\t\tmMouseDown = false;\n\t\t\t\t\t\t\t\t\t\t\t} );\n}\n\nvoid ParticleSphereGPUApp::update()\n{\n\t\/\/ Update particles on the GPU\n\tgl::ScopedGlslProg prog( mUpdateProg );\n\tgl::ScopedState rasterizer( GL_RASTERIZER_DISCARD, true );\t\/\/ turn off fragment stage\n\tmUpdateProg->uniform( \"uMouseForce\", mMouseForce );\n\tmUpdateProg->uniform( \"uMousePos\", mMousePos );\n\n\t\/\/ Bind the source data (Attributes refer to specific buffers).\n\tgl::ScopedVao source( mAttributes[mSourceIndex] );\n\t\/\/ Bind destination as buffer base.\n\tgl::bindBufferBase( GL_TRANSFORM_FEEDBACK_BUFFER, 0, mParticleBuffer[mDestinationIndex] );\n\tgl::beginTransformFeedback( GL_POINTS );\n\n\t\/\/ Draw source into destination, performing our vertex transformations.\n\tgl::drawArrays( GL_POINTS, 0, NUM_PARTICLES );\n\n\tgl::endTransformFeedback();\n\n\t\/\/ Swap source and destination for next loop\n\tstd::swap( mSourceIndex, mDestinationIndex );\n\n\t\/\/ Update mouse force.\n\tif( mMouseDown ) {\n\t\tmMouseForce = 150.0f;\n\t}\n}\n\nvoid ParticleSphereGPUApp::draw()\n{\n\tgl::clear( Color( 0, 0, 0 ) );\n\tgl::setMatricesWindowPersp( getWindowSize() );\n\n\tgl::ScopedGlslProg render( mRenderProg );\n\tgl::ScopedVao vao( mAttributes[mSourceIndex] );\n\tgl::context()->setDefaultShaderVars();\n\tgl::drawArrays( GL_POINTS, 0, NUM_PARTICLES );\n}\n\nCINDER_APP_NATIVE( ParticleSphereGPUApp, RendererGl )\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Steve Reinhardt\n *\/\n\n#include \"arch\/utility.hh\"\n#include \"arch\/faults.hh\"\n#include \"base\/cprintf.hh\"\n#include \"base\/inifile.hh\"\n#include \"base\/loader\/symtab.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/pollevent.hh\"\n#include \"base\/range.hh\"\n#include \"base\/stats\/events.hh\"\n#include \"base\/trace.hh\"\n#include \"cpu\/base.hh\"\n#include \"cpu\/exetrace.hh\"\n#include \"cpu\/profile.hh\"\n#include \"cpu\/simple\/base.hh\"\n#include \"cpu\/simple_thread.hh\"\n#include \"cpu\/smt.hh\"\n#include \"cpu\/static_inst.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"mem\/packet.hh\"\n#include \"sim\/builder.hh\"\n#include \"sim\/byteswap.hh\"\n#include \"sim\/debug.hh\"\n#include \"sim\/host.hh\"\n#include \"sim\/sim_events.hh\"\n#include \"sim\/sim_object.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/system.hh\"\n\n#if FULL_SYSTEM\n#include \"arch\/kernel_stats.hh\"\n#include \"arch\/stacktrace.hh\"\n#include \"arch\/tlb.hh\"\n#include \"arch\/vtophys.hh\"\n#include \"base\/remote_gdb.hh\"\n#else \/\/ !FULL_SYSTEM\n#include \"mem\/mem_object.hh\"\n#endif \/\/ FULL_SYSTEM\n\nusing namespace std;\nusing namespace TheISA;\n\nBaseSimpleCPU::BaseSimpleCPU(Params *p)\n : BaseCPU(p), thread(NULL), predecoder(NULL)\n{\n#if FULL_SYSTEM\n thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb);\n#else\n thread = new SimpleThread(this, \/* thread_num *\/ 0, p->process,\n \/* asid *\/ 0);\n#endif \/\/ !FULL_SYSTEM\n\n thread->setStatus(ThreadContext::Suspended);\n\n tc = thread->getTC();\n\n numInst = 0;\n startNumInst = 0;\n numLoad = 0;\n startNumLoad = 0;\n lastIcacheStall = 0;\n lastDcacheStall = 0;\n\n threadContexts.push_back(tc);\n}\n\nBaseSimpleCPU::~BaseSimpleCPU()\n{\n}\n\nvoid\nBaseSimpleCPU::deallocateContext(int thread_num)\n{\n \/\/ for now, these are equivalent\n suspendContext(thread_num);\n}\n\n\nvoid\nBaseSimpleCPU::haltContext(int thread_num)\n{\n \/\/ for now, these are equivalent\n suspendContext(thread_num);\n}\n\n\nvoid\nBaseSimpleCPU::regStats()\n{\n using namespace Stats;\n\n BaseCPU::regStats();\n\n numInsts\n .name(name() + \".num_insts\")\n .desc(\"Number of instructions executed\")\n ;\n\n numMemRefs\n .name(name() + \".num_refs\")\n .desc(\"Number of memory references\")\n ;\n\n notIdleFraction\n .name(name() + \".not_idle_fraction\")\n .desc(\"Percentage of non-idle cycles\")\n ;\n\n idleFraction\n .name(name() + \".idle_fraction\")\n .desc(\"Percentage of idle cycles\")\n ;\n\n icacheStallCycles\n .name(name() + \".icache_stall_cycles\")\n .desc(\"ICache total stall cycles\")\n .prereq(icacheStallCycles)\n ;\n\n dcacheStallCycles\n .name(name() + \".dcache_stall_cycles\")\n .desc(\"DCache total stall cycles\")\n .prereq(dcacheStallCycles)\n ;\n\n icacheRetryCycles\n .name(name() + \".icache_retry_cycles\")\n .desc(\"ICache total retry cycles\")\n .prereq(icacheRetryCycles)\n ;\n\n dcacheRetryCycles\n .name(name() + \".dcache_retry_cycles\")\n .desc(\"DCache total retry cycles\")\n .prereq(dcacheRetryCycles)\n ;\n\n idleFraction = constant(1.0) - notIdleFraction;\n}\n\nvoid\nBaseSimpleCPU::resetStats()\n{\n\/\/ startNumInst = numInst;\n \/\/ notIdleFraction = (_status != Idle);\n}\n\nvoid\nBaseSimpleCPU::serialize(ostream &os)\n{\n BaseCPU::serialize(os);\n\/\/ SERIALIZE_SCALAR(inst);\n nameOut(os, csprintf(\"%s.xc.0\", name()));\n thread->serialize(os);\n}\n\nvoid\nBaseSimpleCPU::unserialize(Checkpoint *cp, const string §ion)\n{\n BaseCPU::unserialize(cp, section);\n\/\/ UNSERIALIZE_SCALAR(inst);\n thread->unserialize(cp, csprintf(\"%s.xc.0\", section));\n}\n\nvoid\nchange_thread_state(int thread_number, int activate, int priority)\n{\n}\n\nFault\nBaseSimpleCPU::copySrcTranslate(Addr src)\n{\n#if 0\n static bool no_warn = true;\n int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;\n \/\/ Only support block sizes of 64 atm.\n assert(blk_size == 64);\n int offset = src & (blk_size - 1);\n\n \/\/ Make sure block doesn't span page\n if (no_warn &&\n (src & PageMask) != ((src + blk_size) & PageMask) &&\n (src >> 40) != 0xfffffc) {\n warn(\"Copied block source spans pages %x.\", src);\n no_warn = false;\n }\n\n memReq->reset(src & ~(blk_size - 1), blk_size);\n\n \/\/ translate to physical address\n Fault fault = thread->translateDataReadReq(req);\n\n if (fault == NoFault) {\n thread->copySrcAddr = src;\n thread->copySrcPhysAddr = memReq->paddr + offset;\n } else {\n assert(!fault->isAlignmentFault());\n\n thread->copySrcAddr = 0;\n thread->copySrcPhysAddr = 0;\n }\n return fault;\n#else\n return NoFault;\n#endif\n}\n\nFault\nBaseSimpleCPU::copy(Addr dest)\n{\n#if 0\n static bool no_warn = true;\n int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;\n \/\/ Only support block sizes of 64 atm.\n assert(blk_size == 64);\n uint8_t data[blk_size];\n \/\/assert(thread->copySrcAddr);\n int offset = dest & (blk_size - 1);\n\n \/\/ Make sure block doesn't span page\n if (no_warn &&\n (dest & PageMask) != ((dest + blk_size) & PageMask) &&\n (dest >> 40) != 0xfffffc) {\n no_warn = false;\n warn(\"Copied block destination spans pages %x. \", dest);\n }\n\n memReq->reset(dest & ~(blk_size -1), blk_size);\n \/\/ translate to physical address\n Fault fault = thread->translateDataWriteReq(req);\n\n if (fault == NoFault) {\n Addr dest_addr = memReq->paddr + offset;\n \/\/ Need to read straight from memory since we have more than 8 bytes.\n memReq->paddr = thread->copySrcPhysAddr;\n thread->mem->read(memReq, data);\n memReq->paddr = dest_addr;\n thread->mem->write(memReq, data);\n if (dcacheInterface) {\n memReq->cmd = Copy;\n memReq->completionEvent = NULL;\n memReq->paddr = thread->copySrcPhysAddr;\n memReq->dest = dest_addr;\n memReq->size = 64;\n memReq->time = curTick;\n memReq->flags &= ~INST_READ;\n dcacheInterface->access(memReq);\n }\n }\n else\n assert(!fault->isAlignmentFault());\n\n return fault;\n#else\n panic(\"copy not implemented\");\n return NoFault;\n#endif\n}\n\n#if FULL_SYSTEM\nAddr\nBaseSimpleCPU::dbg_vtophys(Addr addr)\n{\n return vtophys(tc, addr);\n}\n#endif \/\/ FULL_SYSTEM\n\n#if FULL_SYSTEM\nvoid\nBaseSimpleCPU::post_interrupt(int int_num, int index)\n{\n BaseCPU::post_interrupt(int_num, index);\n\n if (thread->status() == ThreadContext::Suspended) {\n DPRINTF(Quiesce,\"Suspended Processor awoke\\n\");\n thread->activate();\n }\n}\n#endif \/\/ FULL_SYSTEM\n\nvoid\nBaseSimpleCPU::checkForInterrupts()\n{\n#if FULL_SYSTEM\n if (check_interrupts(tc)) {\n Fault interrupt = interrupts.getInterrupt(tc);\n\n if (interrupt != NoFault) {\n interrupts.updateIntrInfo(tc);\n interrupt->invoke(tc);\n }\n }\n#endif\n}\n\n\nFault\nBaseSimpleCPU::setupFetchRequest(Request *req)\n{\n \/\/ set up memory request for instruction fetch\n#if ISA_HAS_DELAY_SLOT\n DPRINTF(Fetch,\"Fetch: PC:%08p NPC:%08p NNPC:%08p\\n\",thread->readPC(),\n thread->readNextPC(),thread->readNextNPC());\n#else\n DPRINTF(Fetch,\"Fetch: PC:%08p NPC:%08p\",thread->readPC(),\n thread->readNextPC());\n#endif\n\n req->setVirt(0, thread->readPC() & ~3, sizeof(MachInst), 0,\n thread->readPC());\n\n Fault fault = thread->translateInstReq(req);\n\n return fault;\n}\n\n\nvoid\nBaseSimpleCPU::preExecute()\n{\n \/\/ maintain $r0 semantics\n thread->setIntReg(ZeroReg, 0);\n#if THE_ISA == ALPHA_ISA\n thread->setFloatReg(ZeroReg, 0.0);\n#endif \/\/ ALPHA_ISA\n\n \/\/ keep an instruction count\n numInst++;\n numInsts++;\n\n thread->funcExeInst++;\n\n \/\/ check for instruction-count-based events\n comInstEventQueue[0]->serviceEvents(numInst);\n\n \/\/ decode the instruction\n inst = gtoh(inst);\n \/\/If we're not in the middle of a macro instruction\n if (!curMacroStaticInst) {\n StaticInstPtr instPtr = NULL;\n\n \/\/Predecode, ie bundle up an ExtMachInst\n \/\/This should go away once the constructor can be set up properly\n predecoder.setTC(thread->getTC());\n \/\/If more fetch data is needed, pass it in.\n if(predecoder.needMoreBytes())\n predecoder.moreBytes(thread->readPC(), 0, inst);\n else\n predecoder.process();\n \/\/If an instruction is ready, decode it\n if (predecoder.extMachInstReady())\n instPtr = StaticInst::decode(predecoder.getExtMachInst());\n\n \/\/If we decoded an instruction and it's microcoded, start pulling\n \/\/out micro ops\n if (instPtr && instPtr->isMacroOp()) {\n curMacroStaticInst = instPtr;\n curStaticInst = curMacroStaticInst->\n fetchMicroOp(thread->readMicroPC());\n } else {\n curStaticInst = instPtr;\n }\n } else {\n \/\/Read the next micro op from the macro op\n curStaticInst = curMacroStaticInst->\n fetchMicroOp(thread->readMicroPC());\n }\n\n \/\/If we decoded an instruction this \"tick\", record information about it.\n if(curStaticInst)\n {\n traceData = Trace::getInstRecord(curTick, tc, curStaticInst,\n thread->readPC());\n\n DPRINTF(Decode,\"Decode: Decoded %s instruction: 0x%x\\n\",\n curStaticInst->getName(), curStaticInst->machInst);\n\n#if FULL_SYSTEM\n thread->setInst(inst);\n#endif \/\/ FULL_SYSTEM\n }\n}\n\nvoid\nBaseSimpleCPU::postExecute()\n{\n#if FULL_SYSTEM\n if (thread->profile) {\n bool usermode = TheISA::inUserMode(tc);\n thread->profilePC = usermode ? 1 : thread->readPC();\n StaticInstPtr si(inst);\n ProfileNode *node = thread->profile->consume(tc, si);\n if (node)\n thread->profileNode = node;\n }\n#endif\n\n if (curStaticInst->isMemRef()) {\n numMemRefs++;\n }\n\n if (curStaticInst->isLoad()) {\n ++numLoad;\n comLoadEventQueue[0]->serviceEvents(numLoad);\n }\n\n traceFunctions(thread->readPC());\n\n if (traceData) {\n traceData->dump();\n delete traceData;\n traceData = NULL;\n }\n}\n\n\nvoid\nBaseSimpleCPU::advancePC(Fault fault)\n{\n if (fault != NoFault) {\n curMacroStaticInst = StaticInst::nullStaticInstPtr;\n fault->invoke(tc);\n thread->setMicroPC(0);\n thread->setNextMicroPC(1);\n } else if (predecoder.needMoreBytes()) {\n \/\/If we're at the last micro op for this instruction\n if (curStaticInst && curStaticInst->isLastMicroOp()) {\n \/\/We should be working with a macro op\n assert(curMacroStaticInst);\n \/\/Close out this macro op, and clean up the\n \/\/microcode state\n curMacroStaticInst = StaticInst::nullStaticInstPtr;\n thread->setMicroPC(0);\n thread->setNextMicroPC(1);\n }\n \/\/If we're still in a macro op\n if (curMacroStaticInst) {\n \/\/Advance the micro pc\n thread->setMicroPC(thread->readNextMicroPC());\n \/\/Advance the \"next\" micro pc. Note that there are no delay\n \/\/slots, and micro ops are \"word\" addressed.\n thread->setNextMicroPC(thread->readNextMicroPC() + 1);\n } else {\n \/\/ go to the next instruction\n thread->setPC(thread->readNextPC());\n thread->setNextPC(thread->readNextNPC());\n thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst));\n assert(thread->readNextPC() != thread->readNextNPC());\n }\n }\n\n#if FULL_SYSTEM\n Addr oldpc;\n do {\n oldpc = thread->readPC();\n system->pcEventQueue.service(tc);\n } while (oldpc != thread->readPC());\n#endif\n}\n\nUse a computed mask to mask out the fetch address and not a hard coded one.\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Steve Reinhardt\n *\/\n\n#include \"arch\/utility.hh\"\n#include \"arch\/faults.hh\"\n#include \"base\/cprintf.hh\"\n#include \"base\/inifile.hh\"\n#include \"base\/loader\/symtab.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/pollevent.hh\"\n#include \"base\/range.hh\"\n#include \"base\/stats\/events.hh\"\n#include \"base\/trace.hh\"\n#include \"cpu\/base.hh\"\n#include \"cpu\/exetrace.hh\"\n#include \"cpu\/profile.hh\"\n#include \"cpu\/simple\/base.hh\"\n#include \"cpu\/simple_thread.hh\"\n#include \"cpu\/smt.hh\"\n#include \"cpu\/static_inst.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"mem\/packet.hh\"\n#include \"sim\/builder.hh\"\n#include \"sim\/byteswap.hh\"\n#include \"sim\/debug.hh\"\n#include \"sim\/host.hh\"\n#include \"sim\/sim_events.hh\"\n#include \"sim\/sim_object.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/system.hh\"\n\n#if FULL_SYSTEM\n#include \"arch\/kernel_stats.hh\"\n#include \"arch\/stacktrace.hh\"\n#include \"arch\/tlb.hh\"\n#include \"arch\/vtophys.hh\"\n#include \"base\/remote_gdb.hh\"\n#else \/\/ !FULL_SYSTEM\n#include \"mem\/mem_object.hh\"\n#endif \/\/ FULL_SYSTEM\n\nusing namespace std;\nusing namespace TheISA;\n\nBaseSimpleCPU::BaseSimpleCPU(Params *p)\n : BaseCPU(p), thread(NULL), predecoder(NULL)\n{\n#if FULL_SYSTEM\n thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb);\n#else\n thread = new SimpleThread(this, \/* thread_num *\/ 0, p->process,\n \/* asid *\/ 0);\n#endif \/\/ !FULL_SYSTEM\n\n thread->setStatus(ThreadContext::Suspended);\n\n tc = thread->getTC();\n\n numInst = 0;\n startNumInst = 0;\n numLoad = 0;\n startNumLoad = 0;\n lastIcacheStall = 0;\n lastDcacheStall = 0;\n\n threadContexts.push_back(tc);\n}\n\nBaseSimpleCPU::~BaseSimpleCPU()\n{\n}\n\nvoid\nBaseSimpleCPU::deallocateContext(int thread_num)\n{\n \/\/ for now, these are equivalent\n suspendContext(thread_num);\n}\n\n\nvoid\nBaseSimpleCPU::haltContext(int thread_num)\n{\n \/\/ for now, these are equivalent\n suspendContext(thread_num);\n}\n\n\nvoid\nBaseSimpleCPU::regStats()\n{\n using namespace Stats;\n\n BaseCPU::regStats();\n\n numInsts\n .name(name() + \".num_insts\")\n .desc(\"Number of instructions executed\")\n ;\n\n numMemRefs\n .name(name() + \".num_refs\")\n .desc(\"Number of memory references\")\n ;\n\n notIdleFraction\n .name(name() + \".not_idle_fraction\")\n .desc(\"Percentage of non-idle cycles\")\n ;\n\n idleFraction\n .name(name() + \".idle_fraction\")\n .desc(\"Percentage of idle cycles\")\n ;\n\n icacheStallCycles\n .name(name() + \".icache_stall_cycles\")\n .desc(\"ICache total stall cycles\")\n .prereq(icacheStallCycles)\n ;\n\n dcacheStallCycles\n .name(name() + \".dcache_stall_cycles\")\n .desc(\"DCache total stall cycles\")\n .prereq(dcacheStallCycles)\n ;\n\n icacheRetryCycles\n .name(name() + \".icache_retry_cycles\")\n .desc(\"ICache total retry cycles\")\n .prereq(icacheRetryCycles)\n ;\n\n dcacheRetryCycles\n .name(name() + \".dcache_retry_cycles\")\n .desc(\"DCache total retry cycles\")\n .prereq(dcacheRetryCycles)\n ;\n\n idleFraction = constant(1.0) - notIdleFraction;\n}\n\nvoid\nBaseSimpleCPU::resetStats()\n{\n\/\/ startNumInst = numInst;\n \/\/ notIdleFraction = (_status != Idle);\n}\n\nvoid\nBaseSimpleCPU::serialize(ostream &os)\n{\n BaseCPU::serialize(os);\n\/\/ SERIALIZE_SCALAR(inst);\n nameOut(os, csprintf(\"%s.xc.0\", name()));\n thread->serialize(os);\n}\n\nvoid\nBaseSimpleCPU::unserialize(Checkpoint *cp, const string §ion)\n{\n BaseCPU::unserialize(cp, section);\n\/\/ UNSERIALIZE_SCALAR(inst);\n thread->unserialize(cp, csprintf(\"%s.xc.0\", section));\n}\n\nvoid\nchange_thread_state(int thread_number, int activate, int priority)\n{\n}\n\nFault\nBaseSimpleCPU::copySrcTranslate(Addr src)\n{\n#if 0\n static bool no_warn = true;\n int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;\n \/\/ Only support block sizes of 64 atm.\n assert(blk_size == 64);\n int offset = src & (blk_size - 1);\n\n \/\/ Make sure block doesn't span page\n if (no_warn &&\n (src & PageMask) != ((src + blk_size) & PageMask) &&\n (src >> 40) != 0xfffffc) {\n warn(\"Copied block source spans pages %x.\", src);\n no_warn = false;\n }\n\n memReq->reset(src & ~(blk_size - 1), blk_size);\n\n \/\/ translate to physical address\n Fault fault = thread->translateDataReadReq(req);\n\n if (fault == NoFault) {\n thread->copySrcAddr = src;\n thread->copySrcPhysAddr = memReq->paddr + offset;\n } else {\n assert(!fault->isAlignmentFault());\n\n thread->copySrcAddr = 0;\n thread->copySrcPhysAddr = 0;\n }\n return fault;\n#else\n return NoFault;\n#endif\n}\n\nFault\nBaseSimpleCPU::copy(Addr dest)\n{\n#if 0\n static bool no_warn = true;\n int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;\n \/\/ Only support block sizes of 64 atm.\n assert(blk_size == 64);\n uint8_t data[blk_size];\n \/\/assert(thread->copySrcAddr);\n int offset = dest & (blk_size - 1);\n\n \/\/ Make sure block doesn't span page\n if (no_warn &&\n (dest & PageMask) != ((dest + blk_size) & PageMask) &&\n (dest >> 40) != 0xfffffc) {\n no_warn = false;\n warn(\"Copied block destination spans pages %x. \", dest);\n }\n\n memReq->reset(dest & ~(blk_size -1), blk_size);\n \/\/ translate to physical address\n Fault fault = thread->translateDataWriteReq(req);\n\n if (fault == NoFault) {\n Addr dest_addr = memReq->paddr + offset;\n \/\/ Need to read straight from memory since we have more than 8 bytes.\n memReq->paddr = thread->copySrcPhysAddr;\n thread->mem->read(memReq, data);\n memReq->paddr = dest_addr;\n thread->mem->write(memReq, data);\n if (dcacheInterface) {\n memReq->cmd = Copy;\n memReq->completionEvent = NULL;\n memReq->paddr = thread->copySrcPhysAddr;\n memReq->dest = dest_addr;\n memReq->size = 64;\n memReq->time = curTick;\n memReq->flags &= ~INST_READ;\n dcacheInterface->access(memReq);\n }\n }\n else\n assert(!fault->isAlignmentFault());\n\n return fault;\n#else\n panic(\"copy not implemented\");\n return NoFault;\n#endif\n}\n\n#if FULL_SYSTEM\nAddr\nBaseSimpleCPU::dbg_vtophys(Addr addr)\n{\n return vtophys(tc, addr);\n}\n#endif \/\/ FULL_SYSTEM\n\n#if FULL_SYSTEM\nvoid\nBaseSimpleCPU::post_interrupt(int int_num, int index)\n{\n BaseCPU::post_interrupt(int_num, index);\n\n if (thread->status() == ThreadContext::Suspended) {\n DPRINTF(Quiesce,\"Suspended Processor awoke\\n\");\n thread->activate();\n }\n}\n#endif \/\/ FULL_SYSTEM\n\nvoid\nBaseSimpleCPU::checkForInterrupts()\n{\n#if FULL_SYSTEM\n if (check_interrupts(tc)) {\n Fault interrupt = interrupts.getInterrupt(tc);\n\n if (interrupt != NoFault) {\n interrupts.updateIntrInfo(tc);\n interrupt->invoke(tc);\n }\n }\n#endif\n}\n\n\nFault\nBaseSimpleCPU::setupFetchRequest(Request *req)\n{\n \/\/ set up memory request for instruction fetch\n#if ISA_HAS_DELAY_SLOT\n DPRINTF(Fetch,\"Fetch: PC:%08p NPC:%08p NNPC:%08p\\n\",thread->readPC(),\n thread->readNextPC(),thread->readNextNPC());\n#else\n DPRINTF(Fetch,\"Fetch: PC:%08p NPC:%08p\",thread->readPC(),\n thread->readNextPC());\n#endif\n\n \/\/ This will generate a mask which aligns the pc on MachInst size\n \/\/ boundaries. It won't work for non-power-of-two sized MachInsts, but\n \/\/ it will work better than a hard coded mask.\n const Addr PCMask = ~(sizeof(MachInst) - 1);\n req->setVirt(0, thread->readPC() & PCMask, sizeof(MachInst), 0,\n thread->readPC());\n\n Fault fault = thread->translateInstReq(req);\n\n return fault;\n}\n\n\nvoid\nBaseSimpleCPU::preExecute()\n{\n \/\/ maintain $r0 semantics\n thread->setIntReg(ZeroReg, 0);\n#if THE_ISA == ALPHA_ISA\n thread->setFloatReg(ZeroReg, 0.0);\n#endif \/\/ ALPHA_ISA\n\n \/\/ keep an instruction count\n numInst++;\n numInsts++;\n\n thread->funcExeInst++;\n\n \/\/ check for instruction-count-based events\n comInstEventQueue[0]->serviceEvents(numInst);\n\n \/\/ decode the instruction\n inst = gtoh(inst);\n \/\/If we're not in the middle of a macro instruction\n if (!curMacroStaticInst) {\n StaticInstPtr instPtr = NULL;\n\n \/\/Predecode, ie bundle up an ExtMachInst\n \/\/This should go away once the constructor can be set up properly\n predecoder.setTC(thread->getTC());\n \/\/If more fetch data is needed, pass it in.\n if(predecoder.needMoreBytes())\n predecoder.moreBytes(thread->readPC(), 0, inst);\n else\n predecoder.process();\n \/\/If an instruction is ready, decode it\n if (predecoder.extMachInstReady())\n instPtr = StaticInst::decode(predecoder.getExtMachInst());\n\n \/\/If we decoded an instruction and it's microcoded, start pulling\n \/\/out micro ops\n if (instPtr && instPtr->isMacroOp()) {\n curMacroStaticInst = instPtr;\n curStaticInst = curMacroStaticInst->\n fetchMicroOp(thread->readMicroPC());\n } else {\n curStaticInst = instPtr;\n }\n } else {\n \/\/Read the next micro op from the macro op\n curStaticInst = curMacroStaticInst->\n fetchMicroOp(thread->readMicroPC());\n }\n\n \/\/If we decoded an instruction this \"tick\", record information about it.\n if(curStaticInst)\n {\n traceData = Trace::getInstRecord(curTick, tc, curStaticInst,\n thread->readPC());\n\n DPRINTF(Decode,\"Decode: Decoded %s instruction: 0x%x\\n\",\n curStaticInst->getName(), curStaticInst->machInst);\n\n#if FULL_SYSTEM\n thread->setInst(inst);\n#endif \/\/ FULL_SYSTEM\n }\n}\n\nvoid\nBaseSimpleCPU::postExecute()\n{\n#if FULL_SYSTEM\n if (thread->profile) {\n bool usermode = TheISA::inUserMode(tc);\n thread->profilePC = usermode ? 1 : thread->readPC();\n StaticInstPtr si(inst);\n ProfileNode *node = thread->profile->consume(tc, si);\n if (node)\n thread->profileNode = node;\n }\n#endif\n\n if (curStaticInst->isMemRef()) {\n numMemRefs++;\n }\n\n if (curStaticInst->isLoad()) {\n ++numLoad;\n comLoadEventQueue[0]->serviceEvents(numLoad);\n }\n\n traceFunctions(thread->readPC());\n\n if (traceData) {\n traceData->dump();\n delete traceData;\n traceData = NULL;\n }\n}\n\n\nvoid\nBaseSimpleCPU::advancePC(Fault fault)\n{\n if (fault != NoFault) {\n curMacroStaticInst = StaticInst::nullStaticInstPtr;\n fault->invoke(tc);\n thread->setMicroPC(0);\n thread->setNextMicroPC(1);\n } else if (predecoder.needMoreBytes()) {\n \/\/If we're at the last micro op for this instruction\n if (curStaticInst && curStaticInst->isLastMicroOp()) {\n \/\/We should be working with a macro op\n assert(curMacroStaticInst);\n \/\/Close out this macro op, and clean up the\n \/\/microcode state\n curMacroStaticInst = StaticInst::nullStaticInstPtr;\n thread->setMicroPC(0);\n thread->setNextMicroPC(1);\n }\n \/\/If we're still in a macro op\n if (curMacroStaticInst) {\n \/\/Advance the micro pc\n thread->setMicroPC(thread->readNextMicroPC());\n \/\/Advance the \"next\" micro pc. Note that there are no delay\n \/\/slots, and micro ops are \"word\" addressed.\n thread->setNextMicroPC(thread->readNextMicroPC() + 1);\n } else {\n \/\/ go to the next instruction\n thread->setPC(thread->readNextPC());\n thread->setNextPC(thread->readNextNPC());\n thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst));\n assert(thread->readNextPC() != thread->readNextNPC());\n }\n }\n\n#if FULL_SYSTEM\n Addr oldpc;\n do {\n oldpc = thread->readPC();\n system->pcEventQueue.service(tc);\n } while (oldpc != thread->readPC());\n#endif\n}\n\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\r\n#include \"Effect10.h\"\r\n\r\nusing namespace System;\r\nusing namespace System::Collections::Generic;\r\n\r\nnamespace SlimDX\r\n{\r\n\tnamespace Direct3D10\r\n\t{\r\n\t\tEffectPass10::EffectPass10(ID3D10EffectPass* native) : native(native) {\r\n\t\t}\r\n\r\n\t\tvoid EffectPass10::Apply() {\r\n\t\t\tnative->Apply(0);\r\n\t\t}\r\n\r\n\t\tEffectPassDescription10 EffectPass10::GetDescription() {\r\n\t\t\tEffectPassDescription10 result;\r\n\t\t\tD3D10_PASS_DESC passDesc;\r\n\t\t\tnative->GetDesc(&passDesc);\r\n\r\n\t\t\tresult.Name = gcnew System::String(passDesc.Name);\r\n\t\t\tresult.Annotations = passDesc.Annotations;\r\n\t\t\tresult.StencilRef = passDesc.StencilRef;\r\n\t\t\tresult.SampleMask = passDesc.SampleMask;\r\n\t\t\tresult.BlendFactorR = passDesc.BlendFactor[0];\r\n\t\t\tresult.BlendFactorG = passDesc.BlendFactor[1];\r\n\t\t\tresult.BlendFactorB = passDesc.BlendFactor[2];\r\n\t\t\tresult.BlendFactorA = passDesc.BlendFactor[3];\r\n\r\n\t\t\tShaderSignature10 signature;\r\n\t\t\tsignature.Signature = IntPtr(passDesc.pIAInputSignature);\r\n\t\t\tsignature.SignatureLength = passDesc.IAInputSignatureSize;\r\n\r\n\t\t\tresult.ShaderSignature = signature;\r\n\r\n\t\t\treturn result;\r\n\t\t}\r\n\r\n\t\tEffectTechnique10::EffectTechnique10(ID3D10EffectTechnique* native) : native(native) {\r\n\t\t\tpasses = gcnew Dictionary();\r\n\t\t}\r\n\r\n\t\tIEffectPass10^ EffectTechnique10::GetPassByIndex(int index) {\r\n\t\t\tID3D10EffectPass* pass = native->GetPassByIndex(index);\r\n\t\t\tif(!passes->ContainsKey(IntPtr(pass))) {\r\n\t\t\t\tpasses->Add(IntPtr(pass), gcnew EffectPass10(pass));;\r\n\t\t\t}\r\n\r\n\t\t\treturn passes[IntPtr(pass)];\r\n\t\t}\r\n\r\n\t\tEffect10::Effect10( ID3D10Effect* native ) : ComObject(native) {\r\n\t\t\ttechniques = gcnew Dictionary();\r\n\t\t}\r\n\r\n\t\tEffect10::Effect10( System::IntPtr native ) : ComObject(native) {\r\n\t\t\ttechniques = gcnew Dictionary();\r\n\t\t}\r\n\r\n\t\tIEffectTechnique10^ Effect10::GetTechniqueByIndex(int index) {\r\n\t\t\tID3D10EffectTechnique* technique = NativePointer->GetTechniqueByIndex(index);\r\n\t\t\tif(!techniques->ContainsKey(IntPtr(technique))) {\r\n\t\t\t\ttechniques->Add(IntPtr(technique), gcnew EffectTechnique10(technique));;\r\n\t\t\t}\r\n\r\n\t\t\treturn techniques[IntPtr(technique)];\r\n\t\t}\r\n\t}\r\n}Fixed a signed\/unsigned warning.#include \"stdafx.h\"\r\n#include \"Effect10.h\"\r\n\r\nusing namespace System;\r\nusing namespace System::Collections::Generic;\r\n\r\nnamespace SlimDX\r\n{\r\n\tnamespace Direct3D10\r\n\t{\r\n\t\tEffectPass10::EffectPass10(ID3D10EffectPass* native) : native(native) {\r\n\t\t}\r\n\r\n\t\tvoid EffectPass10::Apply() {\r\n\t\t\tnative->Apply(0);\r\n\t\t}\r\n\r\n\t\tEffectPassDescription10 EffectPass10::GetDescription() {\r\n\t\t\tEffectPassDescription10 result;\r\n\t\t\tD3D10_PASS_DESC passDesc;\r\n\t\t\tnative->GetDesc(&passDesc);\r\n\r\n\t\t\tresult.Name = gcnew System::String(passDesc.Name);\r\n\t\t\tresult.Annotations = passDesc.Annotations;\r\n\t\t\tresult.StencilRef = passDesc.StencilRef;\r\n\t\t\tresult.SampleMask = passDesc.SampleMask;\r\n\t\t\tresult.BlendFactorR = passDesc.BlendFactor[0];\r\n\t\t\tresult.BlendFactorG = passDesc.BlendFactor[1];\r\n\t\t\tresult.BlendFactorB = passDesc.BlendFactor[2];\r\n\t\t\tresult.BlendFactorA = passDesc.BlendFactor[3];\r\n\r\n\t\t\tShaderSignature10 signature;\r\n\t\t\tsignature.Signature = IntPtr(passDesc.pIAInputSignature);\r\n\t\t\tsignature.SignatureLength = static_cast( passDesc.IAInputSignatureSize );\r\n\r\n\t\t\tresult.ShaderSignature = signature;\r\n\r\n\t\t\treturn result;\r\n\t\t}\r\n\r\n\t\tEffectTechnique10::EffectTechnique10(ID3D10EffectTechnique* native) : native(native) {\r\n\t\t\tpasses = gcnew Dictionary();\r\n\t\t}\r\n\r\n\t\tIEffectPass10^ EffectTechnique10::GetPassByIndex(int index) {\r\n\t\t\tID3D10EffectPass* pass = native->GetPassByIndex(index);\r\n\t\t\tif(!passes->ContainsKey(IntPtr(pass))) {\r\n\t\t\t\tpasses->Add(IntPtr(pass), gcnew EffectPass10(pass));;\r\n\t\t\t}\r\n\r\n\t\t\treturn passes[IntPtr(pass)];\r\n\t\t}\r\n\r\n\t\tEffect10::Effect10( ID3D10Effect* native ) : ComObject(native) {\r\n\t\t\ttechniques = gcnew Dictionary();\r\n\t\t}\r\n\r\n\t\tEffect10::Effect10( System::IntPtr native ) : ComObject(native) {\r\n\t\t\ttechniques = gcnew Dictionary();\r\n\t\t}\r\n\r\n\t\tIEffectTechnique10^ Effect10::GetTechniqueByIndex(int index) {\r\n\t\t\tID3D10EffectTechnique* technique = NativePointer->GetTechniqueByIndex(index);\r\n\t\t\tif(!techniques->ContainsKey(IntPtr(technique))) {\r\n\t\t\t\ttechniques->Add(IntPtr(technique), gcnew EffectTechnique10(technique));;\r\n\t\t\t}\r\n\r\n\t\t\treturn techniques[IntPtr(technique)];\r\n\t\t}\r\n\t}\r\n}<|endoftext|>"} {"text":"Fix another name I missed. Review URL: http:\/\/codereview.chromium.org\/113727<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"SimpleIni.h\"\n#include \"QuadTree.cpp\"\n#include \"Config.cpp\"\n#include \"morton.h\"\n\nclass Preprocessor {\npublic:\n CSimpleIniA *config;\n\n explicit Preprocessor(const char *path_config) {\n config = new CSimpleIniA(true, false, false);\n\n if (config->LoadFile(path_config) < 0)\n {\n throw std::runtime_error(\"Configuration file parsing error\");\n }\n\n boost::filesystem::path\n path_texture(config->GetValue(Config::TEXTURE_MANAGEMENT, Config::FILE_PPM, Config::DEFAULT));\n boost::filesystem::path dir_texture = path_texture.parent_path();\n Magick::InitializeMagick(dir_texture.c_str());\n }\n\n ~Preprocessor() = default;\n\n bool prepare_single_raster(const char *name_raster) {\n Magick::Image image;\n try\n {\n image.read(name_raster);\n Magick::Geometry geometry = image.size();\n size_t side = (size_t) std::pow(2, std::floor(std::log(std::min(geometry.width(), geometry.height())) \/ std::log(2)));\n geometry.aspect(false);\n geometry.width(side);\n geometry.height(side);\n image.crop(geometry);\n image.write(config->GetValue(Config::TEXTURE_MANAGEMENT, Config::FILE_PPM, Config::DEFAULT));\n }\n catch (Magick::Exception &error_)\n {\n std::cout << \"Caught exception: \" << error_.what() << std::endl;\n return false;\n };\n return true;\n }\n\n bool prepare_mipmap() {\n auto tile_size = (size_t) atoi(config->GetValue(Config::TEXTURE_MANAGEMENT, Config::TILE_SIZE, Config::DEFAULT));\n if ((tile_size & (tile_size - 1)) != 0)\n {\n throw std::runtime_error(\"Tile size is not a power of 2\");\n }\n\n uint32_t count_threads = 0;\n count_threads = atoi(config->GetValue(Config::TEXTURE_MANAGEMENT, Config::RUN_IN_PARALLEL, Config::DEFAULT)) != 1 ? 1 : thread::hardware_concurrency();\n\n size_t dim_x = 0, dim_y = 0;\n\n std::ifstream input;\n input.open(config->GetValue(Config::TEXTURE_MANAGEMENT, Config::FILE_PPM, Config::DEFAULT), std::ifstream::in | std::ifstream::binary);\n read_ppm_header(input, dim_x, dim_y);\n input.close();\n\n uint32_t tree_depth = QuadTree::calculate_depth(dim_x, tile_size);\n size_t first_node_leaf = QuadTree::get_first_node_id_of_depth(tree_depth);\n size_t last_node_leaf = QuadTree::get_first_node_id_of_depth(tree_depth) + QuadTree::get_length_of_depth(tree_depth) - 1;\n\n size_t nodes_per_thread = (last_node_leaf - first_node_leaf + 1) \/ count_threads;\n\n std::vector thread_pool;\n auto *texture_lock = new std::mutex;\n\n for (uint32_t i = 0; i < count_threads; i++)\n {\n size_t node_start = first_node_leaf + i * nodes_per_thread;\n size_t node_end = (i != count_threads - 1) ? first_node_leaf + (i + 1) * nodes_per_thread : last_node_leaf;\n thread_pool.emplace_back([=]()\n { write_tile_range_at_depth((*texture_lock), tile_size, tree_depth, node_start, node_end); });\n }\n for (auto &_thread : thread_pool)\n {\n _thread.join();\n }\n\n thread_pool.clear();\n\n for (uint32_t _depth = tree_depth - 1; _depth > 0; _depth--)\n {\n first_node_leaf = QuadTree::get_first_node_id_of_depth(_depth);\n last_node_leaf = QuadTree::get_first_node_id_of_depth(_depth) + QuadTree::get_length_of_depth(_depth) - 1;\n\n nodes_per_thread = (last_node_leaf - first_node_leaf + 1) \/ count_threads;\n\n if (nodes_per_thread > 0)\n {\n for (uint32_t i = 0; i < count_threads; i++)\n {\n size_t node_start = first_node_leaf + i * nodes_per_thread;\n size_t node_end = (i != count_threads - 1) ? first_node_leaf + (i + 1) * nodes_per_thread : last_node_leaf;\n thread_pool.emplace_back([=]()\n { stitch_tile_range(tile_size, node_start, node_end); });\n }\n }\n else\n {\n stitch_tile_range(tile_size, first_node_leaf, last_node_leaf);\n }\n for (auto &_thread : thread_pool)\n {\n _thread.join();\n }\n }\n\n std::list children_imgs;\n\n for (size_t i = 0; i < 4; i++)\n {\n Magick::Image _child;\n _child.read(\"id_\" + std::to_string(QuadTree::get_child_id(0, i)) + \".ppm\");\n children_imgs.push_back(_child);\n }\n\n write_stitched_tile(0, tile_size, children_imgs);\n\n const char *file_mipmap = config->GetValue(Config::TEXTURE_MANAGEMENT, Config::FILE_MIPMAP, Config::DEFAULT);\n std::ofstream output;\n output.open(file_mipmap, std::ofstream::out | std::ofstream::binary | std::ofstream::trunc);\n\n auto *buf_tile = new char[tile_size * tile_size * 3];\n\n for (uint32_t _depth = 0; _depth <= tree_depth; _depth++)\n {\n first_node_leaf = QuadTree::get_first_node_id_of_depth(_depth);\n last_node_leaf = QuadTree::get_first_node_id_of_depth(_depth) + QuadTree::get_length_of_depth(_depth) - 1;\n\n for (size_t _id = first_node_leaf; _id <= last_node_leaf; _id++)\n {\n std::ifstream input_tile;\n input_tile.open(\"id_\" + std::to_string(_id) + \".ppm\", std::ifstream::in | std::ifstream::binary);\n\n read_ppm_header(input_tile, dim_x, dim_y);\n input_tile.read(&buf_tile[0], tile_size * tile_size * 3);\n\n input_tile.close();\n\n output.write(&buf_tile[0], tile_size * tile_size * 3);\n\n if (atoi(config->GetValue(Config::DEBUG, Config::KEEP_INTERMEDIATE_DATA, Config::DEFAULT)) != 1)\n {\n std::remove((\"id_\" + std::to_string(_id) + \".ppm\").c_str());\n }\n }\n }\n\n output.close();\n\n return false;\n }\n\nprivate:\n\n void read_ppm_header(std::ifstream &_ifs, size_t &_dim_x, size_t &_dim_y) {\n auto *buf_file_version = new char[3];\n _ifs.getline(&buf_file_version[0], 3, '\\x0A');\n\n if (strcmp(buf_file_version, \"P6\") != 0)\n {\n throw std::runtime_error(\"PPM file format not equal to P6\");\n }\n\n auto *buf_dim_x = new char[8];\n auto *buf_dim_y = new char[8];\n auto *buf_color_depth = new char[8];\n\n _ifs.getline(&buf_dim_x[0], 8, '\\x20');\n _ifs.getline(&buf_dim_y[0], 8, '\\x0A');\n _ifs.getline(&buf_color_depth[0], 8, '\\x0A');\n\n _dim_x = (size_t) atol(buf_dim_x);\n _dim_y = (size_t) atol(buf_dim_y);\n auto color_depth = (short) atoi(buf_color_depth);\n\n if (color_depth != 255)\n {\n throw std::runtime_error(\"PPM color depth not equal to 255\");\n }\n\n if (_dim_x != _dim_y || (_dim_x & (_dim_x - 1)) != 0)\n {\n throw std::runtime_error(\"PPM dimensions are not equal or not a power of 2\");\n }\n }\n\n void write_tile_range_at_depth(std::mutex &_texture_lock, const size_t _tile_size, const uint32_t _depth, const size_t _node_start, const size_t _node_end) {\n std::ifstream _ifs;\n _ifs.open(config->GetValue(Config::TEXTURE_MANAGEMENT, Config::FILE_PPM, Config::DEFAULT), std::ifstream::in | std::ifstream::binary);\n\n size_t dim_x = 0, dim_y = 0;\n\n _texture_lock.lock();\n read_ppm_header(_ifs, dim_x, dim_y);\n _texture_lock.unlock();\n\n streamoff _offset_header = _ifs.tellg();\n\n auto *buf_tile = new char[_tile_size * _tile_size * 3];\n std::string buf_header = \"P6\\x0A\" + std::to_string(_tile_size) + \"\\x20\" + std::to_string(_tile_size) + \"\\x0A\" + \"255\" + \"\\x0A\";\n\n size_t _node_first = QuadTree::get_first_node_id_of_depth(_depth);\n size_t _tiles_per_row = QuadTree::get_tiles_per_row(_depth);\n\n for (size_t _id = _node_start; _id <= _node_end; _id++)\n {\n uint_fast64_t skip_cols, skip_rows;\n morton2D_64_decode((uint_fast64_t) (_id - _node_first), skip_cols, skip_rows);\n\n _texture_lock.lock();\n\n _ifs.seekg(_offset_header);\n _ifs.ignore(skip_rows * _tiles_per_row * _tile_size * _tile_size * 3);\n\n for (uint32_t _row = 0; _row < _tile_size; _row++)\n {\n _ifs.ignore(skip_cols * _tile_size * 3);\n _ifs.read(&buf_tile[_row * _tile_size * 3], _tile_size * 3);\n _ifs.ignore((_tiles_per_row - skip_cols - 1) * _tile_size * 3);\n }\n\n _texture_lock.unlock();\n\n std::ofstream output;\n output.open(\"id_\" + std::to_string(_id) + \".ppm\", std::ofstream::out | std::ofstream::binary | std::ofstream::trunc);\n output.write(&buf_header.c_str()[0], buf_header.size());\n output.write(&buf_tile[0], _tile_size * _tile_size * 3);\n output.close();\n }\n\n _ifs.close();\n }\n\n void stitch_tile_range(const size_t _tile_size, const size_t _node_start, const size_t _node_end) {\n for (size_t _id = _node_start; _id <= _node_end; _id++)\n {\n std::list children_imgs;\n\n for (size_t i = 0; i < 4; i++)\n {\n Magick::Image _child;\n _child.read(\"id_\" + std::to_string(QuadTree::get_child_id(_id, i)) + \".ppm\");\n children_imgs.push_back(_child);\n }\n\n write_stitched_tile(_id, _tile_size, children_imgs);\n }\n }\n\n void write_stitched_tile(size_t _id, size_t _tile_size, list &_child_imgs) {\n Magick::Montage montage_settings;\n montage_settings.tile(Magick::Geometry(2, 2));\n montage_settings.geometry(Magick::Geometry(_tile_size, _tile_size));\n\n std::list montage_list;\n Magick::montageImages(&montage_list, _child_imgs.begin(), _child_imgs.end(), montage_settings);\n Magick::writeImages(montage_list.begin(), montage_list.end(), \"id_\" + std::to_string(_id) + \".ppm\");\n\n Magick::Image image;\n image.read(\"id_\" + std::to_string(_id) + \".ppm\");\n Magick::Geometry geometry = image.size();\n geometry.width(_tile_size);\n geometry.height(_tile_size);\n image.scale(geometry);\n image.depth(8);\n image.write(\"id_\" + std::to_string(_id) + \".ppm\");\n }\n};* restructure thread loops;#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"SimpleIni.h\"\n#include \"QuadTree.cpp\"\n#include \"Config.cpp\"\n#include \"morton.h\"\n\nclass Preprocessor {\npublic:\n CSimpleIniA *config;\n\n explicit Preprocessor(const char *path_config) {\n config = new CSimpleIniA(true, false, false);\n\n if (config->LoadFile(path_config) < 0)\n {\n throw std::runtime_error(\"Configuration file parsing error\");\n }\n\n boost::filesystem::path\n path_texture(config->GetValue(Config::TEXTURE_MANAGEMENT, Config::FILE_PPM, Config::DEFAULT));\n boost::filesystem::path dir_texture = path_texture.parent_path();\n Magick::InitializeMagick(dir_texture.c_str());\n }\n\n ~Preprocessor() = default;\n\n bool prepare_single_raster(const char *name_raster) {\n Magick::Image image;\n try\n {\n image.read(name_raster);\n Magick::Geometry geometry = image.size();\n size_t side = (size_t) std::pow(2, std::floor(std::log(std::min(geometry.width(), geometry.height())) \/ std::log(2)));\n geometry.aspect(false);\n geometry.width(side);\n geometry.height(side);\n image.crop(geometry);\n image.write(config->GetValue(Config::TEXTURE_MANAGEMENT, Config::FILE_PPM, Config::DEFAULT));\n }\n catch (Magick::Exception &error_)\n {\n std::cout << \"Caught exception: \" << error_.what() << std::endl;\n return false;\n };\n return true;\n }\n\n bool prepare_mipmap() {\n auto tile_size = (size_t) atoi(config->GetValue(Config::TEXTURE_MANAGEMENT, Config::TILE_SIZE, Config::DEFAULT));\n if ((tile_size & (tile_size - 1)) != 0)\n {\n throw std::runtime_error(\"Tile size is not a power of 2\");\n }\n\n uint32_t count_threads = 0;\n count_threads = atoi(config->GetValue(Config::TEXTURE_MANAGEMENT, Config::RUN_IN_PARALLEL, Config::DEFAULT)) != 1 ? 1 : thread::hardware_concurrency();\n\n size_t dim_x = 0, dim_y = 0;\n\n std::ifstream input;\n input.open(config->GetValue(Config::TEXTURE_MANAGEMENT, Config::FILE_PPM, Config::DEFAULT), std::ifstream::in | std::ifstream::binary);\n read_ppm_header(input, dim_x, dim_y);\n input.close();\n\n uint32_t tree_depth = QuadTree::calculate_depth(dim_x, tile_size);\n size_t first_node_leaf = QuadTree::get_first_node_id_of_depth(tree_depth);\n size_t last_node_leaf = QuadTree::get_first_node_id_of_depth(tree_depth) + QuadTree::get_length_of_depth(tree_depth) - 1;\n\n size_t nodes_per_thread = (last_node_leaf - first_node_leaf + 1) \/ count_threads;\n\n std::vector thread_pool;\n auto *texture_lock = new std::mutex;\n\n for (uint32_t i = 0; i < count_threads; i++)\n {\n size_t node_start = first_node_leaf + i * nodes_per_thread;\n size_t node_end = (i != count_threads - 1) ? first_node_leaf + (i + 1) * nodes_per_thread : last_node_leaf;\n thread_pool.emplace_back([=]()\n { write_tile_range_at_depth((*texture_lock), tile_size, tree_depth, node_start, node_end); });\n }\n for (auto &_thread : thread_pool)\n {\n _thread.join();\n }\n\n thread_pool.clear();\n\n for (uint32_t _depth = tree_depth - 1; _depth > 0; _depth--)\n {\n first_node_leaf = QuadTree::get_first_node_id_of_depth(_depth);\n last_node_leaf = QuadTree::get_first_node_id_of_depth(_depth) + QuadTree::get_length_of_depth(_depth) - 1;\n\n nodes_per_thread = (last_node_leaf - first_node_leaf + 1) \/ count_threads;\n\n if (nodes_per_thread > 0)\n {\n for (uint32_t i = 0; i < count_threads; i++)\n {\n size_t node_start = first_node_leaf + i * nodes_per_thread;\n size_t node_end = (i != count_threads - 1) ? first_node_leaf + (i + 1) * nodes_per_thread : last_node_leaf;\n thread_pool.emplace_back([=]()\n { stitch_tile_range(tile_size, node_start, node_end); });\n }\n for (auto &_thread : thread_pool)\n {\n _thread.join();\n }\n thread_pool.clear();\n }\n else\n {\n stitch_tile_range(tile_size, first_node_leaf, last_node_leaf);\n }\n }\n\n std::list children_imgs;\n\n for (size_t i = 0; i < 4; i++)\n {\n Magick::Image _child;\n _child.read(\"id_\" + std::to_string(QuadTree::get_child_id(0, i)) + \".ppm\");\n children_imgs.push_back(_child);\n }\n\n write_stitched_tile(0, tile_size, children_imgs);\n\n const char *file_mipmap = config->GetValue(Config::TEXTURE_MANAGEMENT, Config::FILE_MIPMAP, Config::DEFAULT);\n std::ofstream output;\n output.open(file_mipmap, std::ofstream::out | std::ofstream::binary | std::ofstream::trunc);\n\n auto *buf_tile = new char[tile_size * tile_size * 3];\n\n for (uint32_t _depth = 0; _depth <= tree_depth; _depth++)\n {\n first_node_leaf = QuadTree::get_first_node_id_of_depth(_depth);\n last_node_leaf = QuadTree::get_first_node_id_of_depth(_depth) + QuadTree::get_length_of_depth(_depth) - 1;\n\n for (size_t _id = first_node_leaf; _id <= last_node_leaf; _id++)\n {\n std::ifstream input_tile;\n input_tile.open(\"id_\" + std::to_string(_id) + \".ppm\", std::ifstream::in | std::ifstream::binary);\n\n read_ppm_header(input_tile, dim_x, dim_y);\n input_tile.read(&buf_tile[0], tile_size * tile_size * 3);\n\n input_tile.close();\n\n output.write(&buf_tile[0], tile_size * tile_size * 3);\n\n if (atoi(config->GetValue(Config::DEBUG, Config::KEEP_INTERMEDIATE_DATA, Config::DEFAULT)) != 1)\n {\n std::remove((\"id_\" + std::to_string(_id) + \".ppm\").c_str());\n }\n }\n }\n\n output.close();\n\n return false;\n }\n\nprivate:\n\n void read_ppm_header(std::ifstream &_ifs, size_t &_dim_x, size_t &_dim_y) {\n auto *buf_file_version = new char[3];\n _ifs.getline(&buf_file_version[0], 3, '\\x0A');\n\n if (strcmp(buf_file_version, \"P6\") != 0)\n {\n throw std::runtime_error(\"PPM file format not equal to P6\");\n }\n\n auto *buf_dim_x = new char[8];\n auto *buf_dim_y = new char[8];\n auto *buf_color_depth = new char[8];\n\n _ifs.getline(&buf_dim_x[0], 8, '\\x20');\n _ifs.getline(&buf_dim_y[0], 8, '\\x0A');\n _ifs.getline(&buf_color_depth[0], 8, '\\x0A');\n\n _dim_x = (size_t) atol(buf_dim_x);\n _dim_y = (size_t) atol(buf_dim_y);\n auto color_depth = (short) atoi(buf_color_depth);\n\n if (color_depth != 255)\n {\n throw std::runtime_error(\"PPM color depth not equal to 255\");\n }\n\n if (_dim_x != _dim_y || (_dim_x & (_dim_x - 1)) != 0)\n {\n throw std::runtime_error(\"PPM dimensions are not equal or not a power of 2\");\n }\n }\n\n void write_tile_range_at_depth(std::mutex &_texture_lock, const size_t _tile_size, const uint32_t _depth, const size_t _node_start, const size_t _node_end) {\n std::ifstream _ifs;\n _ifs.open(config->GetValue(Config::TEXTURE_MANAGEMENT, Config::FILE_PPM, Config::DEFAULT), std::ifstream::in | std::ifstream::binary);\n\n size_t dim_x = 0, dim_y = 0;\n\n _texture_lock.lock();\n read_ppm_header(_ifs, dim_x, dim_y);\n _texture_lock.unlock();\n\n streamoff _offset_header = _ifs.tellg();\n\n auto *buf_tile = new char[_tile_size * _tile_size * 3];\n std::string buf_header = \"P6\\x0A\" + std::to_string(_tile_size) + \"\\x20\" + std::to_string(_tile_size) + \"\\x0A\" + \"255\" + \"\\x0A\";\n\n size_t _node_first = QuadTree::get_first_node_id_of_depth(_depth);\n size_t _tiles_per_row = QuadTree::get_tiles_per_row(_depth);\n\n for (size_t _id = _node_start; _id <= _node_end; _id++)\n {\n uint_fast64_t skip_cols, skip_rows;\n morton2D_64_decode((uint_fast64_t) (_id - _node_first), skip_cols, skip_rows);\n\n _texture_lock.lock();\n\n _ifs.seekg(_offset_header);\n _ifs.ignore(skip_rows * _tiles_per_row * _tile_size * _tile_size * 3);\n\n for (uint32_t _row = 0; _row < _tile_size; _row++)\n {\n _ifs.ignore(skip_cols * _tile_size * 3);\n _ifs.read(&buf_tile[_row * _tile_size * 3], _tile_size * 3);\n _ifs.ignore((_tiles_per_row - skip_cols - 1) * _tile_size * 3);\n }\n\n _texture_lock.unlock();\n\n std::ofstream output;\n output.open(\"id_\" + std::to_string(_id) + \".ppm\", std::ofstream::out | std::ofstream::binary | std::ofstream::trunc);\n output.write(&buf_header.c_str()[0], buf_header.size());\n output.write(&buf_tile[0], _tile_size * _tile_size * 3);\n output.close();\n }\n\n _ifs.close();\n }\n\n void stitch_tile_range(const size_t _tile_size, const size_t _node_start, const size_t _node_end) {\n for (size_t _id = _node_start; _id <= _node_end; _id++)\n {\n std::list children_imgs;\n\n for (size_t i = 0; i < 4; i++)\n {\n Magick::Image _child;\n _child.read(\"id_\" + std::to_string(QuadTree::get_child_id(_id, i)) + \".ppm\");\n children_imgs.push_back(_child);\n }\n\n write_stitched_tile(_id, _tile_size, children_imgs);\n }\n }\n\n void write_stitched_tile(size_t _id, size_t _tile_size, list &_child_imgs) {\n Magick::Montage montage_settings;\n montage_settings.tile(Magick::Geometry(2, 2));\n montage_settings.geometry(Magick::Geometry(_tile_size, _tile_size));\n\n std::list montage_list;\n Magick::montageImages(&montage_list, _child_imgs.begin(), _child_imgs.end(), montage_settings);\n Magick::writeImages(montage_list.begin(), montage_list.end(), \"id_\" + std::to_string(_id) + \".ppm\");\n\n Magick::Image image;\n image.read(\"id_\" + std::to_string(_id) + \".ppm\");\n Magick::Geometry geometry = image.size();\n geometry.width(_tile_size);\n geometry.height(_tile_size);\n image.scale(geometry);\n image.depth(8);\n image.write(\"id_\" + std::to_string(_id) + \".ppm\");\n }\n};<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbFuzzyDescriptorsModelManager.h\"\n#include \"itkExceptionObject.h\"\n#include \"itksys\/SystemTools.hxx\"\n#include \"tinyxml.h\"\n\nnamespace otb {\n\n\nFuzzyDescriptorsModelManager\n::FuzzyDescriptorsModelManager()\n{}\n\nFuzzyDescriptorsModelManager::PairType\nFuzzyDescriptorsModelManager\n::GetDescriptor(const char * model, const DescriptorsModelType & descModel)\n{\n PairType out;\n bool found = false;\n DescriptorsModelType::const_iterator it = descModel.begin();\n\n while( it!=descModel.end() && found == false)\n {\n if( (*it).first == model )\n {\n out = (*it);\n }\n }\n \n if( found == false )\n {\n itkGenericExceptionMacro(<<\"No models named \"< model, DescriptorsModelType &\n descModel )\n{\n PairType lPair( key, model );\n descModel.push_back(lPair);\n}\n\nvoid\nFuzzyDescriptorsModelManager\n::Print( const DescriptorsModelType & descModel )\n{\n for(unsigned int i=0; iNextSiblingElement() )\n {\n PairType currentDescriptor;\n \/\/ Store the descriptor type name\n std::string lol;\n currentDescriptor.first = currentStat->Attribute(\"name\");\n\n \/\/ The size is not stored in the XML file\n \/\/ Store the value in a std::vector, get the size and then\n \/\/ build a measurement vector\n ParameterType param;\n \n for( TiXmlElement* sample = currentStat->FirstChildElement(\"Parameter\");\n sample != NULL;\n sample = sample->NextSiblingElement() )\n {\n \/\/ Get the current value of the descriptor\n double value;\n sample->QueryDoubleAttribute(\"value\", &value);\n \/\/ Store the value\n param.push_back(value);\n }\n\n \/\/ Add descriptor parmaeters\n currentDescriptor.second = param;\n \n \/\/ Add the pai to the model\n descModel.push_back(currentDescriptor);\n }\n\n return descModel;\n}\n\n\nvoid\nFuzzyDescriptorsModelManager\n::Save(const std::string & filename, DescriptorsModelType & model )\n{\n \/\/ Check if the filename is not empty\n if( filename.empty() == true )\n {\n itkGenericExceptionMacro(<<\"The XML output FileName is empty\");\n }\n \n \/\/ Check that the right extension is given : expected .xml *\/\n if (itksys::SystemTools::GetFilenameLastExtension(filename) != \".xml\")\n {\n itkGenericExceptionMacro(<SetAttribute(\"name\", model[i].first.c_str());\n root->LinkEndChild( desc );\n\n ParameterType param = model[i].second;\n \/\/ Store the value for this statistic\n for(unsigned int cindex = 0; cindex < param.size(); ++cindex)\n {\n \/\/ For each value in Measurementvector\n TiXmlElement * curStatisticVector = new TiXmlElement(\"Parameter\");\n curStatisticVector->SetDoubleAttribute(\"value\", param[cindex]);\n desc->LinkEndChild(curStatisticVector);\n }\n }\n \n \/\/ Finally, write the file\n doc.SaveFile( filename.c_str() );\n}\n\n\n} \/\/ End namespace otb\n\nENH: add the iterator incrementation...\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbFuzzyDescriptorsModelManager.h\"\n#include \"itkExceptionObject.h\"\n#include \"itksys\/SystemTools.hxx\"\n#include \"tinyxml.h\"\n\nnamespace otb {\n\n\nFuzzyDescriptorsModelManager\n::FuzzyDescriptorsModelManager()\n{}\n\nFuzzyDescriptorsModelManager::PairType\nFuzzyDescriptorsModelManager\n::GetDescriptor(const char * model, const DescriptorsModelType & descModel)\n{\n PairType out;\n bool found = false;\n DescriptorsModelType::const_iterator it = descModel.begin();\n\n while( it!=descModel.end() && found == false)\n {\n if( (*it).first == model )\n {\n out = (*it);\n }\n ++it;\n }\n \n if( found == false )\n {\n itkGenericExceptionMacro(<<\"No models named \"< model, DescriptorsModelType &\n descModel )\n{\n PairType lPair( key, model );\n descModel.push_back(lPair);\n}\n\nvoid\nFuzzyDescriptorsModelManager\n::Print( const DescriptorsModelType & descModel )\n{\n for(unsigned int i=0; iNextSiblingElement() )\n {\n PairType currentDescriptor;\n \/\/ Store the descriptor type name\n std::string lol;\n currentDescriptor.first = currentStat->Attribute(\"name\");\n\n \/\/ The size is not stored in the XML file\n \/\/ Store the value in a std::vector, get the size and then\n \/\/ build a measurement vector\n ParameterType param;\n \n for( TiXmlElement* sample = currentStat->FirstChildElement(\"Parameter\");\n sample != NULL;\n sample = sample->NextSiblingElement() )\n {\n \/\/ Get the current value of the descriptor\n double value;\n sample->QueryDoubleAttribute(\"value\", &value);\n \/\/ Store the value\n param.push_back(value);\n }\n\n \/\/ Add descriptor parmaeters\n currentDescriptor.second = param;\n \n \/\/ Add the pai to the model\n descModel.push_back(currentDescriptor);\n }\n\n return descModel;\n}\n\n\nvoid\nFuzzyDescriptorsModelManager\n::Save(const std::string & filename, DescriptorsModelType & model )\n{\n \/\/ Check if the filename is not empty\n if( filename.empty() == true )\n {\n itkGenericExceptionMacro(<<\"The XML output FileName is empty\");\n }\n \n \/\/ Check that the right extension is given : expected .xml *\/\n if (itksys::SystemTools::GetFilenameLastExtension(filename) != \".xml\")\n {\n itkGenericExceptionMacro(<SetAttribute(\"name\", model[i].first.c_str());\n root->LinkEndChild( desc );\n\n ParameterType param = model[i].second;\n \/\/ Store the value for this statistic\n for(unsigned int cindex = 0; cindex < param.size(); ++cindex)\n {\n \/\/ For each value in Measurementvector\n TiXmlElement * curStatisticVector = new TiXmlElement(\"Parameter\");\n curStatisticVector->SetDoubleAttribute(\"value\", param[cindex]);\n desc->LinkEndChild(curStatisticVector);\n }\n }\n \n \/\/ Finally, write the file\n doc.SaveFile( filename.c_str() );\n}\n\n\n} \/\/ End namespace otb\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The LevelDB Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file. See the AUTHORS file for names of contributors.\n\n#include \"db\/version_edit.h\"\n\n#include \"db\/version_set.h\"\n#include \"util\/coding.h\"\n\nnamespace leveldb {\n\n\/\/ Tag numbers for serialized VersionEdit. These numbers are written to\n\/\/ disk and should not be changed.\nenum Tag {\n kComparator = 1,\n kLogNumber = 2,\n kNextFileNumber = 3,\n kLastSequence = 4,\n kCompactPointer = 5,\n kDeletedFile = 6,\n kNewFile = 7,\n \/\/ 8 was used for large value refs\n kPrevLogNumber = 9\n};\n\nvoid VersionEdit::Clear() {\n comparator_.clear();\n log_number_ = 0;\n prev_log_number_ = 0;\n last_sequence_ = 0;\n next_file_number_ = 0;\n has_comparator_ = false;\n has_log_number_ = false;\n has_prev_log_number_ = false;\n has_next_file_number_ = false;\n has_last_sequence_ = false;\n deleted_files_.clear();\n new_files_.clear();\n}\n\nvoid VersionEdit::EncodeTo(std::string* dst) const {\n if (has_comparator_) {\n PutVarint32(dst, kComparator);\n PutLengthPrefixedSlice(dst, comparator_);\n }\n if (has_log_number_) {\n PutVarint32(dst, kLogNumber);\n PutVarint64(dst, log_number_);\n }\n if (has_prev_log_number_) {\n PutVarint32(dst, kPrevLogNumber);\n PutVarint64(dst, prev_log_number_);\n }\n if (has_next_file_number_) {\n PutVarint32(dst, kNextFileNumber);\n PutVarint64(dst, next_file_number_);\n }\n if (has_last_sequence_) {\n PutVarint32(dst, kLastSequence);\n PutVarint64(dst, last_sequence_);\n }\n\n for (size_t i = 0; i < compact_pointers_.size(); i++) {\n PutVarint32(dst, kCompactPointer);\n PutVarint32(dst, compact_pointers_[i].first); \/\/ level\n PutLengthPrefixedSlice(dst, compact_pointers_[i].second.Encode());\n }\n\n for (DeletedFileSet::const_iterator iter = deleted_files_.begin();\n iter != deleted_files_.end();\n ++iter) {\n PutVarint32(dst, kDeletedFile);\n PutVarint32(dst, iter->first); \/\/ level\n PutVarint64(dst, iter->second); \/\/ file number\n }\n\n for (size_t i = 0; i < new_files_.size(); i++) {\n const FileMetaData& f = new_files_[i].second;\n PutVarint32(dst, kNewFile);\n PutVarint32(dst, new_files_[i].first); \/\/ level\n PutVarint64(dst, f.number);\n PutVarint64(dst, f.file_size);\n PutLengthPrefixedSlice(dst, f.smallest.Encode());\n PutLengthPrefixedSlice(dst, f.largest.Encode());\n }\n}\n\nstatic bool GetInternalKey(Slice* input, InternalKey* dst) {\n Slice str;\n if (GetLengthPrefixedSlice(input, &str)) {\n dst->DecodeFrom(str);\n return true;\n } else {\n return false;\n }\n}\n\nstatic bool GetLevel(Slice* input, int* level) {\n uint32_t v;\n if (GetVarint32(input, &v) &&\n v < config::kNumLevels) {\n *level = v;\n return true;\n } else {\n return false;\n }\n}\n\nStatus VersionEdit::DecodeFrom(const Slice& src) {\n Clear();\n Slice input = src;\n const char* msg = NULL;\n uint32_t tag;\n\n \/\/ Temporary storage for parsing\n int level;\n uint64_t number;\n FileMetaData f;\n Slice str;\n InternalKey key;\n\n while (msg == NULL && GetVarint32(&input, &tag)) {\n switch (tag) {\n case kComparator:\n if (GetLengthPrefixedSlice(&input, &str)) {\n comparator_ = str.ToString();\n has_comparator_ = true;\n } else {\n msg = \"comparator name\";\n }\n break;\n\n case kLogNumber:\n if (GetVarint64(&input, &log_number_)) {\n has_log_number_ = true;\n } else {\n msg = \"log number\";\n }\n break;\n\n case kPrevLogNumber:\n if (GetVarint64(&input, &prev_log_number_)) {\n has_prev_log_number_ = true;\n } else {\n msg = \"previous log number\";\n }\n break;\n\n case kNextFileNumber:\n if (GetVarint64(&input, &next_file_number_)) {\n has_next_file_number_ = true;\n } else {\n msg = \"next file number\";\n }\n break;\n\n case kLastSequence:\n if (GetVarint64(&input, &last_sequence_)) {\n has_last_sequence_ = true;\n } else {\n msg = \"last sequence number\";\n }\n break;\n\n case kCompactPointer:\n if (GetLevel(&input, &level) &&\n GetInternalKey(&input, &key)) {\n compact_pointers_.push_back(std::make_pair(level, key));\n } else {\n msg = \"compaction pointer\";\n }\n break;\n\n case kDeletedFile:\n if (GetLevel(&input, &level) &&\n GetVarint64(&input, &number)) {\n deleted_files_.insert(std::make_pair(level, number));\n } else {\n msg = \"deleted file\";\n }\n break;\n\n case kNewFile:\n if (GetLevel(&input, &level) &&\n GetVarint64(&input, &f.number) &&\n GetVarint64(&input, &f.file_size) &&\n GetInternalKey(&input, &f.smallest) &&\n GetInternalKey(&input, &f.largest)) {\n new_files_.push_back(std::make_pair(level, f));\n } else {\n msg = \"new-file entry\";\n }\n break;\n\n default:\n msg = \"unknown tag\";\n break;\n }\n }\n\n if (msg == NULL && !input.empty()) {\n msg = \"invalid tag\";\n }\n\n Status result;\n if (msg != NULL) {\n result = Status::Corruption(\"VersionEdit\", msg);\n }\n return result;\n}\n\nstd::string VersionEdit::DebugString() const {\n std::string r;\n r.append(\"VersionEdit {\");\n if (has_comparator_) {\n r.append(\"\\n Comparator: \");\n r.append(comparator_);\n }\n if (has_log_number_) {\n r.append(\"\\n LogNumber: \");\n AppendNumberTo(&r, log_number_);\n }\n if (has_prev_log_number_) {\n r.append(\"\\n PrevLogNumber: \");\n AppendNumberTo(&r, prev_log_number_);\n }\n if (has_next_file_number_) {\n r.append(\"\\n NextFile: \");\n AppendNumberTo(&r, next_file_number_);\n }\n if (has_last_sequence_) {\n r.append(\"\\n LastSeq: \");\n AppendNumberTo(&r, last_sequence_);\n }\n for (size_t i = 0; i < compact_pointers_.size(); i++) {\n r.append(\"\\n CompactPointer: \");\n AppendNumberTo(&r, compact_pointers_[i].first);\n r.append(\" \");\n r.append(compact_pointers_[i].second.DebugString());\n }\n for (DeletedFileSet::const_iterator iter = deleted_files_.begin();\n iter != deleted_files_.end();\n ++iter) {\n r.append(\"\\n DeleteFile: \");\n AppendNumberTo(&r, iter->first);\n r.append(\" \");\n AppendNumberTo(&r, iter->second);\n }\n for (size_t i = 0; i < new_files_.size(); i++) {\n const FileMetaData& f = new_files_[i].second;\n r.append(\"\\n AddFile: \");\n AppendNumberTo(&r, new_files_[i].first);\n r.append(\" \");\n AppendNumberTo(&r, f.number);\n r.append(\" \");\n AppendNumberTo(&r, f.file_size);\n r.append(\" \");\n r.append(f.smallest.DebugString());\n r.append(\" .. \");\n r.append(f.largest.DebugString());\n }\n r.append(\"\\n}\\n\");\n return r;\n}\n\n} \/\/ namespace leveldb\nDelete version_edit.cc<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \"Person.h\"\n#include \"string.h\"\nusing std::invalid_argument;\n\n\/\/CONSTRUCTORS\nPerson::Person()\n{\n}\n\nPerson::Person(const char* name, const char* egn, const char* address, ProfessionEnum job, double income)\n{\n\tSetName(name);\n\n\tValidateEGN(egn);\n\tthis->EGN = new char[strlen(egn) + 1];\n\tstrcpy(this->EGN, egn);\n\n\tSetAddress(address);\n\tthis->age = CalculateAge();\n\tthis->sex = GetSexFromEGN();\n\tSetJob(job);\n\tSetIncome(income);\n}\n\nPerson::Person(const Person& otherPerson)\n{\n\tthis->name = new char[strlen(otherPerson.name) + 1];\n\tstrcpy(this->name, otherPerson.name);\n\n\tthis->EGN = new char[strlen(otherPerson.EGN) + 1];\n\tstrcpy(this->EGN, otherPerson.EGN);\n\n\tthis->address = new char[strlen(otherPerson.address) + 1];\n\tstrcpy(this->address, otherPerson.address);\n\n\tthis->age = otherPerson.age;\n\tthis->sex = otherPerson.sex;\n\tthis->job = otherPerson.job;\n\tthis->income = otherPerson.income;\n}\n\nPerson& Person::operator = (const Person& otherPerson)\n{\n\tthis->name = new char[strlen(otherPerson.name) + 1];\n\tstrcpy(this->name, otherPerson.name);\n\n\tthis->EGN = new char[strlen(otherPerson.EGN) + 1];\n\tstrcpy(this->EGN, otherPerson.EGN);\n\n\tthis->address = new char[strlen(otherPerson.address) + 1];\n\tstrcpy(this->address, otherPerson.address);\n\n\tthis->age = otherPerson.age;\n\tthis->sex = otherPerson.sex;\n\tthis->job = otherPerson.job;\n\tthis->income = otherPerson.income;\n\n\treturn *this;\n}\n\nPerson::~Person()\n{\n\tdelete[] name;\n\tdelete[] EGN;\n\tdelete[] address;\n}\n\n\/\/Private Methods\nunsigned short Person::CalculateAge() const\n{\n\tunsigned short currentYear = 113;\n\tunsigned short yearBorn = (short)(EGN[0] - '0') * 10 + (short)(EGN[1] - '0');\n\n\treturn currentYear - yearBorn;\n}\n\nSexEnum Person::GetSexFromEGN() const\n{\n\tint digitPosShowingSex = 8;\n\tint sexDigit = (int)(EGN[digitPosShowingSex] - '0');\n\tSexEnum sex = Female;\n\n\tif (sexDigit % 2 == 0)\n\t{\n\t\tsex = Male;\n\t}\n\n\treturn sex;\n}\n\nvoid Person::ValidateEGN(const char* egn) const\n{\n\tif (!egn)\n\t{\n\t\tthrow std::invalid_argument(\"EGN must not be null!\");\n\t}\n\n\tunsigned short egnLenght = strlen(egn);\n\tif (egnLenght != 10)\n\t{\n\t\tthrow std::length_error(\"ENG must be 10 digits long!!!\");\n\t}\n\n\tfor (int index = 0; index < egnLenght; index++)\n\t{\n\t\tif (egn[index] - '0' < 0 || egn[index] - '0' > 9)\n\t\t{\n\t\t\tthrow invalid_argument(\"EGN must be consisted entirely by numbers!!!\");\n\t\t}\n\t}\n}\n\n\/\/Public Methods\nchar* Person::JobAsString() const\n{\n\tswitch (job)\n\t{\n\tcase Baker:\n\t\treturn \"Baker\";\n\tcase Teacher:\n\t\treturn \"Teacher\";\n\tcase Janitor:\n\t\treturn \"Janitor\";\n\tcase Gamer:\n\t\treturn \"Gamer\";\n\tcase Journalist:\n\t\treturn \"Journalist\";\n\tcase SoftwareDev:\n\t\treturn \"SoftwareDev\";\n\tcase Unemployed:\n\t\treturn \"Unemployed\";\n\tdefault:\n\t\treturn \"Unemployed\";\n\t}\n}\n\nvoid Person::Information(std::ostream& output = std::cout) const\n{\n\toutput << \"Name: \"<< this->GetName() \n\t\t<<\"\\nEGN: \"<< this->GetEGN() \n\t\t<<\"\\nAddress: \"<< this->GetAddress() \n\t\t<<\"\\nAge: \"<< this->GetAge() \n\t\t<<\"\\nSex: \"<< (this->GetSexType() == 0 ? \"Male\" : \"Female\")\n\t\t<<\"\\nJob: \"<< this->JobAsString()\n\t\t<<\"\\nIncome: \"<< this->GetIncome() \n\t\t<< std::endl;\n}\n\n\/\/Getter and setter for name\nchar* Person::GetName() const\n{\n\treturn this->name;\n}\n\nvoid Person::SetName(const char* name)\n{\n\tif (!name)\n\t{\n\t\tthrow invalid_argument(\"Name can't be null!\");\n\t}\n\n\tthis->name = new char[strlen(name) + 1];\n\tstrcpy(this->name, name);\n}\n\n\/\/Getter for EGN\nchar* Person::GetEGN() const\n{\n\treturn this->EGN;\n}\n\n\/\/Getter and setter for address\nchar* Person::GetAddress() const\n{\n\treturn this->address;\n}\n\nvoid Person::SetAddress(const char* address)\n{\n\tif (!address)\n\t{\n\t\tthrow invalid_argument(\"Address can't be null!\");\n\t}\n\n\tthis->address = new char[strlen(address) + 1];\n\tstrcpy(this->address, address);\n}\n\n\/\/Getter for age\nunsigned short Person::GetAge() const\n{\n\treturn this->age;\n}\n\n\/\/Getter for sex\nSexEnum Person::GetSexType() const\n{\n\treturn this->sex;\n}\n\n\/\/Getter and setter for job\nProfessionEnum Person::GetJob() const\n{\n\treturn this->job;\n}\n\nvoid Person::SetJob(ProfessionEnum job)\n{\n\tthis->job = job;\n}\n\n\/\/Getter and setter for income\ndouble Person::GetIncome() const\n{\n\treturn this->income;\n}\n\nvoid Person::SetIncome(double income)\n{\n\tif (income < 0)\n\t{\n\t\tthrow std::range_error(\"Income must not be negative!\");\n\t}\n\telse\n\t{\n\t\tthis->income = income;\n\t}\n}\n\nstd::ostream& operator <<(std::ostream& output, const Person& person)\n{\n\tperson.Information(output);\n\n\treturn output;\n}\nupdate#include \n#include \n#include \n#include \n#include \"Person.h\"\n#include \"string.h\"\nusing std::invalid_argument;\n\n\/\/CONSTRUCTORS\nPerson::Person()\n{\n}\n\nPerson::Person(const char* name, const char* egn, const char* address, ProfessionEnum job, double income)\n{\n\tSetName(name);\n\n\tValidateEGN(egn);\n\tthis->EGN = new char[strlen(egn) + 1];\n\tstrcpy(this->EGN, egn);\n\n\tSetAddress(address);\n\tthis->age = CalculateAge();\n\tthis->sex = GetSexFromEGN();\n\tSetJob(job);\n\tSetIncome(income);\n}\n\nPerson::Person(const Person& otherPerson)\n{\n\tthis->name = new char[strlen(otherPerson.name) + 1];\n\tstrcpy(this->name, otherPerson.name);\n\n\tthis->EGN = new char[strlen(otherPerson.EGN) + 1];\n\tstrcpy(this->EGN, otherPerson.EGN);\n\n\tthis->address = new char[strlen(otherPerson.address) + 1];\n\tstrcpy(this->address, otherPerson.address);\n\n\tthis->age = otherPerson.age;\n\tthis->sex = otherPerson.sex;\n\tthis->job = otherPerson.job;\n\tthis->income = otherPerson.income;\n}\n\nPerson& Person::operator = (const Person& otherPerson)\n{\n\tif (this != &otherPerson)\n\t{\n\t\tdelete[] name;\n\t\tdelete[] EGN;\n\t\tdelete[] address;\n\n\t\tthis->name = new char[strlen(otherPerson.name) + 1];\n\t\tstrcpy(this->name, otherPerson.name);\n\n\t\tthis->EGN = new char[strlen(otherPerson.EGN) + 1];\n\t\tstrcpy(this->EGN, otherPerson.EGN);\n\n\t\tthis->address = new char[strlen(otherPerson.address) + 1];\n\t\tstrcpy(this->address, otherPerson.address);\n\n\t\tthis->age = otherPerson.age;\n\t\tthis->sex = otherPerson.sex;\n\t\tthis->job = otherPerson.job;\n\t\tthis->income = otherPerson.income;\n\t}\n\n\treturn *this;\n}\n\nPerson::~Person()\n{\n\tdelete[] name;\n\tdelete[] EGN;\n\tdelete[] address;\n}\n\n\/\/Private Methods\nunsigned short Person::CalculateAge() const\n{\n\tunsigned short currentYear = 113;\n\tunsigned short yearBorn = (short)(EGN[0] - '0') * 10 + (short)(EGN[1] - '0');\n\n\treturn currentYear - yearBorn;\n}\n\nSexEnum Person::GetSexFromEGN() const\n{\n\tint digitPosShowingSex = 8;\n\tint sexDigit = (int)(EGN[digitPosShowingSex] - '0');\n\tSexEnum sex = Female;\n\n\tif (sexDigit % 2 == 0)\n\t{\n\t\tsex = Male;\n\t}\n\n\treturn sex;\n}\n\nvoid Person::ValidateEGN(const char* egn) const\n{\n\tif (!egn)\n\t{\n\t\tthrow std::invalid_argument(\"EGN must not be null!\");\n\t}\n\n\tunsigned short egnLenght = strlen(egn);\n\tif (egnLenght != 10)\n\t{\n\t\tthrow std::length_error(\"ENG must be 10 digits long!!!\");\n\t}\n\n\tfor (int index = 0; index < egnLenght; index++)\n\t{\n\t\tif (egn[index] - '0' < 0 || egn[index] - '0' > 9)\n\t\t{\n\t\t\tthrow invalid_argument(\"EGN must be consisted entirely by numbers!!!\");\n\t\t}\n\t}\n}\n\n\/\/Public Methods\nchar* Person::JobAsString() const\n{\n\tswitch (job)\n\t{\n\tcase Baker:\n\t\treturn \"Baker\";\n\tcase Teacher:\n\t\treturn \"Teacher\";\n\tcase Janitor:\n\t\treturn \"Janitor\";\n\tcase Gamer:\n\t\treturn \"Gamer\";\n\tcase Journalist:\n\t\treturn \"Journalist\";\n\tcase SoftwareDev:\n\t\treturn \"SoftwareDev\";\n\tcase Unemployed:\n\t\treturn \"Unemployed\";\n\tdefault:\n\t\treturn \"Unemployed\";\n\t}\n}\n\nvoid Person::Information(std::ostream& output = std::cout) const\n{\n\toutput << \"Name: \"<< this->GetName() \n\t\t<<\"\\nEGN: \"<< this->GetEGN() \n\t\t<<\"\\nAddress: \"<< this->GetAddress() \n\t\t<<\"\\nAge: \"<< this->GetAge() \n\t\t<<\"\\nSex: \"<< (this->GetSexType() == 0 ? \"Male\" : \"Female\")\n\t\t<<\"\\nJob: \"<< this->JobAsString()\n\t\t<<\"\\nIncome: \"<< this->GetIncome() \n\t\t<< std::endl;\n}\n\n\/\/Getter and setter for name\nchar* Person::GetName() const\n{\n\treturn this->name;\n}\n\nvoid Person::SetName(const char* name)\n{\n\tif (!name)\n\t{\n\t\tthrow invalid_argument(\"Name can't be null!\");\n\t}\n\n\tthis->name = new char[strlen(name) + 1];\n\tstrcpy(this->name, name);\n}\n\n\/\/Getter for EGN\nchar* Person::GetEGN() const\n{\n\treturn this->EGN;\n}\n\n\/\/Getter and setter for address\nchar* Person::GetAddress() const\n{\n\treturn this->address;\n}\n\nvoid Person::SetAddress(const char* address)\n{\n\tif (!address)\n\t{\n\t\tthrow invalid_argument(\"Address can't be null!\");\n\t}\n\n\tthis->address = new char[strlen(address) + 1];\n\tstrcpy(this->address, address);\n}\n\n\/\/Getter for age\nunsigned short Person::GetAge() const\n{\n\treturn this->age;\n}\n\n\/\/Getter for sex\nSexEnum Person::GetSexType() const\n{\n\treturn this->sex;\n}\n\n\/\/Getter and setter for job\nProfessionEnum Person::GetJob() const\n{\n\treturn this->job;\n}\n\nvoid Person::SetJob(ProfessionEnum job)\n{\n\tthis->job = job;\n}\n\n\/\/Getter and setter for income\ndouble Person::GetIncome() const\n{\n\treturn this->income;\n}\n\nvoid Person::SetIncome(double income)\n{\n\tif (income < 0)\n\t{\n\t\tthrow std::range_error(\"Income must not be negative!\");\n\t}\n\telse\n\t{\n\t\tthis->income = income;\n\t}\n}\n\nstd::ostream& operator <<(std::ostream& output, const Person& person)\n{\n\tperson.Information(output);\n\n\treturn output;\n}\n<|endoftext|>"} {"text":"\/\/Copyright (c) 2020 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"ExtruderTrain.h\"\n#include \"FffGcodeWriter.h\"\n#include \"InsetOrderOptimizer.h\"\n#include \"LayerPlan.h\"\n#include \"utils\/logoutput.h\"\n#include \"WallToolPaths.h\"\n\nnamespace cura\n{\n\nInsetOrderOptimizer::InsetOrderOptimizer(const FffGcodeWriter& gcode_writer, const SliceDataStorage& storage, LayerPlan& gcode_layer, const SliceMeshStorage& mesh, const int extruder_nr, const PathConfigStorage::MeshPathConfigs& mesh_config, const VariableWidthPaths& paths, unsigned int layer_nr) :\n gcode_writer(gcode_writer),\n storage(storage),\n gcode_layer(gcode_layer),\n mesh(mesh),\n extruder_nr(extruder_nr),\n mesh_config(mesh_config),\n paths(paths),\n layer_nr(layer_nr),\n z_seam_config(mesh.settings.get(\"z_seam_type\"), mesh.getZSeamHint(), mesh.settings.get(\"z_seam_corner\")),\n added_something(false),\n retraction_region_calculated(false)\n{\n}\n\nbool InsetOrderOptimizer::optimize(const WallType& wall_type)\n{\n \/\/ Settings & configs:\n const GCodePathConfig& skin_or_infill_config = wall_type == WallType::EXTRA_SKIN ? mesh_config.skin_config : mesh_config.infill_config[0];\n const bool do_outer_wall = wall_type == WallType::OUTER_WALL;\n const GCodePathConfig& inset_0_non_bridge_config = do_outer_wall ? mesh_config.inset0_config : skin_or_infill_config;\n const GCodePathConfig& inset_X_non_bridge_config = do_outer_wall ? mesh_config.insetX_config : skin_or_infill_config;\n const GCodePathConfig& inset_0_bridge_config = do_outer_wall ? mesh_config.bridge_inset0_config : skin_or_infill_config;\n const GCodePathConfig& inset_X_bridge_config = do_outer_wall ? mesh_config.bridge_insetX_config : skin_or_infill_config;\n\n const size_t wall_0_extruder_nr = mesh.settings.get(\"wall_0_extruder_nr\").extruder_nr;\n const size_t wall_x_extruder_nr = mesh.settings.get(\"wall_x_extruder_nr\").extruder_nr;\n const size_t top_bottom_extruder_nr = mesh.settings.get(\"top_bottom_extruder_nr\").extruder_nr;\n const size_t infill_extruder_nr = mesh.settings.get(\"infill_extruder_nr\").extruder_nr;\n\n const bool ignore_inner_insets = !mesh.settings.get(\"optimize_wall_printing_order\");\n \/\/ If the outer wall extruder is different than the inner wall extruder, don't apply the outer_inset_first to the skin\n \/\/ and infill insets.\n const bool outer_inset_first = wall_0_extruder_nr == wall_x_extruder_nr && mesh.settings.get(\"outer_inset_first\");\n\n \/\/Bin the insets in order to print the inset indices together, and to optimize the order of each bin to reduce travels.\n std::set bins_with_index_zero_insets;\n BinJunctions insets = variableWidthPathToBinJunctions(paths, ignore_inner_insets, outer_inset_first, &bins_with_index_zero_insets);\n\n size_t start_inset;\n size_t end_inset;\n int direction;\n if((wall_type == WallType::OUTER_WALL && wall_0_extruder_nr == wall_x_extruder_nr && wall_x_extruder_nr == extruder_nr) ||\n (wall_type == WallType::EXTRA_SKIN && extruder_nr == top_bottom_extruder_nr) ||\n (wall_type == WallType::EXTRA_INFILL && extruder_nr == infill_extruder_nr))\n {\n \/\/If printing the outer inset first, start with the lowest inset.\n \/\/Otherwise start with the highest inset and iterate backwards.\n if(outer_inset_first)\n {\n start_inset = 0;\n end_inset = insets.size();\n direction = 1;\n }\n else\n {\n start_inset = insets.size() - 1;\n end_inset = -1;\n direction = -1;\n }\n }\n else if(wall_type == WallType::OUTER_WALL && wall_0_extruder_nr != wall_x_extruder_nr)\n {\n \/\/If the wall_0 and wall_x extruders are different, then only include the insets that should be printed by the\n \/\/current extruder_nr.\n if(extruder_nr == wall_0_extruder_nr)\n {\n start_inset = 0;\n end_inset = 1; \/\/ Ignore inner walls\n direction = 1;\n }\n else if(extruder_nr == wall_x_extruder_nr)\n {\n start_inset = insets.size() - 1;\n end_inset = 0; \/\/ Ignore outer wall\n direction = -1;\n }\n else\n {\n return added_something;\n }\n }\n else\n {\n return added_something;\n }\n\n\n \/\/Add all of the insets one by one.\n constexpr Ratio flow = 1.0_r;\n const bool retract_before_outer_wall = mesh.settings.get(\"travel_retract_before_outer_wall\");\n const coord_t wall_0_wipe_dist = mesh.settings.get(\"wall_0_wipe_dist\");\n for(size_t inset = start_inset; inset != end_inset; inset += direction)\n {\n if(insets[inset].empty())\n {\n continue; \/\/Don't switch extruders either, etc.\n }\n added_something = true;\n gcode_writer.setExtruder_addPrime(storage, gcode_layer, extruder_nr);\n gcode_layer.setIsInside(true); \/\/Going to print walls, which are always inside.\n ZSeamConfig z_seam_config(mesh.settings.get(\"z_seam_type\"), mesh.getZSeamHint(), mesh.settings.get(\"z_seam_corner\"));\n\n if(bins_with_index_zero_insets.count(inset) > 0) \/\/Print using outer wall config.\n {\n gcode_layer.addWalls(insets[inset], mesh, inset_0_non_bridge_config, inset_0_bridge_config, z_seam_config, wall_0_wipe_dist, flow, retract_before_outer_wall);\n }\n else\n {\n gcode_layer.addWalls(insets[inset], mesh, inset_X_non_bridge_config, inset_X_bridge_config, z_seam_config, 0, flow, false);\n }\n }\n return added_something;\n}\n\nsize_t InsetOrderOptimizer::getOuterRegionId(const VariableWidthPaths& toolpaths, size_t& out_number_of_regions)\n{\n \/\/ Polygons show up here one by one, so there are always only a) the outer lines and b) the lines that are part of the holes.\n \/\/ Therefore, the outer-regions' lines will always have the region-id that is larger then all of the other ones.\n\n \/\/ First, build the bounding boxes:\n std::map region_ids_to_bboxes;\n for (const VariableWidthLines& path : toolpaths)\n {\n for (const ExtrusionLine& line : path)\n {\n if (region_ids_to_bboxes.count(line.region_id) == 0)\n {\n region_ids_to_bboxes[line.region_id] = AABB();\n }\n AABB& aabb = region_ids_to_bboxes[line.region_id];\n for (const auto& junction : line.junctions)\n {\n aabb.include(junction.p);\n }\n }\n }\n\n \/\/ Then, the largest of these will be the one that's needed for the outer region, the others' all belong to hole regions:\n AABB outer_bbox;\n size_t outer_region_id = 0; \/\/ Region-ID 0 is reserved for 'None'.\n for (const auto& region_id_bbox_pair : region_ids_to_bboxes)\n {\n if (region_id_bbox_pair.second.contains(outer_bbox))\n {\n outer_bbox = region_id_bbox_pair.second;\n outer_region_id = region_id_bbox_pair.first;\n }\n }\n\n out_number_of_regions = region_ids_to_bboxes.size();\n return outer_region_id;\n}\n\nBinJunctions InsetOrderOptimizer::variableWidthPathToBinJunctions(const VariableWidthPaths& toolpaths, const bool& ignore_inner_inset_order, const bool& pack_regions_by_inset, std::set* p_bins_with_index_zero_insets)\n{\n \/\/ Find the largest inset-index:\n size_t max_inset_index = 0;\n for (const VariableWidthLines& path : toolpaths)\n {\n max_inset_index = std::max(path.front().inset_idx, max_inset_index);\n }\n\n \/\/ Find which regions are associated with the outer-outer walls (which region is the one the rest is holes inside of):\n size_t number_of_regions = 0;\n const size_t outer_region_id = getOuterRegionId(toolpaths, number_of_regions);\n\n \/\/ Since we're (optionally!) splitting off in the outer and inner regions, it may need twice as many bins as inset-indices.\n const size_t max_bin = ignore_inner_inset_order ? (number_of_regions * 2) + 2 : (max_inset_index + 1) * 2;\n BinJunctions insets(max_bin + 1);\n for (const VariableWidthLines& path : toolpaths)\n {\n if (path.empty()) \/\/ Don't bother printing these.\n {\n continue;\n }\n const size_t inset_index = path.front().inset_idx;\n\n \/\/ Convert list of extrusion lines to vectors of extrusion junctions, and add those to the binned insets.\n for (const ExtrusionLine& line : path)\n {\n \/\/ Sort into the right bin, ...\n size_t bin_index;\n const bool in_hole_region = line.region_id != outer_region_id && line.region_id != 0;\n if(ignore_inner_inset_order)\n {\n bin_index = std::min(inset_index, static_cast(1)) + 2 * (in_hole_region ? line.region_id : 0);\n }\n else\n {\n if (pack_regions_by_inset) \/\/ <- inset-0 region-A, inset-0 B, inset-1 A, inset-1 B, inset-2 A, inset-2 B, ..., etc.\n {\n bin_index = (inset_index * 2) + (in_hole_region ? 1 : 0);\n }\n else \/\/ <- inset-0 region-A, inset-1 A, inset-2 A, ..., inset-0 B, inset-1 B, inset-2 B, ..., etc.\n {\n bin_index = inset_index + (in_hole_region ? (max_inset_index + 1) : 0);\n }\n }\n insets[bin_index].emplace_back(line.junctions.begin(), line.junctions.end());\n\n \/\/ Collect all bins that have zero-inset indices in them, if needed:\n if (inset_index == 0 && p_bins_with_index_zero_insets != nullptr)\n {\n p_bins_with_index_zero_insets->insert(bin_index);\n }\n }\n }\n return insets;\n}\n\n}\/\/namespace cura\nDocument the major if-else cases\/\/Copyright (c) 2020 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"ExtruderTrain.h\"\n#include \"FffGcodeWriter.h\"\n#include \"InsetOrderOptimizer.h\"\n#include \"LayerPlan.h\"\n#include \"utils\/logoutput.h\"\n#include \"WallToolPaths.h\"\n\nnamespace cura\n{\n\nInsetOrderOptimizer::InsetOrderOptimizer(const FffGcodeWriter& gcode_writer, const SliceDataStorage& storage, LayerPlan& gcode_layer, const SliceMeshStorage& mesh, const int extruder_nr, const PathConfigStorage::MeshPathConfigs& mesh_config, const VariableWidthPaths& paths, unsigned int layer_nr) :\n gcode_writer(gcode_writer),\n storage(storage),\n gcode_layer(gcode_layer),\n mesh(mesh),\n extruder_nr(extruder_nr),\n mesh_config(mesh_config),\n paths(paths),\n layer_nr(layer_nr),\n z_seam_config(mesh.settings.get(\"z_seam_type\"), mesh.getZSeamHint(), mesh.settings.get(\"z_seam_corner\")),\n added_something(false),\n retraction_region_calculated(false)\n{\n}\n\nbool InsetOrderOptimizer::optimize(const WallType& wall_type)\n{\n \/\/ Settings & configs:\n const GCodePathConfig& skin_or_infill_config = wall_type == WallType::EXTRA_SKIN ? mesh_config.skin_config : mesh_config.infill_config[0];\n const bool do_outer_wall = wall_type == WallType::OUTER_WALL;\n const GCodePathConfig& inset_0_non_bridge_config = do_outer_wall ? mesh_config.inset0_config : skin_or_infill_config;\n const GCodePathConfig& inset_X_non_bridge_config = do_outer_wall ? mesh_config.insetX_config : skin_or_infill_config;\n const GCodePathConfig& inset_0_bridge_config = do_outer_wall ? mesh_config.bridge_inset0_config : skin_or_infill_config;\n const GCodePathConfig& inset_X_bridge_config = do_outer_wall ? mesh_config.bridge_insetX_config : skin_or_infill_config;\n\n const size_t wall_0_extruder_nr = mesh.settings.get(\"wall_0_extruder_nr\").extruder_nr;\n const size_t wall_x_extruder_nr = mesh.settings.get(\"wall_x_extruder_nr\").extruder_nr;\n const size_t top_bottom_extruder_nr = mesh.settings.get(\"top_bottom_extruder_nr\").extruder_nr;\n const size_t infill_extruder_nr = mesh.settings.get(\"infill_extruder_nr\").extruder_nr;\n\n const bool ignore_inner_insets = !mesh.settings.get(\"optimize_wall_printing_order\");\n \/\/ If the outer wall extruder is different than the inner wall extruder, don't apply the outer_inset_first to the skin\n \/\/ and infill insets.\n const bool outer_inset_first = wall_0_extruder_nr == wall_x_extruder_nr && mesh.settings.get(\"outer_inset_first\");\n\n \/\/Bin the insets in order to print the inset indices together, and to optimize the order of each bin to reduce travels.\n std::set bins_with_index_zero_insets;\n BinJunctions insets = variableWidthPathToBinJunctions(paths, ignore_inner_insets, outer_inset_first, &bins_with_index_zero_insets);\n\n size_t start_inset;\n size_t end_inset;\n int direction;\n \/\/If the entire wall is printed with the current extruder, print all of it.\n if((wall_type == WallType::OUTER_WALL && wall_0_extruder_nr == wall_x_extruder_nr && wall_x_extruder_nr == extruder_nr) ||\n (wall_type == WallType::EXTRA_SKIN && extruder_nr == top_bottom_extruder_nr) ||\n (wall_type == WallType::EXTRA_INFILL && extruder_nr == infill_extruder_nr))\n {\n \/\/If printing the outer inset first, start with the lowest inset.\n \/\/Otherwise start with the highest inset and iterate backwards.\n if(outer_inset_first)\n {\n start_inset = 0;\n end_inset = insets.size();\n direction = 1;\n }\n else\n {\n start_inset = insets.size() - 1;\n end_inset = -1;\n direction = -1;\n }\n }\n \/\/If the wall is partially printed with the current extruder, print the correct part.\n else if(wall_type == WallType::OUTER_WALL && wall_0_extruder_nr != wall_x_extruder_nr)\n {\n \/\/If the wall_0 and wall_x extruders are different, then only include the insets that should be printed by the\n \/\/current extruder_nr.\n if(extruder_nr == wall_0_extruder_nr)\n {\n start_inset = 0;\n end_inset = 1; \/\/ Ignore inner walls\n direction = 1;\n }\n else if(extruder_nr == wall_x_extruder_nr)\n {\n start_inset = insets.size() - 1;\n end_inset = 0; \/\/ Ignore outer wall\n direction = -1;\n }\n else\n {\n return added_something;\n }\n }\n else \/\/The wall is not printed with this extruder, not even in part. Don't print anything then.\n {\n return added_something;\n }\n\n\n \/\/Add all of the insets one by one.\n constexpr Ratio flow = 1.0_r;\n const bool retract_before_outer_wall = mesh.settings.get(\"travel_retract_before_outer_wall\");\n const coord_t wall_0_wipe_dist = mesh.settings.get(\"wall_0_wipe_dist\");\n for(size_t inset = start_inset; inset != end_inset; inset += direction)\n {\n if(insets[inset].empty())\n {\n continue; \/\/Don't switch extruders either, etc.\n }\n added_something = true;\n gcode_writer.setExtruder_addPrime(storage, gcode_layer, extruder_nr);\n gcode_layer.setIsInside(true); \/\/Going to print walls, which are always inside.\n ZSeamConfig z_seam_config(mesh.settings.get(\"z_seam_type\"), mesh.getZSeamHint(), mesh.settings.get(\"z_seam_corner\"));\n\n if(bins_with_index_zero_insets.count(inset) > 0) \/\/Print using outer wall config.\n {\n gcode_layer.addWalls(insets[inset], mesh, inset_0_non_bridge_config, inset_0_bridge_config, z_seam_config, wall_0_wipe_dist, flow, retract_before_outer_wall);\n }\n else\n {\n gcode_layer.addWalls(insets[inset], mesh, inset_X_non_bridge_config, inset_X_bridge_config, z_seam_config, 0, flow, false);\n }\n }\n return added_something;\n}\n\nsize_t InsetOrderOptimizer::getOuterRegionId(const VariableWidthPaths& toolpaths, size_t& out_number_of_regions)\n{\n \/\/ Polygons show up here one by one, so there are always only a) the outer lines and b) the lines that are part of the holes.\n \/\/ Therefore, the outer-regions' lines will always have the region-id that is larger then all of the other ones.\n\n \/\/ First, build the bounding boxes:\n std::map region_ids_to_bboxes;\n for (const VariableWidthLines& path : toolpaths)\n {\n for (const ExtrusionLine& line : path)\n {\n if (region_ids_to_bboxes.count(line.region_id) == 0)\n {\n region_ids_to_bboxes[line.region_id] = AABB();\n }\n AABB& aabb = region_ids_to_bboxes[line.region_id];\n for (const auto& junction : line.junctions)\n {\n aabb.include(junction.p);\n }\n }\n }\n\n \/\/ Then, the largest of these will be the one that's needed for the outer region, the others' all belong to hole regions:\n AABB outer_bbox;\n size_t outer_region_id = 0; \/\/ Region-ID 0 is reserved for 'None'.\n for (const auto& region_id_bbox_pair : region_ids_to_bboxes)\n {\n if (region_id_bbox_pair.second.contains(outer_bbox))\n {\n outer_bbox = region_id_bbox_pair.second;\n outer_region_id = region_id_bbox_pair.first;\n }\n }\n\n out_number_of_regions = region_ids_to_bboxes.size();\n return outer_region_id;\n}\n\nBinJunctions InsetOrderOptimizer::variableWidthPathToBinJunctions(const VariableWidthPaths& toolpaths, const bool& ignore_inner_inset_order, const bool& pack_regions_by_inset, std::set* p_bins_with_index_zero_insets)\n{\n \/\/ Find the largest inset-index:\n size_t max_inset_index = 0;\n for (const VariableWidthLines& path : toolpaths)\n {\n max_inset_index = std::max(path.front().inset_idx, max_inset_index);\n }\n\n \/\/ Find which regions are associated with the outer-outer walls (which region is the one the rest is holes inside of):\n size_t number_of_regions = 0;\n const size_t outer_region_id = getOuterRegionId(toolpaths, number_of_regions);\n\n \/\/ Since we're (optionally!) splitting off in the outer and inner regions, it may need twice as many bins as inset-indices.\n const size_t max_bin = ignore_inner_inset_order ? (number_of_regions * 2) + 2 : (max_inset_index + 1) * 2;\n BinJunctions insets(max_bin + 1);\n for (const VariableWidthLines& path : toolpaths)\n {\n if (path.empty()) \/\/ Don't bother printing these.\n {\n continue;\n }\n const size_t inset_index = path.front().inset_idx;\n\n \/\/ Convert list of extrusion lines to vectors of extrusion junctions, and add those to the binned insets.\n for (const ExtrusionLine& line : path)\n {\n \/\/ Sort into the right bin, ...\n size_t bin_index;\n const bool in_hole_region = line.region_id != outer_region_id && line.region_id != 0;\n if(ignore_inner_inset_order)\n {\n bin_index = std::min(inset_index, static_cast(1)) + 2 * (in_hole_region ? line.region_id : 0);\n }\n else\n {\n if (pack_regions_by_inset) \/\/ <- inset-0 region-A, inset-0 B, inset-1 A, inset-1 B, inset-2 A, inset-2 B, ..., etc.\n {\n bin_index = (inset_index * 2) + (in_hole_region ? 1 : 0);\n }\n else \/\/ <- inset-0 region-A, inset-1 A, inset-2 A, ..., inset-0 B, inset-1 B, inset-2 B, ..., etc.\n {\n bin_index = inset_index + (in_hole_region ? (max_inset_index + 1) : 0);\n }\n }\n insets[bin_index].emplace_back(line.junctions.begin(), line.junctions.end());\n\n \/\/ Collect all bins that have zero-inset indices in them, if needed:\n if (inset_index == 0 && p_bins_with_index_zero_insets != nullptr)\n {\n p_bins_with_index_zero_insets->insert(bin_index);\n }\n }\n }\n return insets;\n}\n\n}\/\/namespace cura\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2005 by Andrew Mann\n Based in part on work by Norman Kraemer\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"iutil\/comp.h\"\n#include \"isndsys\/ss_stream.h\"\n#include \"oggdata2.h\"\n#include \"oggstream2.h\"\n\n#include \"ivaria\/reporter.h\"\n\n\/* Keep these as integer values or the stream may feed portions of a sample to \n * the higher layer which may cause problems\n * 1 , 1 will decode 1\/1 or 1 second of audio in advance *\/\n#define OGG_BUFFER_LENGTH_MULTIPLIER 1\n#define OGG_BUFFER_LENGTH_DIVISOR 5\n\n\/**\n * The size in bytes of the buffer in which decoded ogg data is stored before \n * copying\/conversion\n *\/\n#define OGG_DECODE_BUFFER_SIZE 4096\n\nextern cs_ov_callbacks *GetCallbacks();\n\nSndSysOggSoundStream::SndSysOggSoundStream (csRef pData, \n\t\t\t\t\t OggDataStore *pDataStore, csSndSysSoundFormat *pRenderFormat, \n int Mode3D) :\n SndSysBasicStream(pRenderFormat, Mode3D)\n{\n \/\/ Initialize the stream data\n m_StreamData.datastore=pDataStore;\n m_StreamData.position=0;\n\n m_pSoundData=pData;\n\n \/\/ Allocate an advance buffer\n m_pCyclicBuffer = new SoundCyclicBuffer (\n (m_RenderFormat.Bits\/8 * m_RenderFormat.Channels) * \n (m_RenderFormat.Freq * OGG_BUFFER_LENGTH_MULTIPLIER \/ \n\tOGG_BUFFER_LENGTH_DIVISOR));\n CS_ASSERT(m_pCyclicBuffer!=0);\n\n \/\/ Initialize ogg file\n memset(&m_VorbisFile,0,sizeof(OggVorbis_File));\n ov_open_callbacks (&m_StreamData,&m_VorbisFile,0,0,\n *(ov_callbacks*)GetCallbacks());\n\n \/\/ Set to not a valid stream\n m_CurrentOggStream=-1;\n}\n\nSndSysOggSoundStream::~SndSysOggSoundStream ()\n{\n}\n\nconst char *SndSysOggSoundStream::GetDescription()\n{\n \/\/ Try to retrieve the description from the underlying data component.\n const char *pDesc=m_pSoundData->GetDescription();\n\n \/\/ If the data component has no description, return a default description.\n if (!pDesc)\n return \"Ogg Stream\";\n return pDesc;\n}\n\nsize_t SndSysOggSoundStream::GetFrameCount()\n{\n const csSndSysSoundFormat *data_format=m_pSoundData->GetFormat();\n\n uint64 framecount=m_pSoundData->GetFrameCount();\n framecount*=m_RenderFormat.Freq;\n framecount\/=data_format->Freq;\n\n return framecount;\n}\n\nvoid SndSysOggSoundStream::AdvancePosition(size_t frame_delta)\n{\n size_t needed_bytes=0;\n \/\/if loop is enabled, end loop frame is different than zero and we are at the loop ending return to the\n \/\/start of the loop\n if(m_bLooping && m_endLoopFrame != 0 && m_MostAdvancedReadPointer+frame_delta >= m_endLoopFrame)\n {\n \/\/first advance the decoding of the exact bound we need to reach the endloopframe\n AdvancePosition(m_endLoopFrame-m_MostAdvancedReadPointer-1);\n \/\/remove from frame_delta what we decoded already\n frame_delta -= m_endLoopFrame-m_MostAdvancedReadPointer-1;\n \/\/ Flush the prepared samples\n m_PreparedDataBufferUsage=0;\n m_PreparedDataBufferStart=0;\n\n \/\/ Seek the ogg stream to the start loop position position for the rest of the advancement\n ov_raw_seek(&m_VorbisFile,m_startLoopFrame);\n }\n\n if (m_NewPosition != InvalidPosition)\n {\n \/\/ Signal a full cyclic buffer flush\n needed_bytes=m_pCyclicBuffer->GetLength();\n\n \/\/ Flush the prepared samples too\n m_PreparedDataBufferUsage=0;\n m_PreparedDataBufferStart=0;\n\n \/\/ Seek the ogg stream to the requested position\n ov_raw_seek(&m_VorbisFile,m_NewPosition);\n\n m_NewPosition = InvalidPosition;\n m_bPlaybackReadComplete=false;\n }\n if (m_bPaused || m_bPlaybackReadComplete || frame_delta==0)\n return;\n\n \n long bytes_read=0;\n \n\n \/\/ Figure out how many bytes we need to fill for this advancement\n if (needed_bytes==0)\n needed_bytes=frame_delta * (m_RenderFormat.Bits\/8) * m_RenderFormat.Channels ;\n\n \/* If we need more space than is available in the whole cyclic buffer, \n * then we already underbuffered, reduce to just 1 cycle full\n *\/\n if ((size_t)needed_bytes > m_pCyclicBuffer->GetLength())\n needed_bytes=(long)(m_pCyclicBuffer->GetLength() & 0x7FFFFFFF);\n\n \/\/ Free space in the cyclic buffer if necessary\n if (needed_bytes > m_pCyclicBuffer->GetFreeBytes())\n m_pCyclicBuffer->AdvanceStartValue (needed_bytes - \n m_pCyclicBuffer->GetFreeBytes());\n\n \/\/ Fill in leftover decoded data if needed\n if (m_PreparedDataBufferUsage > 0)\n needed_bytes -= CopyBufferBytes (needed_bytes);\n\n while (needed_bytes > 0)\n {\n int last_ogg_stream=m_CurrentOggStream;\n char ogg_decode_buffer[OGG_DECODE_BUFFER_SIZE];\n\n bytes_read=0;\n\n while (bytes_read==0)\n {\n bytes_read = ov_read (&m_VorbisFile, ogg_decode_buffer,\n OGG_DECODE_BUFFER_SIZE, OGG_ENDIAN,\n (m_RenderFormat.Bits==8)?1:2, (m_RenderFormat.Bits==8)?0:1,\n &m_CurrentOggStream);\n \n \/\/ Assert on error\n CS_ASSERT(bytes_read >=0);\n\n if (bytes_read <= 0)\n {\n if (!m_bLooping)\n {\n \/\/ Seek back to the beginning for a restart. Pause on the next call\n m_bPlaybackReadComplete=true;\n ov_raw_seek(&m_VorbisFile,0);\n return;\n }\n\n \/\/ Loop by resetting the position to the start loop position and continuing\n ov_raw_seek(&m_VorbisFile,m_startLoopFrame);\n }\n }\n\n\n \n\n \/\/ If streams changed, the format may have changed as well\n if ((m_NewOutputFrequency != m_OutputFrequency) \n || (last_ogg_stream != m_CurrentOggStream))\n {\n int needed_buffer,source_sample_size;\n\n m_OutputFrequency=m_NewOutputFrequency;\n\n m_pCurrentOggFormatInfo=ov_info(&m_VorbisFile,m_CurrentOggStream);\n\n \/\/ Create the pcm sample converter if it's not yet created\n if (m_pPCMConverter == 0)\n m_pPCMConverter = new PCMSampleConverter (\n m_pCurrentOggFormatInfo->channels, m_RenderFormat.Bits,\n m_pCurrentOggFormatInfo->rate);\n\n \/\/ Calculate the size of one source sample\n source_sample_size=m_pCurrentOggFormatInfo->channels * m_RenderFormat.Bits;\n\n \/\/ Calculate the needed buffer size for this conversion\n needed_buffer = (m_pPCMConverter->GetRequiredOutputBufferMultiple (\n m_RenderFormat.Channels,m_RenderFormat.Bits,m_OutputFrequency) * \n (OGG_DECODE_BUFFER_SIZE + source_sample_size))\/1024;\n\n \/\/ Allocate a new buffer if needed - this will only happen if the source rate changes\n if (m_PreparedDataBufferSize < needed_buffer)\n {\n delete[] m_pPreparedDataBuffer;\n m_pPreparedDataBuffer = new char[needed_buffer];\n m_PreparedDataBufferSize=needed_buffer;\n }\n }\n\n \/\/ If no conversion is necessary \n if ((m_pCurrentOggFormatInfo->rate == m_OutputFrequency) &&\n (m_pCurrentOggFormatInfo->channels == m_RenderFormat.Channels))\n {\n CS_ASSERT(bytes_read <= m_PreparedDataBufferSize);\n memcpy(m_pPreparedDataBuffer,ogg_decode_buffer,bytes_read);\n m_PreparedDataBufferUsage=bytes_read;\n }\n else\n {\n m_PreparedDataBufferUsage = m_pPCMConverter->ConvertBuffer (ogg_decode_buffer,\n bytes_read, m_pPreparedDataBuffer, m_RenderFormat.Channels,\n m_RenderFormat.Bits,m_OutputFrequency);\n }\n\n if (m_PreparedDataBufferUsage > 0)\n needed_bytes -= CopyBufferBytes (needed_bytes);\n\n }\n \n}\n\nwhen setting a position with setpos the cs api states that frames are used, same goes for the loop positions, but ov_raw_seek doesn't respect this: \"Seeks to the offset specified (in compressed raw bytes) within the physical bitstream.\" while we want to seek to a frame so we need ov_pcm_seek which has predictable positions: \"Seeks to the offset specified (in pcm samples) within the physical bitstream.\"\/*\n Copyright (C) 2005 by Andrew Mann\n Based in part on work by Norman Kraemer\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"iutil\/comp.h\"\n#include \"isndsys\/ss_stream.h\"\n#include \"oggdata2.h\"\n#include \"oggstream2.h\"\n\n#include \"ivaria\/reporter.h\"\n\n\/* Keep these as integer values or the stream may feed portions of a sample to \n * the higher layer which may cause problems\n * 1 , 1 will decode 1\/1 or 1 second of audio in advance *\/\n#define OGG_BUFFER_LENGTH_MULTIPLIER 1\n#define OGG_BUFFER_LENGTH_DIVISOR 5\n\n\/**\n * The size in bytes of the buffer in which decoded ogg data is stored before \n * copying\/conversion\n *\/\n#define OGG_DECODE_BUFFER_SIZE 4096\n\nextern cs_ov_callbacks *GetCallbacks();\n\nSndSysOggSoundStream::SndSysOggSoundStream (csRef pData, \n\t\t\t\t\t OggDataStore *pDataStore, csSndSysSoundFormat *pRenderFormat, \n int Mode3D) :\n SndSysBasicStream(pRenderFormat, Mode3D)\n{\n \/\/ Initialize the stream data\n m_StreamData.datastore=pDataStore;\n m_StreamData.position=0;\n\n m_pSoundData=pData;\n\n \/\/ Allocate an advance buffer\n m_pCyclicBuffer = new SoundCyclicBuffer (\n (m_RenderFormat.Bits\/8 * m_RenderFormat.Channels) * \n (m_RenderFormat.Freq * OGG_BUFFER_LENGTH_MULTIPLIER \/ \n\tOGG_BUFFER_LENGTH_DIVISOR));\n CS_ASSERT(m_pCyclicBuffer!=0);\n\n \/\/ Initialize ogg file\n memset(&m_VorbisFile,0,sizeof(OggVorbis_File));\n ov_open_callbacks (&m_StreamData,&m_VorbisFile,0,0,\n *(ov_callbacks*)GetCallbacks());\n\n \/\/ Set to not a valid stream\n m_CurrentOggStream=-1;\n}\n\nSndSysOggSoundStream::~SndSysOggSoundStream ()\n{\n}\n\nconst char *SndSysOggSoundStream::GetDescription()\n{\n \/\/ Try to retrieve the description from the underlying data component.\n const char *pDesc=m_pSoundData->GetDescription();\n\n \/\/ If the data component has no description, return a default description.\n if (!pDesc)\n return \"Ogg Stream\";\n return pDesc;\n}\n\nsize_t SndSysOggSoundStream::GetFrameCount()\n{\n const csSndSysSoundFormat *data_format=m_pSoundData->GetFormat();\n\n uint64 framecount=m_pSoundData->GetFrameCount();\n framecount*=m_RenderFormat.Freq;\n framecount\/=data_format->Freq;\n\n return framecount;\n}\n\nvoid SndSysOggSoundStream::AdvancePosition(size_t frame_delta)\n{\n size_t needed_bytes=0;\n \/\/if loop is enabled, end loop frame is different than zero and we are at the loop ending return to the\n \/\/start of the loop\n if(m_bLooping && m_endLoopFrame != 0 && m_MostAdvancedReadPointer+frame_delta >= m_endLoopFrame)\n {\n \/\/first advance the decoding of the exact bound we need to reach the endloopframe\n AdvancePosition(m_endLoopFrame-m_MostAdvancedReadPointer-1);\n \/\/remove from frame_delta what we decoded already\n frame_delta -= m_endLoopFrame-m_MostAdvancedReadPointer-1;\n \/\/ Flush the prepared samples\n m_PreparedDataBufferUsage=0;\n m_PreparedDataBufferStart=0;\n\n \/\/ Seek the ogg stream to the start loop position position for the rest of the advancement\n ov_pcm_seek(&m_VorbisFile,m_startLoopFrame);\n }\n\n if (m_NewPosition != InvalidPosition)\n {\n \/\/ Signal a full cyclic buffer flush\n needed_bytes=m_pCyclicBuffer->GetLength();\n\n \/\/ Flush the prepared samples too\n m_PreparedDataBufferUsage=0;\n m_PreparedDataBufferStart=0;\n\n \/\/ Seek the ogg stream to the requested position\n ov_pcm_seek(&m_VorbisFile,m_NewPosition);\n\n m_NewPosition = InvalidPosition;\n m_bPlaybackReadComplete=false;\n }\n if (m_bPaused || m_bPlaybackReadComplete || frame_delta==0)\n return;\n\n \n long bytes_read=0;\n \n\n \/\/ Figure out how many bytes we need to fill for this advancement\n if (needed_bytes==0)\n needed_bytes=frame_delta * (m_RenderFormat.Bits\/8) * m_RenderFormat.Channels ;\n\n \/* If we need more space than is available in the whole cyclic buffer, \n * then we already underbuffered, reduce to just 1 cycle full\n *\/\n if ((size_t)needed_bytes > m_pCyclicBuffer->GetLength())\n needed_bytes=(long)(m_pCyclicBuffer->GetLength() & 0x7FFFFFFF);\n\n \/\/ Free space in the cyclic buffer if necessary\n if (needed_bytes > m_pCyclicBuffer->GetFreeBytes())\n m_pCyclicBuffer->AdvanceStartValue (needed_bytes - \n m_pCyclicBuffer->GetFreeBytes());\n\n \/\/ Fill in leftover decoded data if needed\n if (m_PreparedDataBufferUsage > 0)\n needed_bytes -= CopyBufferBytes (needed_bytes);\n\n while (needed_bytes > 0)\n {\n int last_ogg_stream=m_CurrentOggStream;\n char ogg_decode_buffer[OGG_DECODE_BUFFER_SIZE];\n\n bytes_read=0;\n\n while (bytes_read==0)\n {\n bytes_read = ov_read (&m_VorbisFile, ogg_decode_buffer,\n OGG_DECODE_BUFFER_SIZE, OGG_ENDIAN,\n (m_RenderFormat.Bits==8)?1:2, (m_RenderFormat.Bits==8)?0:1,\n &m_CurrentOggStream);\n \n \/\/ Assert on error\n CS_ASSERT(bytes_read >=0);\n\n if (bytes_read <= 0)\n {\n if (!m_bLooping)\n {\n \/\/ Seek back to the beginning for a restart. Pause on the next call\n m_bPlaybackReadComplete=true;\n ov_raw_seek(&m_VorbisFile,0);\n return;\n }\n\n \/\/ Loop by resetting the position to the start loop position and continuing\n ov_pcm_seek(&m_VorbisFile,m_startLoopFrame);\n }\n }\n\n\n \n\n \/\/ If streams changed, the format may have changed as well\n if ((m_NewOutputFrequency != m_OutputFrequency) \n || (last_ogg_stream != m_CurrentOggStream))\n {\n int needed_buffer,source_sample_size;\n\n m_OutputFrequency=m_NewOutputFrequency;\n\n m_pCurrentOggFormatInfo=ov_info(&m_VorbisFile,m_CurrentOggStream);\n\n \/\/ Create the pcm sample converter if it's not yet created\n if (m_pPCMConverter == 0)\n m_pPCMConverter = new PCMSampleConverter (\n m_pCurrentOggFormatInfo->channels, m_RenderFormat.Bits,\n m_pCurrentOggFormatInfo->rate);\n\n \/\/ Calculate the size of one source sample\n source_sample_size=m_pCurrentOggFormatInfo->channels * m_RenderFormat.Bits;\n\n \/\/ Calculate the needed buffer size for this conversion\n needed_buffer = (m_pPCMConverter->GetRequiredOutputBufferMultiple (\n m_RenderFormat.Channels,m_RenderFormat.Bits,m_OutputFrequency) * \n (OGG_DECODE_BUFFER_SIZE + source_sample_size))\/1024;\n\n \/\/ Allocate a new buffer if needed - this will only happen if the source rate changes\n if (m_PreparedDataBufferSize < needed_buffer)\n {\n delete[] m_pPreparedDataBuffer;\n m_pPreparedDataBuffer = new char[needed_buffer];\n m_PreparedDataBufferSize=needed_buffer;\n }\n }\n\n \/\/ If no conversion is necessary \n if ((m_pCurrentOggFormatInfo->rate == m_OutputFrequency) &&\n (m_pCurrentOggFormatInfo->channels == m_RenderFormat.Channels))\n {\n CS_ASSERT(bytes_read <= m_PreparedDataBufferSize);\n memcpy(m_pPreparedDataBuffer,ogg_decode_buffer,bytes_read);\n m_PreparedDataBufferUsage=bytes_read;\n }\n else\n {\n m_PreparedDataBufferUsage = m_pPCMConverter->ConvertBuffer (ogg_decode_buffer,\n bytes_read, m_pPreparedDataBuffer, m_RenderFormat.Channels,\n m_RenderFormat.Bits,m_OutputFrequency);\n }\n\n if (m_PreparedDataBufferUsage > 0)\n needed_bytes -= CopyBufferBytes (needed_bytes);\n\n }\n \n}\n\n<|endoftext|>"} {"text":"\/*=========================================================================\n\nProgram: NeuroLib (DTI command line tools)\nLanguage: C++\nDate: $Date: 2009\/08\/03 17:36:42 $\nVersion: $Revision: 1.8 $\nAuthor: Casey Goodlett (gcasey@sci.utah.edu)\n\nCopyright (c) Casey Goodlett. All rights reserved.\nSee NeuroLibCopyright.txt or http:\/\/www.ia.unc.edu\/dev\/Copyright.htm for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\/\/ STL includes\n#include \n#include \n#include \n\n\/\/ ITK includes\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/#include \"FiberCalculator.h\"\n#include \"deformationfieldoperations.h\"\n#include \"fiberio.h\"\n#include \"dtitypes.h\"\n#include \"fiberprocessCLP.h\"\n\nint main(int argc, char* argv[])\n{\n PARSE_ARGS;\n\n if(fiberFile == \"\")\n {\n std::cerr << \"A fiber file has to be specified\" << std::endl;\n return EXIT_FAILURE;\n }\n const bool VERBOSE = verbose;\n \n \/\/ Reader fiber bundle\n GroupType::Pointer group = readFiberFile(fiberFile);\n \n DeformationImageType::Pointer deformationfield(NULL);\n if(hField != \"\")\n deformationfield = readDeformationField(hField, HField);\n else if(displacementField != \"\")\n deformationfield = readDeformationField(displacementField, Displacement);\n else\n deformationfield = NULL;\n \n typedef itk::VectorLinearInterpolateImageFunction DeformationInterpolateType;\n DeformationInterpolateType::Pointer definterp(NULL);\n if(deformationfield)\n {\n definterp = DeformationInterpolateType::New();\n definterp->SetInputImage(deformationfield);\n } else {\n noWarp = true;\n }\n \n \/\/ Setup new fiber bundle group\n GroupType::Pointer newgroup = GroupType::New();\n newgroup->SetId(0);\n \n ChildrenListType* children = group->GetChildren(0);\n \n if(VERBOSE)\n std::cout << \"Getting spacing\" << std::endl;\n \n \/\/ Get Spacing and offset from group\n double spacing[3];\n if( noWarp )\n {\n newgroup->SetObjectToWorldTransform( group->GetObjectToWorldTransform() ) ;\n newgroup->ComputeObjectToParentTransform() ;\n for(unsigned int i =0; i < 3; i++)\n {\n spacing[i] = (group->GetSpacing())[i];\n }\n }\n else\n {\n spacing[0] = spacing[1] = spacing[2] = 1; \n }\n newgroup->SetSpacing(spacing);\n \n itk::Vector sooffset;\n for(unsigned int i = 0; i < 3; i++)\n sooffset[i] = (group->GetObjectToParentTransform()->GetOffset())[i];\n \n if(VERBOSE)\n {\n std::cout << \"Group Spacing: \" << spacing[0] << \", \" << spacing[1] << \", \" << spacing[2] << std::endl;\n std::cout << \"Group Offset: \" << sooffset[0] << \", \" << sooffset[1] << \", \" << sooffset[2] << std::endl;\n std::cout << \"deformationfield: '\" << deformationfield << \"'\" << std::endl; \n }\n \n \/\/ Setup tensor file if available\n typedef itk::ImageFileReader TensorImageReader;\n typedef itk::TensorLinearInterpolateImageFunction TensorInterpolateType;\n TensorImageReader::Pointer tensorreader = NULL;\n TensorInterpolateType::Pointer tensorinterp = NULL;\n \n if(tensorVolume != \"\")\n {\n tensorreader = TensorImageReader::New();\n tensorinterp = TensorInterpolateType::New();\n \n tensorreader->SetFileName(tensorVolume);\n try\n {\n tensorreader->Update();\n tensorinterp->SetInputImage(tensorreader->GetOutput());\n }\n catch(itk::ExceptionObject exp)\n {\n std::cerr << exp << std::endl;\n return EXIT_FAILURE;\n }\n }\n \n if(VERBOSE)\n std::cout << \"Starting Loop\" << std::endl;\n \n ChildrenListType::iterator it;\n unsigned int id = 1;\n \n \/\/ Need to allocate an image to write into for creating\n \/\/ the fiber label map\n IntImageType::Pointer labelimage;\n if(voxelize != \"\")\n {\n if(tensorVolume == \"\")\n {\n std::cerr << \"Must specify tensor file to copy image metadata for fiber voxelize.\" << std::endl;\n return EXIT_FAILURE;\n }\n \/\/tensorreader->GetOutput();\n labelimage = IntImageType::New();\n labelimage->SetSpacing(tensorreader->GetOutput()->GetSpacing());\n labelimage->SetOrigin(tensorreader->GetOutput()->GetOrigin());\n labelimage->SetDirection(tensorreader->GetOutput()->GetDirection());\n labelimage->SetRegions(tensorreader->GetOutput()->GetLargestPossibleRegion());\n labelimage->Allocate();\n labelimage->FillBuffer(0);\n }\n \n \/\/ For each fiber\n for(it = children->begin(); it != children->end(); it++)\n {\n DTIPointListType pointlist = dynamic_cast((*it).GetPointer())->GetPoints();\n DTITubeType::Pointer newtube = DTITubeType::New();\n DTIPointListType newpoints;\n \n DTIPointListType::iterator pit;\n \n typedef DeformationInterpolateType::ContinuousIndexType ContinuousIndexType;\n ContinuousIndexType tensor_ci, def_ci ;\n \/\/ For each point along the fiber\n\/\/std::cout<<\"plop\"<GetPosition();\n DTITubeType::TransformPointer transform = ((*it).GetPointer())->GetObjectToWorldTransform() ;\n const PointType p_world_orig = transform->TransformPoint( p ) ;\n\/\/ std::cout< pt_trans = p_world_orig ;\n if(deformationfield)\n {\n deformationfield->TransformPhysicalPointToContinuousIndex(p_world_orig, def_ci);\n\n if( !deformationfield->GetLargestPossibleRegion().IsInside( def_ci ) )\n {\n std::cerr << \"Fiber is outside deformation field image. Deformation field has to be in the fiber space. Warning: Original position will be used\" << std::endl ;\n }\n else\n {\n DeformationPixelType warp(definterp->EvaluateAtContinuousIndex(def_ci).GetDataPointer());\n for( int i = 0 ; i < 3 ; i++ )\n {\n pt_trans[ i ] += warp[ i ] ;\n }\n\/\/ deformationfield->TransformContinuousIndexToPhysicalPoint( def_ci , pt_trans ) ;\n\/\/ std::cout<

ind;\n labelimage->TransformPhysicalPointToContinuousIndex(pt_trans, cind);\n ind[0] = static_cast(vnl_math_rnd_halfinttoeven(cind[0]));\n ind[1] = static_cast(vnl_math_rnd_halfinttoeven(cind[1]));\n ind[2] = static_cast(vnl_math_rnd_halfinttoeven(cind[2]));\n\t\n if(!labelimage->GetLargestPossibleRegion().IsInside(ind))\n {\n std::cerr << \"Error index: \" << ind << \" not in image\" << std::endl;\n std::cout << \"Ignoring\" << std::endl;\n \/\/return EXIT_FAILURE;\n\t}\n if(voxelizeCountFibers)\n {\n labelimage->SetPixel(ind, labelimage->GetPixel(ind) + 1);\n\t}\n else\n {\n labelimage->SetPixel(ind, voxelLabel);\n\t}\n }\n \n \n DTIPointType newpoint;\n if(noDataChange==true)\n\tnewpoint = *pit;\n \/\/ Should not have to do this\n if(noWarp)\n {\n\/\/ std::cout<<\"no warp\"<GetOutput()->TransformPhysicalPointToContinuousIndex(pt_trans, tensor_ci);\n\titk::DiffusionTensor3D tensor(tensorinterp->EvaluateAtContinuousIndex(tensor_ci).GetDataPointer());\n\t\n\t\/\/ TODO: Change SpatialObject interface to accept DiffusionTensor3D\n\tfloat sotensor[6];\n\tfor(unsigned int i = 0; i < 6; ++i)\n\t sotensor[i] = tensor[i];\n\t\n\ttypedef itk::DiffusionTensor3D::EigenValuesArrayType EigenValuesType;\n\tEigenValuesType eigenvalues;\n\ttensor.ComputeEigenValues(eigenvalues);\n \n\tnewpoint.SetRadius(0.5);\n\tnewpoint.SetTensorMatrix(sotensor);\n\tnewpoint.AddField(itk::DTITubeSpatialObjectPoint<3>::FA, tensor.GetFractionalAnisotropy());\n\tnewpoint.AddField(\"md\", tensor.GetTrace()\/3);\n\tnewpoint.AddField(\"fro\", sqrt(tensor[0]*tensor[0] +\n\t\t\t\t 2*tensor[1]*tensor[1] +\n\t\t\t\t 2*tensor[2]*tensor[2] +\n\t\t\t\t tensor[3]*tensor[3] +\n\t\t\t\t 2*tensor[4]*tensor[4] +\n\t\t\t\t tensor[5]*tensor[5]));\n\tnewpoint.AddField(\"l1\", eigenvalues[2]);\n\tnewpoint.AddField(\"l2\", eigenvalues[1]);\n\tnewpoint.AddField(\"l3\", eigenvalues[0]);\n }\n \n newpoints.push_back(newpoint);\n } \n newtube->SetSpacing(spacing);\n newtube->SetId(id++);\n newtube->SetPoints(newpoints);\n newgroup->AddSpatialObject(newtube);\n }\n\/\/ std::cout<<\"plop2\"< LabelWriter;\n LabelWriter::Pointer writer = LabelWriter::New();\n writer->SetInput(labelimage);\n writer->SetFileName(voxelize);\n writer->UseCompressionOn();\n try\n {\n writer->Update();\n }\n catch(itk::ExceptionObject & e)\n {\n std::cerr << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n delete children;\n return EXIT_SUCCESS;\n}\nBUG: fix processing with verbose mode ON when no deformation field is used\/*=========================================================================\n\nProgram: NeuroLib (DTI command line tools)\nLanguage: C++\nDate: $Date: 2009\/08\/03 17:36:42 $\nVersion: $Revision: 1.8 $\nAuthor: Casey Goodlett (gcasey@sci.utah.edu)\n\nCopyright (c) Casey Goodlett. All rights reserved.\nSee NeuroLibCopyright.txt or http:\/\/www.ia.unc.edu\/dev\/Copyright.htm for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\/\/ STL includes\n#include \n#include \n#include \n\n\/\/ ITK includes\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/#include \"FiberCalculator.h\"\n#include \"deformationfieldoperations.h\"\n#include \"fiberio.h\"\n#include \"dtitypes.h\"\n#include \"fiberprocessCLP.h\"\n\nint main(int argc, char* argv[])\n{\n PARSE_ARGS;\n\n if(fiberFile == \"\")\n {\n std::cerr << \"A fiber file has to be specified\" << std::endl;\n return EXIT_FAILURE;\n }\n const bool VERBOSE = verbose;\n \n \/\/ Reader fiber bundle\n GroupType::Pointer group = readFiberFile(fiberFile);\n \n DeformationImageType::Pointer deformationfield(NULL);\n if(hField != \"\")\n deformationfield = readDeformationField(hField, HField);\n else if(displacementField != \"\")\n deformationfield = readDeformationField(displacementField, Displacement);\n else\n deformationfield = NULL;\n \n typedef itk::VectorLinearInterpolateImageFunction DeformationInterpolateType;\n DeformationInterpolateType::Pointer definterp(NULL);\n if(deformationfield)\n {\n definterp = DeformationInterpolateType::New();\n definterp->SetInputImage(deformationfield);\n } else {\n noWarp = true;\n }\n \n \/\/ Setup new fiber bundle group\n GroupType::Pointer newgroup = GroupType::New();\n newgroup->SetId(0);\n \n ChildrenListType* children = group->GetChildren(0);\n \n if(VERBOSE)\n std::cout << \"Getting spacing\" << std::endl;\n \n \/\/ Get Spacing and offset from group\n double spacing[3];\n if( noWarp )\n {\n newgroup->SetObjectToWorldTransform( group->GetObjectToWorldTransform() ) ;\n newgroup->ComputeObjectToParentTransform() ;\n for(unsigned int i =0; i < 3; i++)\n {\n spacing[i] = (group->GetSpacing())[i];\n }\n }\n else\n {\n spacing[0] = spacing[1] = spacing[2] = 1; \n }\n newgroup->SetSpacing(spacing);\n \n itk::Vector sooffset;\n for(unsigned int i = 0; i < 3; i++)\n sooffset[i] = (group->GetObjectToParentTransform()->GetOffset())[i];\n \n if(VERBOSE)\n {\n std::cout << \"Group Spacing: \" << spacing[0] << \", \" << spacing[1] << \", \" << spacing[2] << std::endl;\n std::cout << \"Group Offset: \" << sooffset[0] << \", \" << sooffset[1] << \", \" << sooffset[2] << std::endl;\n if (deformationfield)\n std::cout << \"deformationfield: '\" << deformationfield << \"'\" << std::endl; \n }\n \n \/\/ Setup tensor file if available\n typedef itk::ImageFileReader TensorImageReader;\n typedef itk::TensorLinearInterpolateImageFunction TensorInterpolateType;\n TensorImageReader::Pointer tensorreader = NULL;\n TensorInterpolateType::Pointer tensorinterp = NULL;\n \n if(tensorVolume != \"\")\n {\n tensorreader = TensorImageReader::New();\n tensorinterp = TensorInterpolateType::New();\n \n tensorreader->SetFileName(tensorVolume);\n try\n {\n tensorreader->Update();\n tensorinterp->SetInputImage(tensorreader->GetOutput());\n }\n catch(itk::ExceptionObject exp)\n {\n std::cerr << exp << std::endl;\n return EXIT_FAILURE;\n }\n }\n \n if(VERBOSE)\n std::cout << \"Starting Loop\" << std::endl;\n \n ChildrenListType::iterator it;\n unsigned int id = 1;\n \n \/\/ Need to allocate an image to write into for creating\n \/\/ the fiber label map\n IntImageType::Pointer labelimage;\n if(voxelize != \"\")\n {\n if(tensorVolume == \"\")\n {\n std::cerr << \"Must specify tensor file to copy image metadata for fiber voxelize.\" << std::endl;\n return EXIT_FAILURE;\n }\n \/\/tensorreader->GetOutput();\n labelimage = IntImageType::New();\n labelimage->SetSpacing(tensorreader->GetOutput()->GetSpacing());\n labelimage->SetOrigin(tensorreader->GetOutput()->GetOrigin());\n labelimage->SetDirection(tensorreader->GetOutput()->GetDirection());\n labelimage->SetRegions(tensorreader->GetOutput()->GetLargestPossibleRegion());\n labelimage->Allocate();\n labelimage->FillBuffer(0);\n }\n \n \/\/ For each fiber\n for(it = children->begin(); it != children->end(); it++)\n {\n DTIPointListType pointlist = dynamic_cast((*it).GetPointer())->GetPoints();\n DTITubeType::Pointer newtube = DTITubeType::New();\n DTIPointListType newpoints;\n \n DTIPointListType::iterator pit;\n \n typedef DeformationInterpolateType::ContinuousIndexType ContinuousIndexType;\n ContinuousIndexType tensor_ci, def_ci ;\n \/\/ For each point along the fiber\n\/\/std::cout<<\"plop\"<GetPosition();\n DTITubeType::TransformPointer transform = ((*it).GetPointer())->GetObjectToWorldTransform() ;\n const PointType p_world_orig = transform->TransformPoint( p ) ;\n\/\/ std::cout< pt_trans = p_world_orig ;\n if(deformationfield)\n {\n deformationfield->TransformPhysicalPointToContinuousIndex(p_world_orig, def_ci);\n\n if( !deformationfield->GetLargestPossibleRegion().IsInside( def_ci ) )\n {\n std::cerr << \"Fiber is outside deformation field image. Deformation field has to be in the fiber space. Warning: Original position will be used\" << std::endl ;\n }\n else\n {\n DeformationPixelType warp(definterp->EvaluateAtContinuousIndex(def_ci).GetDataPointer());\n for( int i = 0 ; i < 3 ; i++ )\n {\n pt_trans[ i ] += warp[ i ] ;\n }\n\/\/ deformationfield->TransformContinuousIndexToPhysicalPoint( def_ci , pt_trans ) ;\n\/\/ std::cout<

ind;\n labelimage->TransformPhysicalPointToContinuousIndex(pt_trans, cind);\n ind[0] = static_cast(vnl_math_rnd_halfinttoeven(cind[0]));\n ind[1] = static_cast(vnl_math_rnd_halfinttoeven(cind[1]));\n ind[2] = static_cast(vnl_math_rnd_halfinttoeven(cind[2]));\n\t\n if(!labelimage->GetLargestPossibleRegion().IsInside(ind))\n {\n std::cerr << \"Error index: \" << ind << \" not in image\" << std::endl;\n std::cout << \"Ignoring\" << std::endl;\n \/\/return EXIT_FAILURE;\n\t}\n if(voxelizeCountFibers)\n {\n labelimage->SetPixel(ind, labelimage->GetPixel(ind) + 1);\n\t}\n else\n {\n labelimage->SetPixel(ind, voxelLabel);\n\t}\n }\n \n \n DTIPointType newpoint;\n if(noDataChange==true)\n\tnewpoint = *pit;\n \/\/ Should not have to do this\n if(noWarp)\n {\n\/\/ std::cout<<\"no warp\"<GetOutput()->TransformPhysicalPointToContinuousIndex(pt_trans, tensor_ci);\n\titk::DiffusionTensor3D tensor(tensorinterp->EvaluateAtContinuousIndex(tensor_ci).GetDataPointer());\n\t\n\t\/\/ TODO: Change SpatialObject interface to accept DiffusionTensor3D\n\tfloat sotensor[6];\n\tfor(unsigned int i = 0; i < 6; ++i)\n\t sotensor[i] = tensor[i];\n\t\n\ttypedef itk::DiffusionTensor3D::EigenValuesArrayType EigenValuesType;\n\tEigenValuesType eigenvalues;\n\ttensor.ComputeEigenValues(eigenvalues);\n \n\tnewpoint.SetRadius(0.5);\n\tnewpoint.SetTensorMatrix(sotensor);\n\tnewpoint.AddField(itk::DTITubeSpatialObjectPoint<3>::FA, tensor.GetFractionalAnisotropy());\n\tnewpoint.AddField(\"md\", tensor.GetTrace()\/3);\n\tnewpoint.AddField(\"fro\", sqrt(tensor[0]*tensor[0] +\n\t\t\t\t 2*tensor[1]*tensor[1] +\n\t\t\t\t 2*tensor[2]*tensor[2] +\n\t\t\t\t tensor[3]*tensor[3] +\n\t\t\t\t 2*tensor[4]*tensor[4] +\n\t\t\t\t tensor[5]*tensor[5]));\n\tnewpoint.AddField(\"l1\", eigenvalues[2]);\n\tnewpoint.AddField(\"l2\", eigenvalues[1]);\n\tnewpoint.AddField(\"l3\", eigenvalues[0]);\n }\n \n newpoints.push_back(newpoint);\n } \n newtube->SetSpacing(spacing);\n newtube->SetId(id++);\n newtube->SetPoints(newpoints);\n newgroup->AddSpatialObject(newtube);\n }\n\/\/ std::cout<<\"plop2\"< LabelWriter;\n LabelWriter::Pointer writer = LabelWriter::New();\n writer->SetInput(labelimage);\n writer->SetFileName(voxelize);\n writer->UseCompressionOn();\n try\n {\n writer->Update();\n }\n catch(itk::ExceptionObject & e)\n {\n std::cerr << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n delete children;\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \"cmm_internal_listener.h\"\n#include \"debug.h\"\n\n#define INTERNAL_LISTEN_PORT 42424\n\nListenerThread::ListenerThread(CMMSocketImpl *sk_)\n : sk(sk_)\n{\n struct sockaddr_in bind_addr;\n memset(&bind_addr, 0, sizeof(bind_addr));\n bind_addr.sin_addr.s_addr = INADDR_ANY;\n bind_addr.sin_port = htons(INTERNAL_LISTEN_PORT);\n \n listener_sock = socket(PF_INET, SOCK_STREAM, 0);\n if (listener_sock < 0) {\n throw -1;\n }\n\n int on = 1;\n int rc = setsockopt(listener_sock, SOL_SOCKET, SO_REUSEADDR,\n (char *) &on, sizeof(on));\n if (rc < 0) {\n dbgprintf(\"Cannot reuse socket address\");\n }\n \n rc = bind(listener_sock, \n (struct sockaddr *)&bind_addr, sizeof(bind_addr));\n if (rc < 0) {\n close(listener_sock);\n throw rc;\n }\n socklen_t addrlen = sizeof(bind_addr);\n rc = getsockname(listener_sock, \n (struct sockaddr *)&bind_addr, &addrlen);\n if (rc < 0) {\n perror(\"getsockname\");\n close(listener_sock);\n throw rc;\n }\n listen_port = bind_addr.sin_port;\n rc = listen(listener_sock, 5);\n if (rc < 0) {\n close(listener_sock);\n throw rc;\n }\n dbgprintf(\"Internal socket listener listening up on port %d\\n\",\n ntohs(listen_port));\n}\n\nListenerThread::~ListenerThread()\n{\n close(listener_sock);\n}\n\nin_port_t\nListenerThread::port() const\n{\n return listen_port;\n}\n\nvoid\nListenerThread::Run()\n{\n while (1) {\n fd_set readfds;\n FD_ZERO(&readfds);\n FD_SET(listener_sock, &readfds);\n int rc = select(listener_sock + 1, &readfds, NULL, NULL, NULL);\n\n struct sockaddr_in remote_addr;\n socklen_t addrlen = sizeof(remote_addr);\n int sock = accept(listener_sock,\n (struct sockaddr *)&remote_addr, &addrlen);\n if (sock < 0) {\n\t perror(\"accept\");\n throw std::runtime_error(\"Socket error\");\n }\n\n struct sockaddr_in local_addr;\n rc = getsockname(sock, \n (struct sockaddr *)&local_addr, &addrlen);\n if (rc < 0) {\n perror(\"getsockname\");\n close(sock);\n\t close(listener_sock);\n throw std::runtime_error(\"Socket error\");\n }\n\n try {\n sk->add_connection(sock, \n local_addr.sin_addr, remote_addr.sin_addr);\n } catch (std::runtime_error& e) {\n dbgprintf(\"Failed to add connection: %s\\n\", e.what());\n }\n }\n}\nwow, somehow I got away without checking the return code of select in the internal listener thread. whoops! fixed that.#include \n#include \n#include \n#include \n#include \"cmm_internal_listener.h\"\n#include \"debug.h\"\n\n#define INTERNAL_LISTEN_PORT 42424\n\nListenerThread::ListenerThread(CMMSocketImpl *sk_)\n : sk(sk_)\n{\n struct sockaddr_in bind_addr;\n memset(&bind_addr, 0, sizeof(bind_addr));\n bind_addr.sin_addr.s_addr = INADDR_ANY;\n bind_addr.sin_port = htons(INTERNAL_LISTEN_PORT);\n \n listener_sock = socket(PF_INET, SOCK_STREAM, 0);\n if (listener_sock < 0) {\n throw -1;\n }\n\n int on = 1;\n int rc = setsockopt(listener_sock, SOL_SOCKET, SO_REUSEADDR,\n (char *) &on, sizeof(on));\n if (rc < 0) {\n dbgprintf(\"Cannot reuse socket address\");\n }\n \n rc = bind(listener_sock, \n (struct sockaddr *)&bind_addr, sizeof(bind_addr));\n if (rc < 0) {\n close(listener_sock);\n throw rc;\n }\n socklen_t addrlen = sizeof(bind_addr);\n rc = getsockname(listener_sock, \n (struct sockaddr *)&bind_addr, &addrlen);\n if (rc < 0) {\n perror(\"getsockname\");\n close(listener_sock);\n throw rc;\n }\n listen_port = bind_addr.sin_port;\n rc = listen(listener_sock, 5);\n if (rc < 0) {\n close(listener_sock);\n throw rc;\n }\n dbgprintf(\"Internal socket listener listening up on port %d\\n\",\n ntohs(listen_port));\n}\n\nListenerThread::~ListenerThread()\n{\n close(listener_sock);\n}\n\nin_port_t\nListenerThread::port() const\n{\n return listen_port;\n}\n\nvoid\nListenerThread::Run()\n{\n while (1) {\n fd_set readfds;\n FD_ZERO(&readfds);\n FD_SET(listener_sock, &readfds);\n int rc = select(listener_sock + 1, &readfds, NULL, NULL, NULL);\n\tif (rc < 0) {\n\t if (errno == EINTR) {\n\t\tcontinue;\n\t } else {\n\t\treturn;\n\t }\n\t}\n\n struct sockaddr_in remote_addr;\n socklen_t addrlen = sizeof(remote_addr);\n int sock = accept(listener_sock,\n (struct sockaddr *)&remote_addr, &addrlen);\n if (sock < 0) {\n\t perror(\"accept\");\n throw std::runtime_error(\"Socket error\");\n }\n\n struct sockaddr_in local_addr;\n rc = getsockname(sock, \n (struct sockaddr *)&local_addr, &addrlen);\n if (rc < 0) {\n perror(\"getsockname\");\n close(sock);\n\t close(listener_sock);\n throw std::runtime_error(\"Socket error\");\n }\n\n try {\n sk->add_connection(sock, \n local_addr.sin_addr, remote_addr.sin_addr);\n } catch (std::runtime_error& e) {\n dbgprintf(\"Failed to add connection: %s\\n\", e.what());\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ HLine.cpp\n\/\/ Copyright (c) 2009, Dan Heeks\n\/\/ This program is released under the BSD license. See the file COPYING for details.\n#include \"stdafx.h\"\n\n#include \"HLine.h\"\n#include \"HILine.h\"\n#include \"HCircle.h\"\n#include \"HArc.h\"\n#include \"..\/interface\/Tool.h\"\n#include \"..\/interface\/PropertyDouble.h\"\n#include \"..\/interface\/PropertyLength.h\"\n#include \"..\/interface\/PropertyVertex.h\"\n#include \"..\/tinyxml\/tinyxml.h\"\n#include \"Gripper.h\"\n\nHLine::HLine(const HLine &line){\n\toperator=(line);\n}\n\nHLine::HLine(const gp_Pnt &a, const gp_Pnt &b, const HeeksColor* col){\n\tA = a;\n\tB = b;\n\tcolor = *col;\n}\n\nHLine::~HLine(){\n}\n\nconst HLine& HLine::operator=(const HLine &b){\n\tEndedObject::operator=(b);\n\tcolor = b.color;\n\treturn *this;\n}\nHLine* line_for_tool = NULL;\n\nclass SetLineHorizontal:public Tool{\npublic:\n\tvoid Run(){\n\t\tline_for_tool->SetAbsoluteAngleConstraint(AbsoluteAngleHorizontal);\n\t\twxGetApp().Repaint();\n\t}\n\tconst wxChar* GetTitle(){return _T(\"Toggle Horizontal\");}\n\twxString BitmapPath(){return _T(\"new\");}\n\tconst wxChar* GetToolTip(){return _(\"Set this line to be horizontal\");}\n};\nstatic SetLineHorizontal horizontal_line_toggle;\n\nclass SetLineVertical:public Tool{\npublic:\n\tvoid Run(){\n\t\tline_for_tool->SetAbsoluteAngleConstraint(AbsoluteAngleVertical);\n\t\twxGetApp().Repaint();\n\t}\n\tconst wxChar* GetTitle(){return _T(\"Toggle Vertical\");}\n\twxString BitmapPath(){return _T(\"new\");}\n\tconst wxChar* GetToolTip(){return _(\"Set this line to be vertical\");}\n};\nstatic SetLineVertical vertical_line_toggle;\n\nvoid HLine::GetTools(std::list* t_list, const wxPoint* p)\n{\n\tline_for_tool = this;\n\tt_list->push_back(&horizontal_line_toggle);\n\tt_list->push_back(&vertical_line_toggle);\n}\n\nvoid HLine::glCommands(bool select, bool marked, bool no_color){\n\tif(!no_color){\n\t\twxGetApp().glColorEnsuringContrast(color);\n\t}\n\tGLfloat save_depth_range[2];\n\tif(marked){\n\t\tglGetFloatv(GL_DEPTH_RANGE, save_depth_range);\n\t\tglDepthRange(0, 0);\n\t\tglLineWidth(2);\n\t}\n\tglBegin(GL_LINES);\n\tglVertex3d(A.X(), A.Y(), A.Z());\n\tglVertex3d(B.X(), B.Y(), B.Z());\n\tglEnd();\n\tif(marked){\n\t\tglLineWidth(1);\n\t\tglDepthRange(save_depth_range[0], save_depth_range[1]);\n\t}\n\tgp_Pnt mid_point = A.XYZ() + (B.XYZ() - A.XYZ())\/2;\n\tgp_Dir dir = B.XYZ() - mid_point.XYZ();\n\tgp_Ax1 ax(mid_point,dir);\n\t\/\/gp_Dir up(0,0,1);\n\t\/\/ax.Rotate(gp_Ax1(mid_point,up),Pi\/2);\n\tConstrainedObject::glCommands(color,ax);\n}\n\nvoid HLine::Draw(wxDC& dc)\n{\n\twxGetApp().PlotSetColor(color);\n\tdouble s[3], e[3];\n\textract(A, s);\n\textract(B, e);\n\twxGetApp().PlotLine(s, e);\n}\n\nHeeksObj *HLine::MakeACopy(void)const{\n\tHLine *new_object = new HLine(*this);\n\treturn new_object;\n}\n\nvoid HLine::GetBox(CBox &box){\n\tbox.Insert(A.X(), A.Y(), A.Z());\n\tbox.Insert(B.X(), B.Y(), B.Z());\n}\n\nvoid HLine::GetGripperPositions(std::list *list, bool just_for_endof){\n\tlist->push_back(GripperTypeStretch);\n\tlist->push_back(A.X());\n\tlist->push_back(A.Y());\n\tlist->push_back(A.Z());\n\tlist->push_back(GripperTypeStretch);\n\tlist->push_back(B.X());\n\tlist->push_back(B.Y());\n\tlist->push_back(B.Z());\n}\n\nstatic void on_set_start(const double *vt, HeeksObj* object){\n\t((HLine*)object)->A = make_point(vt);\n\twxGetApp().Repaint();\n}\n\nstatic void on_set_end(const double *vt, HeeksObj* object){\n\t((HLine*)object)->B = make_point(vt);\n\twxGetApp().Repaint();\n}\n\nvoid HLine::GetProperties(std::list *list){\n\tdouble a[3], b[3];\n\textract(A, a);\n\textract(B, b);\n\tlist->push_back(new PropertyVertex(_(\"start\"), a, this, on_set_start));\n\tlist->push_back(new PropertyVertex(_(\"end\"), b, this, on_set_end));\n\tdouble length = A.Distance(B);\n\tlist->push_back(new PropertyLength(_(\"Length\"), length, NULL));\n\n\tHeeksObj::GetProperties(list);\n}\n\nbool HLine::FindNearPoint(const double* ray_start, const double* ray_direction, double *point){\n\tgp_Lin ray(make_point(ray_start), make_vector(ray_direction));\n\tgp_Pnt p1, p2;\n\tClosestPointsOnLines(GetLine(), ray, p1, p2);\n\n\tif(!Intersects(p1))\n\t\treturn false;\n\n\textract(p1, point);\n\treturn true;\n}\n\nbool HLine::FindPossTangentPoint(const double* ray_start, const double* ray_direction, double *point){\n\t\/\/ any point on this line is a possible tangent point\n\treturn FindNearPoint(ray_start, ray_direction, point);\n}\n\ngp_Lin HLine::GetLine()const{\n\tgp_Vec v(A, B);\n\treturn gp_Lin(A, v);\n}\n\nint HLine::Intersects(const HeeksObj *object, std::list< double > *rl)const{\n\tint numi = 0;\n\n\tswitch(object->GetType())\n\t{\n\tcase LineType:\n\t\t{\n\t\t\t\/\/ The OpenCascase libraries throw an exception when one tries to\n\t\t\t\/\/ create a gp_Lin() object using a vector that doesn't point\n\t\t\t\/\/ anywhere. If this is a zero-length line then we're in\n\t\t\t\/\/ trouble. Don't both with it.\n\t\t\tif ((A.X() == B.X()) &&\n\t\t\t (A.Y() == B.Y()) &&\n\t\t\t (A.Z() == B.Z())) break;\n\n\t\t\tgp_Pnt pnt;\n\t\t\tif(intersect(GetLine(), ((HLine*)object)->GetLine(), pnt))\n\t\t\t{\n\t\t\t\tif(Intersects(pnt) && ((HLine*)object)->Intersects(pnt)){\n\t\t\t\t\tif(rl)add_pnt_to_doubles(pnt, *rl);\n\t\t\t\t\tnumi++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase ILineType:\n\t\t{\n\t\t\tgp_Pnt pnt;\n\t\t\tif(intersect(GetLine(), ((HILine*)object)->GetLine(), pnt))\n\t\t\t{\n\t\t\t\tif(Intersects(pnt)){\n\t\t\t\t\tif(rl)add_pnt_to_doubles(pnt, *rl);\n\t\t\t\t\tnumi++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase ArcType:\n\t\t{\n\t\t\tstd::list plist;\n\t\t\tintersect(GetLine(), ((HArc*)object)->m_circle, plist);\n\t\t\tfor(std::list::iterator It = plist.begin(); It != plist.end(); It++)\n\t\t\t{\n\t\t\t\tgp_Pnt& pnt = *It;\n\t\t\t\tif(Intersects(pnt) && ((HArc*)object)->Intersects(pnt))\n\t\t\t\t{\n\t\t\t\t\tif(rl)add_pnt_to_doubles(pnt, *rl);\n\t\t\t\t\tnumi++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase CircleType:\n\t\t{\n\t\t\tstd::list plist;\n\t\t\tintersect(GetLine(), ((HCircle*)object)->m_circle, plist);\n\t\t\tfor(std::list::iterator It = plist.begin(); It != plist.end(); It++)\n\t\t\t{\n\t\t\t\tgp_Pnt& pnt = *It;\n\t\t\t\tif(Intersects(pnt))\n\t\t\t\t{\n\t\t\t\t\tif(rl)add_pnt_to_doubles(pnt, *rl);\n\t\t\t\t\tnumi++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\n\treturn numi;\n}\n\nbool HLine::Intersects(const gp_Pnt &pnt)const\n{\n\tgp_Lin this_line = GetLine();\n\tif(!intersect(pnt, this_line))return false;\n\n\t\/\/ check it lies between A and B\n\tgp_Vec v = this_line.Direction();\n\tdouble dpA = gp_Vec(A.XYZ()) * v;\n\tdouble dpB = gp_Vec(B.XYZ()) * v;\n\tdouble dp = gp_Vec(pnt.XYZ()) * v;\n\treturn dp >= dpA - wxGetApp().m_geom_tol && dp <= dpB + wxGetApp().m_geom_tol;\n}\n\nvoid HLine::GetSegments(void(*callbackfunc)(const double *p), double pixels_per_mm, bool want_start_point)const{\n\tif(want_start_point)\n\t{\n\t\tdouble p[3];\n\t\textract(A, p);\n\t\t(*callbackfunc)(p);\n\t}\n\n\tdouble p[3];\n\textract(B, p);\n\t(*callbackfunc)(p);\n}\n\ngp_Vec HLine::GetSegmentVector(double fraction)\n{\n\tgp_Vec line_vector(A, B);\n\tif(line_vector.Magnitude() < 0.000000001)return gp_Vec(0, 0, 0);\n\treturn gp_Vec(A, B).Normalized();\n}\n\nvoid HLine::WriteXML(TiXmlNode *root)\n{\n\tTiXmlElement * element;\n\telement = new TiXmlElement( \"Line\" );\n\troot->LinkEndChild( element ); \n\telement->SetAttribute(\"col\", color.COLORREF_color());\n\telement->SetDoubleAttribute(\"sx\", A.X());\n\telement->SetDoubleAttribute(\"sy\", A.Y());\n\telement->SetDoubleAttribute(\"sz\", A.Z());\n\telement->SetDoubleAttribute(\"ex\", B.X());\n\telement->SetDoubleAttribute(\"ey\", B.Y());\n\telement->SetDoubleAttribute(\"ez\", B.Z());\n\tWriteBaseXML(element);\n}\n\n\/\/ static member function\nHeeksObj* HLine::ReadFromXMLElement(TiXmlElement* pElem)\n{\n\tgp_Pnt p0, p1;\n\tHeeksColor c;\n\n\t\/\/ get the attributes\n\tfor(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())\n\t{\n\t\tstd::string name(a->Name());\n\t\tif(name == \"col\"){c = HeeksColor(a->IntValue());}\n\t\telse if(name == \"sx\"){p0.SetX(a->DoubleValue());}\n\t\telse if(name == \"sy\"){p0.SetY(a->DoubleValue());}\n\t\telse if(name == \"sz\"){p0.SetZ(a->DoubleValue());}\n\t\telse if(name == \"ex\"){p1.SetX(a->DoubleValue());}\n\t\telse if(name == \"ey\"){p1.SetY(a->DoubleValue());}\n\t\telse if(name == \"ez\"){p1.SetZ(a->DoubleValue());}\n\t}\n\n\tHLine* new_object = new HLine(p0, p1, &c);\n\tnew_object->ReadBaseXML(pElem);\n\n\treturn new_object;\n}\n\nvoid HLine::Reverse()\n{\n\tgp_Pnt temp = A;\n\tA = B;\n\tB = temp;\n}\n\nFixed Issue 162: \t Drawing regular shape (rectangle) causes crash gp_Dir doesn't like having no length. We don't seem to handle Open CASCADE's errors too well. Anyway, this change stops gp_Dir being constructed with no length, in this case.\/\/ HLine.cpp\n\/\/ Copyright (c) 2009, Dan Heeks\n\/\/ This program is released under the BSD license. See the file COPYING for details.\n#include \"stdafx.h\"\n\n#include \"HLine.h\"\n#include \"HILine.h\"\n#include \"HCircle.h\"\n#include \"HArc.h\"\n#include \"..\/interface\/Tool.h\"\n#include \"..\/interface\/PropertyDouble.h\"\n#include \"..\/interface\/PropertyLength.h\"\n#include \"..\/interface\/PropertyVertex.h\"\n#include \"..\/tinyxml\/tinyxml.h\"\n#include \"Gripper.h\"\n\nHLine::HLine(const HLine &line){\n\toperator=(line);\n}\n\nHLine::HLine(const gp_Pnt &a, const gp_Pnt &b, const HeeksColor* col){\n\tA = a;\n\tB = b;\n\tcolor = *col;\n}\n\nHLine::~HLine(){\n}\n\nconst HLine& HLine::operator=(const HLine &b){\n\tEndedObject::operator=(b);\n\tcolor = b.color;\n\treturn *this;\n}\nHLine* line_for_tool = NULL;\n\nclass SetLineHorizontal:public Tool{\npublic:\n\tvoid Run(){\n\t\tline_for_tool->SetAbsoluteAngleConstraint(AbsoluteAngleHorizontal);\n\t\twxGetApp().Repaint();\n\t}\n\tconst wxChar* GetTitle(){return _T(\"Toggle Horizontal\");}\n\twxString BitmapPath(){return _T(\"new\");}\n\tconst wxChar* GetToolTip(){return _(\"Set this line to be horizontal\");}\n};\nstatic SetLineHorizontal horizontal_line_toggle;\n\nclass SetLineVertical:public Tool{\npublic:\n\tvoid Run(){\n\t\tline_for_tool->SetAbsoluteAngleConstraint(AbsoluteAngleVertical);\n\t\twxGetApp().Repaint();\n\t}\n\tconst wxChar* GetTitle(){return _T(\"Toggle Vertical\");}\n\twxString BitmapPath(){return _T(\"new\");}\n\tconst wxChar* GetToolTip(){return _(\"Set this line to be vertical\");}\n};\nstatic SetLineVertical vertical_line_toggle;\n\nvoid HLine::GetTools(std::list* t_list, const wxPoint* p)\n{\n\tline_for_tool = this;\n\tt_list->push_back(&horizontal_line_toggle);\n\tt_list->push_back(&vertical_line_toggle);\n}\n\nvoid HLine::glCommands(bool select, bool marked, bool no_color){\n\tif(!no_color){\n\t\twxGetApp().glColorEnsuringContrast(color);\n\t}\n\tGLfloat save_depth_range[2];\n\tif(marked){\n\t\tglGetFloatv(GL_DEPTH_RANGE, save_depth_range);\n\t\tglDepthRange(0, 0);\n\t\tglLineWidth(2);\n\t}\n\tglBegin(GL_LINES);\n\tglVertex3d(A.X(), A.Y(), A.Z());\n\tglVertex3d(B.X(), B.Y(), B.Z());\n\tglEnd();\n\tif(marked){\n\t\tglLineWidth(1);\n\t\tglDepthRange(save_depth_range[0], save_depth_range[1]);\n\t}\n\n\tif(!A.IsEqual(B, wxGetApp().m_geom_tol))\n\t{\n\t\tgp_Pnt mid_point = A.XYZ() + (B.XYZ() - A.XYZ())\/2;\n\t\tgp_Dir dir = B.XYZ() - mid_point.XYZ();\n\t\tgp_Ax1 ax(mid_point,dir);\n\t\t\/\/gp_Dir up(0,0,1);\n\t\t\/\/ax.Rotate(gp_Ax1(mid_point,up),Pi\/2);\n\t\tConstrainedObject::glCommands(color,ax);\n\t}\n}\n\nvoid HLine::Draw(wxDC& dc)\n{\n\twxGetApp().PlotSetColor(color);\n\tdouble s[3], e[3];\n\textract(A, s);\n\textract(B, e);\n\twxGetApp().PlotLine(s, e);\n}\n\nHeeksObj *HLine::MakeACopy(void)const{\n\tHLine *new_object = new HLine(*this);\n\treturn new_object;\n}\n\nvoid HLine::GetBox(CBox &box){\n\tbox.Insert(A.X(), A.Y(), A.Z());\n\tbox.Insert(B.X(), B.Y(), B.Z());\n}\n\nvoid HLine::GetGripperPositions(std::list *list, bool just_for_endof){\n\tlist->push_back(GripperTypeStretch);\n\tlist->push_back(A.X());\n\tlist->push_back(A.Y());\n\tlist->push_back(A.Z());\n\tlist->push_back(GripperTypeStretch);\n\tlist->push_back(B.X());\n\tlist->push_back(B.Y());\n\tlist->push_back(B.Z());\n}\n\nstatic void on_set_start(const double *vt, HeeksObj* object){\n\t((HLine*)object)->A = make_point(vt);\n\twxGetApp().Repaint();\n}\n\nstatic void on_set_end(const double *vt, HeeksObj* object){\n\t((HLine*)object)->B = make_point(vt);\n\twxGetApp().Repaint();\n}\n\nvoid HLine::GetProperties(std::list *list){\n\tdouble a[3], b[3];\n\textract(A, a);\n\textract(B, b);\n\tlist->push_back(new PropertyVertex(_(\"start\"), a, this, on_set_start));\n\tlist->push_back(new PropertyVertex(_(\"end\"), b, this, on_set_end));\n\tdouble length = A.Distance(B);\n\tlist->push_back(new PropertyLength(_(\"Length\"), length, NULL));\n\n\tHeeksObj::GetProperties(list);\n}\n\nbool HLine::FindNearPoint(const double* ray_start, const double* ray_direction, double *point){\n\tgp_Lin ray(make_point(ray_start), make_vector(ray_direction));\n\tgp_Pnt p1, p2;\n\tClosestPointsOnLines(GetLine(), ray, p1, p2);\n\n\tif(!Intersects(p1))\n\t\treturn false;\n\n\textract(p1, point);\n\treturn true;\n}\n\nbool HLine::FindPossTangentPoint(const double* ray_start, const double* ray_direction, double *point){\n\t\/\/ any point on this line is a possible tangent point\n\treturn FindNearPoint(ray_start, ray_direction, point);\n}\n\ngp_Lin HLine::GetLine()const{\n\tgp_Vec v(A, B);\n\treturn gp_Lin(A, v);\n}\n\nint HLine::Intersects(const HeeksObj *object, std::list< double > *rl)const{\n\tint numi = 0;\n\n\tswitch(object->GetType())\n\t{\n\tcase LineType:\n\t\t{\n\t\t\t\/\/ The OpenCascase libraries throw an exception when one tries to\n\t\t\t\/\/ create a gp_Lin() object using a vector that doesn't point\n\t\t\t\/\/ anywhere. If this is a zero-length line then we're in\n\t\t\t\/\/ trouble. Don't both with it.\n\t\t\tif ((A.X() == B.X()) &&\n\t\t\t (A.Y() == B.Y()) &&\n\t\t\t (A.Z() == B.Z())) break;\n\n\t\t\tgp_Pnt pnt;\n\t\t\tif(intersect(GetLine(), ((HLine*)object)->GetLine(), pnt))\n\t\t\t{\n\t\t\t\tif(Intersects(pnt) && ((HLine*)object)->Intersects(pnt)){\n\t\t\t\t\tif(rl)add_pnt_to_doubles(pnt, *rl);\n\t\t\t\t\tnumi++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase ILineType:\n\t\t{\n\t\t\tgp_Pnt pnt;\n\t\t\tif(intersect(GetLine(), ((HILine*)object)->GetLine(), pnt))\n\t\t\t{\n\t\t\t\tif(Intersects(pnt)){\n\t\t\t\t\tif(rl)add_pnt_to_doubles(pnt, *rl);\n\t\t\t\t\tnumi++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase ArcType:\n\t\t{\n\t\t\tstd::list plist;\n\t\t\tintersect(GetLine(), ((HArc*)object)->m_circle, plist);\n\t\t\tfor(std::list::iterator It = plist.begin(); It != plist.end(); It++)\n\t\t\t{\n\t\t\t\tgp_Pnt& pnt = *It;\n\t\t\t\tif(Intersects(pnt) && ((HArc*)object)->Intersects(pnt))\n\t\t\t\t{\n\t\t\t\t\tif(rl)add_pnt_to_doubles(pnt, *rl);\n\t\t\t\t\tnumi++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase CircleType:\n\t\t{\n\t\t\tstd::list plist;\n\t\t\tintersect(GetLine(), ((HCircle*)object)->m_circle, plist);\n\t\t\tfor(std::list::iterator It = plist.begin(); It != plist.end(); It++)\n\t\t\t{\n\t\t\t\tgp_Pnt& pnt = *It;\n\t\t\t\tif(Intersects(pnt))\n\t\t\t\t{\n\t\t\t\t\tif(rl)add_pnt_to_doubles(pnt, *rl);\n\t\t\t\t\tnumi++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\n\treturn numi;\n}\n\nbool HLine::Intersects(const gp_Pnt &pnt)const\n{\n\tgp_Lin this_line = GetLine();\n\tif(!intersect(pnt, this_line))return false;\n\n\t\/\/ check it lies between A and B\n\tgp_Vec v = this_line.Direction();\n\tdouble dpA = gp_Vec(A.XYZ()) * v;\n\tdouble dpB = gp_Vec(B.XYZ()) * v;\n\tdouble dp = gp_Vec(pnt.XYZ()) * v;\n\treturn dp >= dpA - wxGetApp().m_geom_tol && dp <= dpB + wxGetApp().m_geom_tol;\n}\n\nvoid HLine::GetSegments(void(*callbackfunc)(const double *p), double pixels_per_mm, bool want_start_point)const{\n\tif(want_start_point)\n\t{\n\t\tdouble p[3];\n\t\textract(A, p);\n\t\t(*callbackfunc)(p);\n\t}\n\n\tdouble p[3];\n\textract(B, p);\n\t(*callbackfunc)(p);\n}\n\ngp_Vec HLine::GetSegmentVector(double fraction)\n{\n\tgp_Vec line_vector(A, B);\n\tif(line_vector.Magnitude() < 0.000000001)return gp_Vec(0, 0, 0);\n\treturn gp_Vec(A, B).Normalized();\n}\n\nvoid HLine::WriteXML(TiXmlNode *root)\n{\n\tTiXmlElement * element;\n\telement = new TiXmlElement( \"Line\" );\n\troot->LinkEndChild( element ); \n\telement->SetAttribute(\"col\", color.COLORREF_color());\n\telement->SetDoubleAttribute(\"sx\", A.X());\n\telement->SetDoubleAttribute(\"sy\", A.Y());\n\telement->SetDoubleAttribute(\"sz\", A.Z());\n\telement->SetDoubleAttribute(\"ex\", B.X());\n\telement->SetDoubleAttribute(\"ey\", B.Y());\n\telement->SetDoubleAttribute(\"ez\", B.Z());\n\tWriteBaseXML(element);\n}\n\n\/\/ static member function\nHeeksObj* HLine::ReadFromXMLElement(TiXmlElement* pElem)\n{\n\tgp_Pnt p0, p1;\n\tHeeksColor c;\n\n\t\/\/ get the attributes\n\tfor(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())\n\t{\n\t\tstd::string name(a->Name());\n\t\tif(name == \"col\"){c = HeeksColor(a->IntValue());}\n\t\telse if(name == \"sx\"){p0.SetX(a->DoubleValue());}\n\t\telse if(name == \"sy\"){p0.SetY(a->DoubleValue());}\n\t\telse if(name == \"sz\"){p0.SetZ(a->DoubleValue());}\n\t\telse if(name == \"ex\"){p1.SetX(a->DoubleValue());}\n\t\telse if(name == \"ey\"){p1.SetY(a->DoubleValue());}\n\t\telse if(name == \"ez\"){p1.SetZ(a->DoubleValue());}\n\t}\n\n\tHLine* new_object = new HLine(p0, p1, &c);\n\tnew_object->ReadBaseXML(pElem);\n\n\treturn new_object;\n}\n\nvoid HLine::Reverse()\n{\n\tgp_Pnt temp = A;\n\tA = B;\n\tB = temp;\n}\n\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n\/\/ If is included, put it after , because it includes\n\/\/ , and therefore would ignore the _WITH_GETLINE.\n#ifdef FREEBSD\n#define _WITH_GETLINE\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nHooks::Hooks ()\n: _enabled (true)\n, _debug (0)\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nHooks::~Hooks ()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Hooks::initialize ()\n{\n _debug = context.config.getInteger (\"debug.hooks\");\n\n \/\/ Scan \/hooks\n Directory d (context.config.get (\"data.location\"));\n d += \"hooks\";\n if (d.is_directory () &&\n d.readable ())\n {\n _scripts = d.list ();\n std::sort (_scripts.begin (), _scripts.end ());\n\n if (_debug >= 1)\n {\n std::vector ::iterator i;\n for (i = _scripts.begin (); i != _scripts.end (); ++i)\n context.debug (\"Found hook script \" + *i);\n }\n }\n else if (_debug >= 1)\n context.debug (\"Hook directory not readable: \" + d._data);\n\n _enabled = context.config.getBoolean (\"hooks\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Hooks::enable (bool value)\n{\n bool old_value = _enabled;\n _enabled = value;\n return old_value;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The on-launch event is triggered once, after initialization, before any\n\/\/ processing occurs, i.e first\n\/\/\n\/\/ Input:\n\/\/ - none\n\/\/\n\/\/ Output:\n\/\/ - all emitted JSON lines are added\/modified as tasks, if the exit code is\n\/\/ zero, otherwise ignored.\n\/\/ - minimal new task: {\"description\":\"Buy milk\"}\n\/\/ - to modify a task include complete JSON\n\/\/ - all emitted non-JSON lines are considered feedback messages if the exit\n\/\/ code is zero, otherwise they are considered errors.\n\/\/\nvoid Hooks::onLaunch ()\n{\n if (! _enabled)\n return;\n\n context.timer_hooks.start ();\n\n std::vector matchingScripts = scripts (\"on-launch\");\n std::vector ::iterator i;\n for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i)\n {\n if (_debug >= 1)\n context.debug (\"Hooks: Calling \" + *i);\n\n std::string output;\n std::vector args;\n int status = execute (*i, args, \"\", output);\n\n if (_debug >= 2)\n context.debug (format (\"Hooks: Completed with status {1}\", status));\n\n std::vector lines;\n split (lines, output, '\\n');\n std::vector ::iterator line;\n\n if (status == 0)\n {\n for (line = lines.begin (); line != lines.end (); ++line)\n {\n if (isJSON (*line))\n {\n if (_debug >= 2)\n context.debug (\"Hook output: \" + *line);\n\n \/\/ Only 'add' is possible.\n Task newTask (*line);\n context.tdb2.add (newTask);\n }\n else\n context.header (*line);\n }\n }\n else\n {\n for (line = lines.begin (); line != lines.end (); ++line)\n if (! isJSON (*line))\n context.error (*line);\n\n throw 0; \/\/ This is how hooks silently terminate processing.\n }\n }\n\n context.timer_hooks.stop ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The on-exit event is triggered once, after all processing is complete, i.e.\n\/\/ last\n\/\/\n\/\/ Input:\n\/\/ - read-only line of JSON for each task added\/modified\n\/\/\n\/\/ Output:\n\/\/ - any emitted JSON is ignored\n\/\/ - all emitted non-JSON lines are considered feedback messages if the exit\n\/\/ code is zero, otherwise they are considered errors.\n\/\/\nvoid Hooks::onExit ()\n{\n if (! _enabled)\n return;\n\n context.timer_hooks.start ();\n\n std::vector changes;\n context.tdb2.get_changes (changes);\n\n std::string input = \"\";\n std::vector ::const_iterator t;\n for (t = changes.begin (); t != changes.end (); ++t)\n {\n std::string json = t->composeJSON ();\n if (_debug >= 2)\n context.debug (\"Hook input: \" + json);\n\n input += json + \"\\n\";\n }\n\n std::vector matchingScripts = scripts (\"on-exit\");\n std::vector ::iterator i;\n for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i)\n {\n if (_debug >= 1)\n context.debug (\"Hooks: Calling \" + *i);\n\n std::string output;\n std::vector args;\n int status = execute (*i, args, input, output);\n\n if (_debug >= 2)\n context.debug (format (\"Hooks: Completed with status {1}\", status));\n\n std::vector lines;\n split (lines, output, '\\n');\n std::vector ::iterator line;\n\n for (line = lines.begin (); line != lines.end (); ++line)\n {\n if (_debug >= 2)\n context.debug (\"Hook output: \" + *line);\n\n if (! isJSON (*line))\n {\n if (status == 0)\n context.footnote (*line);\n else\n context.error (*line);\n }\n }\n }\n\n context.timer_hooks.stop ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The on-add event is triggered separately for each task added\n\/\/\n\/\/ Input:\n\/\/ - line of JSON for the task added\n\/\/\n\/\/ Output:\n\/\/ - all emitted JSON lines are added\/modified as tasks, if the exit code is\n\/\/ zero, otherwise ignored.\n\/\/ - minimal new task: {\"description\":\"Buy milk\"}\n\/\/ - to modify a task include complete JSON\n\/\/ - all emitted non-JSON lines are considered feedback messages if the exit\n\/\/ code is zero, otherwise they are considered errors.\n\/\/\nvoid Hooks::onAdd (std::vector & changes)\n{\n if (! _enabled)\n return;\n\n context.timer_hooks.start ();\n\n std::vector matchingScripts = scripts (\"on-add\");\n std::vector ::iterator i;\n for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i)\n {\n if (_debug >= 1)\n context.debug (\"Hooks: Calling \" + *i);\n\n std::string input = changes.at(0).composeJSON ();\n if (_debug >= 2)\n context.debug (\"Hook input: \" + input);\n\n input += \"\\n\";\n std::string output;\n std::vector args;\n int status = execute (*i, args, input, output);\n\n if (_debug >= 2)\n context.debug (format (\"Hooks: Completed with status {1}\", status));\n\n std::vector lines;\n split (lines, output, '\\n');\n std::vector ::iterator line;\n\n if (status == 0)\n {\n changes.clear ();\n for (line = lines.begin (); line != lines.end (); ++line)\n {\n if (_debug >= 2)\n context.debug (\"Hook output: \" + *line);\n\n if (isJSON (*line))\n changes.push_back (Task (*line));\n else\n context.footnote (*line);\n }\n }\n else\n {\n for (line = lines.begin (); line != lines.end (); ++line)\n if (! isJSON (*line))\n context.error (*line);\n\n throw 0; \/\/ This is how hooks silently terminate processing.\n }\n }\n\n context.timer_hooks.stop ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The on-modify event is triggered separately for each task added or modified\n\/\/\n\/\/ Input:\n\/\/ - line of JSON for the original task\n\/\/ - line of JSON for the modified task, the diff being the modification\n\/\/\n\/\/ Output:\n\/\/ - all emitted JSON lines are added\/modified as tasks, if the exit code is\n\/\/ zero, otherwise ignored.\n\/\/ - minimal new task: {\"description\":\"Buy milk\"}\n\/\/ - to modify a task include complete JSON\n\/\/ - all emitted non-JSON lines are considered feedback messages if the exit\n\/\/ code is zero, otherwise they are considered errors.\n\/\/\nvoid Hooks::onModify (const Task& before, std::vector & changes)\n{\n if (! _enabled)\n return;\n\n context.timer_hooks.start ();\n\n std::vector matchingScripts = scripts (\"on-modify\");\n std::vector ::iterator i;\n for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i)\n {\n if (_debug >= 1)\n context.debug (\"Hooks: Calling \" + *i);\n\n std::string beforeJSON = before.composeJSON ();\n std::string afterJSON = changes[0].composeJSON ();\n if (_debug >= 2)\n {\n context.debug (\"Hook input: \" + beforeJSON);\n context.debug (\"Hook input: \" + afterJSON);\n }\n\n std::string input = beforeJSON\n + \"\\n\"\n + afterJSON\n + \"\\n\";\n std::string output;\n std::vector args;\n int status = execute (*i, args, input, output);\n\n if (_debug >= 2)\n context.debug (format (\"Hooks: Completed with status {1}\", status));\n\n std::vector lines;\n split (lines, output, '\\n');\n std::vector ::iterator line;\n\n if (status == 0)\n {\n changes.clear ();\n for (line = lines.begin (); line != lines.end (); ++line)\n {\n if (_debug >= 2)\n context.debug (\"Hook output: \" + *line);\n\n if (isJSON (*line))\n changes.push_back (Task (*line));\n else\n context.footnote (*line);\n }\n }\n else\n {\n for (line = lines.begin (); line != lines.end (); ++line)\n if (! isJSON (*line))\n context.error (*line);\n\n throw 0; \/\/ This is how hooks silently terminate processing.\n }\n }\n\n context.timer_hooks.stop ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::vector Hooks::list ()\n{\n return _scripts;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::vector Hooks::scripts (const std::string& event)\n{\n std::vector matching;\n std::vector ::iterator i;\n for (i = _scripts.begin (); i != _scripts.end (); ++i)\n {\n if (i->find (\"\/\" + event) != std::string::npos)\n {\n File script (*i);\n if (script.executable ())\n matching.push_back (*i);\n }\n }\n\n return matching;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Hooks::isJSON (const std::string& input) const\n{\n \/\/ Does it even look like JSON? {...}\n if (input.length () > 2 &&\n input[0] == '{' &&\n input[input.length () - 1] == '}')\n {\n try\n {\n \/\/ The absolute minimum a task needs is:\n bool foundDescription = false;\n\n \/\/ Parse the whole thing.\n json::value* root = json::parse (input);\n if (root->type () == json::j_object)\n {\n json::object* root_obj = (json::object*)root;\n\n \/\/ For each object element...\n json_object_iter i;\n for (i = root_obj->_data.begin ();\n i != root_obj->_data.end ();\n ++i)\n {\n \/\/ If the attribute is a recognized column.\n std::string type = Task::attributes[i->first];\n if (type == \"string\" && i->first == \"description\")\n foundDescription = true;\n }\n }\n else\n throw std::string (\"Object expected.\");\n\n \/\/ It's JSON, but is it a task?\n if (! foundDescription)\n throw std::string (\"Missing 'description' attribute, of type 'string'.\");\n\n \/\/ Yep, looks like a JSON task.\n return true;\n }\n\n catch (const std::string& e)\n {\n if (_debug >= 1)\n context.error (\"Hook output looks like JSON, but is not a valid task.\");\n\n if (_debug >= 2)\n context.error (\"JSON \" + e);\n }\n\n catch (...)\n {\n if (_debug >= 1)\n context.error (\"Hook output looks like JSON, but fails to parse.\");\n }\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nHooks\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n\/\/ If is included, put it after , because it includes\n\/\/ , and therefore would ignore the _WITH_GETLINE.\n#ifdef FREEBSD\n#define _WITH_GETLINE\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nHooks::Hooks ()\n: _enabled (true)\n, _debug (0)\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nHooks::~Hooks ()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Hooks::initialize ()\n{\n _debug = context.config.getInteger (\"debug.hooks\");\n\n \/\/ Scan \/hooks\n Directory d (context.config.get (\"data.location\"));\n d += \"hooks\";\n if (d.is_directory () &&\n d.readable ())\n {\n _scripts = d.list ();\n std::sort (_scripts.begin (), _scripts.end ());\n\n if (_debug >= 1)\n {\n std::vector ::iterator i;\n for (i = _scripts.begin (); i != _scripts.end (); ++i)\n context.debug (\"Found hook script \" + *i);\n }\n }\n else if (_debug >= 1)\n context.debug (\"Hook directory not readable: \" + d._data);\n\n _enabled = context.config.getBoolean (\"hooks\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Hooks::enable (bool value)\n{\n bool old_value = _enabled;\n _enabled = value;\n return old_value;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The on-launch event is triggered once, after initialization, before any\n\/\/ processing occurs, i.e first\n\/\/\n\/\/ Input:\n\/\/ - none\n\/\/\n\/\/ Output:\n\/\/ - all emitted JSON lines are added\/modified as tasks, if the exit code is\n\/\/ zero, otherwise ignored.\n\/\/ - minimal new task: {\"description\":\"Buy milk\"}\n\/\/ - to modify a task include complete JSON\n\/\/ - all emitted non-JSON lines are considered feedback messages if the exit\n\/\/ code is zero, otherwise they are considered errors.\n\/\/\nvoid Hooks::onLaunch ()\n{\n if (! _enabled)\n return;\n\n context.timer_hooks.start ();\n\n std::vector matchingScripts = scripts (\"on-launch\");\n std::vector ::iterator i;\n for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i)\n {\n if (_debug >= 1)\n context.debug (\"Hooks: Calling \" + *i);\n\n std::string output;\n std::vector args;\n int status = execute (*i, args, \"\", output);\n\n if (_debug >= 2)\n context.debug (format (\"Hooks: Completed with status {1}\", status));\n\n std::vector lines;\n split (lines, output, '\\n');\n std::vector ::iterator line;\n\n if (status == 0)\n {\n for (line = lines.begin (); line != lines.end (); ++line)\n {\n if (isJSON (*line))\n {\n if (_debug >= 2)\n {\n context.debug (\"Hook output:\");\n context.debug (\" \" + *line);\n }\n\n \/\/ Only 'add' is possible.\n Task newTask (*line);\n context.tdb2.add (newTask);\n }\n else\n context.header (*line);\n }\n }\n else\n {\n for (line = lines.begin (); line != lines.end (); ++line)\n if (! isJSON (*line))\n context.error (*line);\n\n throw 0; \/\/ This is how hooks silently terminate processing.\n }\n }\n\n context.timer_hooks.stop ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The on-exit event is triggered once, after all processing is complete, i.e.\n\/\/ last\n\/\/\n\/\/ Input:\n\/\/ - read-only line of JSON for each task added\/modified\n\/\/\n\/\/ Output:\n\/\/ - any emitted JSON is ignored\n\/\/ - all emitted non-JSON lines are considered feedback messages if the exit\n\/\/ code is zero, otherwise they are considered errors.\n\/\/\nvoid Hooks::onExit ()\n{\n if (! _enabled)\n return;\n\n context.timer_hooks.start ();\n\n std::vector changes;\n context.tdb2.get_changes (changes);\n\n std::string input = \"\";\n std::vector ::const_iterator t;\n for (t = changes.begin (); t != changes.end (); ++t)\n {\n std::string json = t->composeJSON ();\n if (_debug >= 2)\n context.debug (\"Hook input: \" + json);\n\n input += json + \"\\n\";\n }\n\n std::vector matchingScripts = scripts (\"on-exit\");\n std::vector ::iterator i;\n for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i)\n {\n if (_debug >= 1)\n context.debug (\"Hooks: Calling \" + *i);\n\n std::string output;\n std::vector args;\n int status = execute (*i, args, input, output);\n\n if (_debug >= 2)\n context.debug (format (\"Hooks: Completed with status {1}\", status));\n\n std::vector lines;\n split (lines, output, '\\n');\n std::vector ::iterator line;\n\n if (_debug >= 2)\n context.debug (\"Hook output:\");\n\n for (line = lines.begin (); line != lines.end (); ++line)\n {\n if (! isJSON (*line))\n {\n if (_debug >= 2)\n context.debug (\" \" + *line);\n\n if (status == 0)\n context.footnote (*line);\n else\n context.error (*line);\n }\n }\n }\n\n context.timer_hooks.stop ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The on-add event is triggered separately for each task added\n\/\/\n\/\/ Input:\n\/\/ - line of JSON for the task added\n\/\/\n\/\/ Output:\n\/\/ - all emitted JSON lines are added\/modified as tasks, if the exit code is\n\/\/ zero, otherwise ignored.\n\/\/ - minimal new task: {\"description\":\"Buy milk\"}\n\/\/ - to modify a task include complete JSON\n\/\/ - all emitted non-JSON lines are considered feedback messages if the exit\n\/\/ code is zero, otherwise they are considered errors.\n\/\/\nvoid Hooks::onAdd (std::vector & changes)\n{\n if (! _enabled)\n return;\n\n context.timer_hooks.start ();\n\n std::vector matchingScripts = scripts (\"on-add\");\n std::vector ::iterator i;\n for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i)\n {\n if (_debug >= 1)\n context.debug (\"Hooks: Calling \" + *i);\n\n std::string input = changes.at(0).composeJSON ();\n if (_debug >= 2)\n context.debug (\"Hook input: \" + input);\n\n input += \"\\n\";\n std::string output;\n std::vector args;\n int status = execute (*i, args, input, output);\n\n if (_debug >= 2)\n context.debug (format (\"Hooks: Completed with status {1}\", status));\n\n std::vector lines;\n split (lines, output, '\\n');\n std::vector ::iterator line;\n\n if (status == 0)\n {\n changes.clear ();\n\n if (_debug >= 2)\n context.debug (\"Hook output:\");\n\n for (line = lines.begin (); line != lines.end (); ++line)\n {\n if (_debug >= 2)\n context.debug (\" \" + *line);\n\n if (isJSON (*line))\n changes.push_back (Task (*line));\n else\n context.footnote (*line);\n }\n }\n else\n {\n for (line = lines.begin (); line != lines.end (); ++line)\n if (! isJSON (*line))\n context.error (*line);\n\n throw 0; \/\/ This is how hooks silently terminate processing.\n }\n }\n\n context.timer_hooks.stop ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The on-modify event is triggered separately for each task added or modified\n\/\/\n\/\/ Input:\n\/\/ - line of JSON for the original task\n\/\/ - line of JSON for the modified task, the diff being the modification\n\/\/\n\/\/ Output:\n\/\/ - all emitted JSON lines are added\/modified as tasks, if the exit code is\n\/\/ zero, otherwise ignored.\n\/\/ - minimal new task: {\"description\":\"Buy milk\"}\n\/\/ - to modify a task include complete JSON\n\/\/ - all emitted non-JSON lines are considered feedback messages if the exit\n\/\/ code is zero, otherwise they are considered errors.\n\/\/\nvoid Hooks::onModify (const Task& before, std::vector & changes)\n{\n if (! _enabled)\n return;\n\n context.timer_hooks.start ();\n\n std::vector matchingScripts = scripts (\"on-modify\");\n std::vector ::iterator i;\n for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i)\n {\n if (_debug >= 1)\n context.debug (\"Hooks: Calling \" + *i);\n\n std::string beforeJSON = before.composeJSON ();\n std::string afterJSON = changes[0].composeJSON ();\n if (_debug >= 2)\n {\n context.debug (\"Hook input:\");\n context.debug (\" \" + beforeJSON);\n context.debug (\" \" + afterJSON);\n }\n\n std::string input = beforeJSON\n + \"\\n\"\n + afterJSON\n + \"\\n\";\n std::string output;\n std::vector args;\n int status = execute (*i, args, input, output);\n\n if (_debug >= 2)\n context.debug (format (\"Hooks: Completed with status {1}\", status));\n\n std::vector lines;\n split (lines, output, '\\n');\n std::vector ::iterator line;\n\n if (status == 0)\n {\n changes.clear ();\n\n if (_debug >= 2)\n context.debug (\"Hook output:\");\n\n for (line = lines.begin (); line != lines.end (); ++line)\n {\n if (_debug >= 2)\n context.debug (\" \" + *line);\n\n if (isJSON (*line))\n changes.push_back (Task (*line));\n else\n context.footnote (*line);\n }\n }\n else\n {\n for (line = lines.begin (); line != lines.end (); ++line)\n if (! isJSON (*line))\n context.error (*line);\n\n throw 0; \/\/ This is how hooks silently terminate processing.\n }\n }\n\n context.timer_hooks.stop ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::vector Hooks::list ()\n{\n return _scripts;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::vector Hooks::scripts (const std::string& event)\n{\n std::vector matching;\n std::vector ::iterator i;\n for (i = _scripts.begin (); i != _scripts.end (); ++i)\n {\n if (i->find (\"\/\" + event) != std::string::npos)\n {\n File script (*i);\n if (script.executable ())\n matching.push_back (*i);\n }\n }\n\n return matching;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Hooks::isJSON (const std::string& input) const\n{\n \/\/ Does it even look like JSON? {...}\n if (input.length () > 2 &&\n input[0] == '{' &&\n input[input.length () - 1] == '}')\n {\n try\n {\n \/\/ The absolute minimum a task needs is:\n bool foundDescription = false;\n\n \/\/ Parse the whole thing.\n json::value* root = json::parse (input);\n if (root->type () == json::j_object)\n {\n json::object* root_obj = (json::object*)root;\n\n \/\/ For each object element...\n json_object_iter i;\n for (i = root_obj->_data.begin ();\n i != root_obj->_data.end ();\n ++i)\n {\n \/\/ If the attribute is a recognized column.\n std::string type = Task::attributes[i->first];\n if (type == \"string\" && i->first == \"description\")\n foundDescription = true;\n }\n }\n else\n throw std::string (\"Object expected.\");\n\n \/\/ It's JSON, but is it a task?\n if (! foundDescription)\n throw std::string (\"Missing 'description' attribute, of type 'string'.\");\n\n \/\/ Yep, looks like a JSON task.\n return true;\n }\n\n catch (const std::string& e)\n {\n if (_debug >= 1)\n context.error (\"Hook output looks like JSON, but is not a valid task.\");\n\n if (_debug >= 2)\n context.error (\"JSON \" + e);\n }\n\n catch (...)\n {\n if (_debug >= 1)\n context.error (\"Hook output looks like JSON, but fails to parse.\");\n }\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"#include \n#include \"Input.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/ void Input::setUser() {\n\/\/ }\n\nvoid Input::getInput() {\n strLine.clear();\n cout << \"$ \";\n getline (cin, strLine);\n \n \/\/ if the user ONLY entered exit \n if (strLine == \"exit\") {\n cout << \"You have exited shell.\" << endl;\n exit(0);\n }\n\n \/\/ if # spotted, cuts off # and everything after it\n size_t found = strLine.find('#');\n if (found != string::npos) {\n strLine.erase(strLine.begin() + found, strLine.end());\n if (strLine.size() == 0) {\n \/\/ cout << \"nothing left\" << endl;\n }\n }\n}\n\nbool Input::isTest() {\n size_t found = strLine.find('[');\n if (found != string::npos) {\n if ( validTest() ) {\n return true;\n }\n return false;\n }\n \n \/\/ check if test is first word in string or after connector\n if (strLine.find(\"test \") != string::npos) {\n return true;\n }\n\n return false;\n}\n\n\/\/ handle error when user puts something like \"] [\" wtf\nbool Input::validTest() {\n size_t cntrOpen = std::count(strLine.begin(), strLine.end(), '[');\n size_t cntrClose = std::count(strLine.begin(), strLine.end(), ']');\n\n if (cntrOpen == cntrClose) {\n return true;\n }\n return false;\n}\n\nvoid Input::brackTest() {\n \/\/ handles [ ]\n}\n\n\/\/ if semicolon, erase \nvoid Input::semicolon(queue& q, string s) {\n if (s.size() != 0 && s.at(s.size()-1) == ';') {\n s.erase(s.size()-1);\n q.push(s);\n q.push(\";\");\n }\n else {\n q.push(s);\n }\n}\n\n\n\/\/ returns a queue of parsed string\nqueue Input::Parse() {\n \/\/ checks if there's anything\n \/\/ cout << \"test: \" << strLine << endl;\n \n \/\/ clears tasks queue\n queue empty;\n swap(tasks, empty);\n\n if (strLine.size() == 0) {\n return tasks;\n }\n \n \/\/ checks if string has only spaces\n if (strLine.find_first_not_of(' ') == string::npos) {\n return tasks;\n }\n\n istringstream iss(strLine);\n\n \/\/ iss >> ws;\n string token;\n string cmd;\n \/\/ end used to determine if its end of user input\n bool end = true;\n bool start = true;\n \/\/ if a connector was just detected\n bool con = false;\n \/\/ if there is a parentheses\n bool paren = false;\n bool tested = false;\n\n \/\/ ignores ' '\n while (getline(iss, token, ' ')) {\n if ( (start && token == \"test\") || (con && token == \"test\" )) {\n tasks.push(token);\n if (getline(iss, token, ' ')) {\n if (token == \"-e\" || token == \"-f\" || token == \"-d\") {\n tasks.push(token);\n if (getline(iss, token, ' ')) {\n \/\/ tasks.push(token);\n semicolon(tasks, token);\n }\n \/\/ strLine empty\n else {return tasks;}\n }\n else if (token != \"&&\" && token != \"||\" && token != \";\") {\n tasks.push(\"-e\");\n \/\/ tasks.push(token);\n semicolon(tasks, token);\n }\n else if (token == \"&&\" || token == \"||\" || token == \";\") {\n \/\/ tasks.push(token);\n semicolon(tasks, token);\n }\n }\n end = false;\n tested = true;\n } \n\n \/\/ removed else if\n else if (token == \"&&\" || token == \"||\" || token == \";\" || \n token == \"(\" || token == \")\") {\n \/\/ pushes whatever cmd was\n \/\/ if (!tested) {\n if (!cmd.empty()) {\n tasks.push(cmd);\n }\n \/\/ makes string empty\n cmd.clear();\n \/\/ pushes &&, ||, or ;\n tasks.push(token);\n if (token == \"(\") {paren = true;}\n end = false;\n con = true;\n tested = false;\n }\n \n \/\/ if you see [, keep reading til you see ]\n else if ( (start && token == \"[\") || (con && token == \"[\") ) {\n tasks.push(token);\n while (token != \"]\") {\n if (getline(iss, token, ' ')) {\n \/\/ tasks.push(token);\n semicolon(tasks, token);\n }\n \/\/ empty\n else {return tasks;}\n }\n end = false;\n con = false;\n tested = false;\n }\n\n\n \n\t \/\/ would see if the first char of token is \n\t \/\/ ( then would push ( delete it from\n\t \/\/ the token then push the actual token in\n\t \/\/ would set paren to true letting \n\t \/\/ it know that there is a closing\n\t \/\/ paren to look for\n\n\t else if (token.at(0) == '(') {\n while (token.at(0) == '(') {\n\t paren = true;\n \t tasks.push(\"(\");\n\t token.erase(0, 1);\n\t \/\/ tasks.push(token);\n if (cmd.empty()) {\n cmd = token;\n }\n else {\n cmd = \" \" + token;\n }\n }\n end = false;\n con = false;\n\t }\n\n\t \/\/ would check to see if paren is true \n\t \/\/ and would see is the last char in\n\t \/\/ token is ) then would erase ) from token\n\t \/\/ push the token in push the \n\t \/\/ ) in and make paren false again\n\t \/\/ so that it know the braket is closed \n\t else if (paren == true && token.at(token.size() - 1) == ')') {\n while (token.at(token.size() - 1) == ')') {\n token.erase(token.size()-1);\n if (cmd.empty()) {\n tasks.push(token);\n }\n else {\n tasks.push(cmd + \" \" + token);\n cmd.clear();\n }\n\t \/\/ tasks.push(token);\n\t tasks.push(\")\");\n }\n\t \/\/ paren = false;\n end = false;\n con = false;\n\t }\t\n \/\/ else if not a connector\n \n \/\/ else if (strLine.find(\"&&\") != std::string::npos) {\n \/\/ cout << \"found &&\" << endl;\n \/\/ find position and split up string accordingly\n \/\/ }\n\n else { \/\/if (!tested) {\n \/\/ check if end of token has semicolon\n \/\/ remove the extra spaces\n \/\/ cout << \"token: \" << token << token.size() << endl;\n if (token.size() != 0 && token.at(token.size() - 1) == ';') {\n token.erase(token.size()-1);\n if (cmd.empty()) {\n tasks.push(token);\n }\n else {\n tasks.push(cmd + \" \" + token);\n cmd.clear();\n }\n tasks.push(\";\");\n end = false;\n }\n\n \n \/\/ check if connectors are hidden in words\n \n \/\/ no semicolon detected at end of word\n else {\n if (cmd.empty()) {\n cmd = token;\n }\n else {\n cmd = cmd + \" \" + token;\n }\n end = true;\n }\n con = false;\n tested = false;\n }\n\n start = false;\n }\n \n \/\/ if no more connectors were detected\n if (end) {\n tasks.push(cmd);\n }\n\n \/\/ check if last thing in task is a && or ||\n \/\/ if (token == \"&&\" || token == \"||\") {\n \/\/ get user input again\n \/\/ getInput();\n \/\/ Parse();\n \/\/ }\n\n return tasks;\n}\n\n\/\/ converts a token to char**\nchar** Input::toChar(string a) {\n stringstream stream(a);\n string oneWord;\n int i = 0;\n char** c = new char*[1024];\n \/\/ one word at a time\n while (stream >> oneWord) {\n \/\/ allocating memory\n char* ptr = new char[oneWord.size() + 1];\n \/\/ copies string (converted to c-string) to ptr)\n memcpy(ptr, oneWord.c_str(), oneWord.size() + 1);\n c[i] = ptr;\n ++i;\n }\n \n \/\/ null terminates the char**\n c[i] = '\\0';\n\n return c;\n}\n\n\nshould parse parentheses correctly#include \n#include \"Input.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/ void Input::setUser() {\n\/\/ }\n\nvoid Input::getInput() {\n strLine.clear();\n cout << \"$ \";\n getline (cin, strLine);\n \n \/\/ if the user ONLY entered exit \n if (strLine == \"exit\") {\n cout << \"You have exited shell.\" << endl;\n exit(0);\n }\n\n \/\/ if # spotted, cuts off # and everything after it\n size_t found = strLine.find('#');\n if (found != string::npos) {\n strLine.erase(strLine.begin() + found, strLine.end());\n if (strLine.size() == 0) {\n \/\/ cout << \"nothing left\" << endl;\n }\n }\n}\n\nbool Input::isTest() {\n size_t found = strLine.find('[');\n if (found != string::npos) {\n if ( validTest() ) {\n return true;\n }\n return false;\n }\n \n \/\/ check if test is first word in string or after connector\n if (strLine.find(\"test \") != string::npos) {\n return true;\n }\n\n return false;\n}\n\n\/\/ handle error when user puts something like \"] [\" wtf\nbool Input::validTest() {\n size_t cntrOpen = std::count(strLine.begin(), strLine.end(), '[');\n size_t cntrClose = std::count(strLine.begin(), strLine.end(), ']');\n\n if (cntrOpen == cntrClose) {\n return true;\n }\n return false;\n}\n\nvoid Input::brackTest() {\n \/\/ handles [ ]\n}\n\n\/\/ if semicolon, erase \nvoid Input::semicolon(queue& q, string s) {\n if (s.size() != 0 && s.at(s.size()-1) == ';') {\n s.erase(s.size()-1);\n q.push(s);\n q.push(\";\");\n }\n else {\n q.push(s);\n }\n}\n\n\n\/\/ returns a queue of parsed string\nqueue Input::Parse() {\n \/\/ checks if there's anything\n \/\/ cout << \"test: \" << strLine << endl;\n \n \/\/ clears tasks queue\n queue empty;\n swap(tasks, empty);\n\n if (strLine.size() == 0) {\n return tasks;\n }\n \n \/\/ checks if string has only spaces\n if (strLine.find_first_not_of(' ') == string::npos) {\n return tasks;\n }\n\n istringstream iss(strLine);\n\n \/\/ iss >> ws;\n string token;\n string cmd;\n \/\/ end used to determine if its end of user input\n bool end = true;\n bool start = true;\n \/\/ if a connector was just detected\n bool con = false;\n \/\/ if there is a parentheses\n bool paren = false;\n bool tested = false;\n\n \/\/ ignores ' '\n while (getline(iss, token, ' ')) {\n if ( (start && token == \"test\") || (con && token == \"test\" )) {\n tasks.push(token);\n if (getline(iss, token, ' ')) {\n if (token == \"-e\" || token == \"-f\" || token == \"-d\") {\n tasks.push(token);\n if (getline(iss, token, ' ')) {\n \/\/ tasks.push(token);\n semicolon(tasks, token);\n }\n \/\/ strLine empty\n else {return tasks;}\n }\n else if (token != \"&&\" && token != \"||\" && token != \";\") {\n tasks.push(\"-e\");\n \/\/ tasks.push(token);\n semicolon(tasks, token);\n }\n else if (token == \"&&\" || token == \"||\" || token == \";\") {\n \/\/ tasks.push(token);\n semicolon(tasks, token);\n }\n }\n end = false;\n tested = true;\n } \n\n \/\/ removed else if\n else if (token == \"&&\" || token == \"||\" || token == \";\" || \n token == \"(\" || token == \")\") {\n \/\/ pushes whatever cmd was\n \/\/ if (!tested) {\n if (!cmd.empty()) {\n tasks.push(cmd);\n }\n \/\/ makes string empty\n cmd.clear();\n \/\/ pushes &&, ||, or ;\n tasks.push(token);\n if (token == \"(\") {paren = true;}\n end = false;\n con = true;\n tested = false;\n }\n \n \/\/ if you see [, keep reading til you see ]\n else if ( (start && token == \"[\") || (con && token == \"[\") ) {\n tasks.push(token);\n while (token != \"]\") {\n if (getline(iss, token, ' ')) {\n \/\/ tasks.push(token);\n semicolon(tasks, token);\n }\n \/\/ empty\n else {return tasks;}\n }\n end = false;\n con = false;\n tested = false;\n }\n\n\n \n\t \/\/ would see if the first char of token is \n\t \/\/ ( then would push ( delete it from\n\t \/\/ the token then push the actual token in\n\t \/\/ would set paren to true letting \n\t \/\/ it know that there is a closing\n\t \/\/ paren to look for\n\n\t else if (token.at(0) == '(') {\n while (token.at(0) == '(') {\n\t paren = true;\n \t tasks.push(\"(\");\n\t token.erase(0, 1);\n\t \/\/ tasks.push(token);\n if (cmd.empty() && !token.empty() && token.at(0) != '(') {\n cmd = token;\n }\n else if (!cmd.empty()) {\n cmd += \" \" + token;\n }\n }\n end = false;\n con = false;\n\t }\n\n\t \/\/ would check to see if paren is true \n\t \/\/ and would see is the last char in\n\t \/\/ token is ) then would erase ) from token\n\t \/\/ push the token in push the \n\t \/\/ ) in and make paren false again\n\t \/\/ so that it know the braket is closed \n\t else if (paren == true && token.at(token.size() - 1) == ')') {\n int count = 0;\n while (token.at(token.size() - 1) == ')') {\n token.erase(token.size()-1);\n ++count;\n if (cmd.empty() && !token.empty() && token.at(0) != ')') {\n \/\/ cout << \"1: \" << token << endl;\n \/\/ tasks.push(token);\n cmd = token;\n }\n else if (!cmd.empty() && token.at(token.size()-1) != ')') {\n \/\/ tasks.push(cmd + \" \" + token);\n \/\/ cmd.clear();\n cmd += \" \" + token;\n }\n\t \/\/ tasks.push(token);\n\t \/\/ tasks.push(\")\");\n }\n tasks.push(cmd);\n cmd.clear();\n\t \/\/ paren = false;\n while (count != 0) {\n tasks.push(\")\");\n count -= 1;\n }\n end = false;\n con = false;\n\t }\t\n \/\/ else if not a connector\n \n \/\/ else if (strLine.find(\"&&\") != std::string::npos) {\n \/\/ cout << \"found &&\" << endl;\n \/\/ find position and split up string accordingly\n \/\/ }\n\n else { \/\/if (!tested) {\n \/\/ check if end of token has semicolon\n \/\/ remove the extra spaces\n \/\/ cout << \"token: \" << token << token.size() << endl;\n if (token.size() != 0 && token.at(token.size() - 1) == ';') {\n token.erase(token.size()-1);\n if (cmd.empty()) {\n tasks.push(token);\n }\n else {\n tasks.push(cmd + \" \" + token);\n cmd.clear();\n }\n tasks.push(\";\");\n end = false;\n }\n\n \n \/\/ check if connectors are hidden in words\n \n \/\/ no semicolon detected at end of word\n else {\n if (cmd.empty()) {\n cmd = token;\n }\n else {\n cmd = cmd + \" \" + token;\n }\n end = true;\n }\n con = false;\n tested = false;\n }\n\n start = false;\n }\n \n \/\/ if no more connectors were detected\n if (end) {\n tasks.push(cmd);\n }\n\n \/\/ check if last thing in task is a && or ||\n \/\/ if (token == \"&&\" || token == \"||\") {\n \/\/ get user input again\n \/\/ getInput();\n \/\/ Parse();\n \/\/ }\n\n return tasks;\n}\n\n\/\/ converts a token to char**\nchar** Input::toChar(string a) {\n stringstream stream(a);\n string oneWord;\n int i = 0;\n char** c = new char*[1024];\n \/\/ one word at a time\n while (stream >> oneWord) {\n \/\/ allocating memory\n char* ptr = new char[oneWord.size() + 1];\n \/\/ copies string (converted to c-string) to ptr)\n memcpy(ptr, oneWord.c_str(), oneWord.size() + 1);\n c[i] = ptr;\n ++i;\n }\n \n \/\/ null terminates the char**\n c[i] = '\\0';\n\n return c;\n}\n\n\n<|endoftext|>"} {"text":"#include \"Ising.h\"\n#include \n#include \n\n#define SQUARED(x) x*x\n\nnamespace ising {\n inline int s(char x,char y,char z) {\n return (x<<2) + (y<<1) + (z);\n }\n \n inline int boundsCheck(int x, const int max) {\n if (x < 0) {\n return max + x;\n }\n return x % max;\n }\n}\n\nusing namespace ising;\n\nint IsingReservoir::interactWithBit(int bit) {\n if (currentState->bit != bit) {\n currentState=currentState->bitFlipState;\n }\n \n assert(ceil(constants.tau)>0 &&\n \"Figure out how tau converts to discrete time.\");\n int iterations = ceil(constants.tau);\n \n for (int k = 0; kisingStep();\n this->wheelStep();\n }\n \n return currentState->bit;\n}\n\ninline int IsingReservoir::isingStep() {\n int row = 0;\n int column = (currentStepType == odd ? row + 1 : row) % 2;\n while (rowisingSide); k++) {\n int row = (int)(k % this->isingSide);\n int column = (int)(k \/ this->isingSide);\n \n \/\/Randomize the cells.\n this->cells[column][row] = gsl_rng_uniform_int(RNG,2);\n }\n \n \/\/ The metropolis algorithm!\n for (int k=0; k neighbors(4);\n for (int k = 0; k<4; k++) {\n Coordinate neighbor;\n switch (k) {\n case 0: \/\/ North\n neighbor.x = c.x;\n neighbor.y = c.y - 1;\n break;\n \n case 1: \/\/ South\n neighbor.x = c.x;\n neighbor.y = c.y + 1;\n break;\n \n case 2: \/\/ East\n neighbor.x = c.x - 1;\n neighbor.y = c.y;\n break;\n \n case 3: \/\/ West\n neighbor.x = c.x + 1;\n neighbor.y = c.y;\n break;\n \n default: \/\/ We should never be here.\n assert(0 && \"Unreachable.\");\n break;\n }\n neighbor.x = boundsCheck(neighbor.x, isingSide);\n neighbor.y = boundsCheck(neighbor.y, isingSide);\n neighbors.push_back(neighbor);\n }\n return neighbors;\n}\n \nIsingReservoir::~IsingReservoir() {\n for (int k=0; kisingSide; k++) {\n delete [] cells[k];\n }\n delete [] cells;\n}\n\nIsingReservoir::IsingReservoir(gsl_rng *RNG, Constants constants, int IS) : Reservoir(constants), isingSide(IS) {\n setupStateTable();\n this->cells = new char *[IS];\n for (int k=0; kcells[k]=new char[IS];\n }\n this->initializeCellsWithRNG(RNG);\n}\n\ninline void IsingReservoir::setupStateTable() {\n \/\/TODO: Custom states. This is goofy.\n \/\/Source: http:\/\/imgur.com\/FF5TBQh\n \n #define init(XX,StateXX) \\\n TransitionTable XX;\\\n for (char k=0; k<8; k++) \\\n XX[k]=&StateXX;\n init(A1,StateA1);\n A1[s(0,0,1)] = &StateB1;\n A1[s(1,0,1)] = &StateB1;\n transitions[&StateA1]=A1;\n \n init(B1,StateB1);\n B1[s(0,0,1)] = &StateA1;\n B1[s(1,0,1)] = &StateA1;\n B1[s(1,1,1)] = &StateC1;\n B1[s(0,1,1)] = &StateC1;\n transitions[&StateB1]=B1;\n \n init(C1,StateC1);\n C1[s(0,1,1)] = &StateB1;\n C1[s(1,1,1)] = &StateB1;\n C1[s(0,0,1)] = &StateA0;\n C1[s(0,0,0)] = &StateA0;\n transitions[&StateC1]=C1;\n \n init(A0,StateA0);\n A0[s(0,1,0)] = &StateC1;\n A0[s(0,1,1)] = &StateC1;\n A0[s(1,0,1)] = &StateB0;\n A0[s(0,0,1)] = &StateB0;\n transitions[&StateA0]=A0;\n \n init(B0,StateB0);\n B0[s(0,0,1)] = &StateB0;\n B0[s(1,0,1)] = &StateB0;\n B0[s(1,1,1)] = &StateA0;\n B0[s(0,1,1)] = &StateA0;\n transitions[&StateB0] = B0;\n \n init(C0,StateC0);\n C0[s(1,1,1)] = &StateB0;\n C0[s(0,1,1)] = &StateB0;\n transitions[&StateC0] = C0;\n \/\/TODO: TEST ME.\n}\n\nReservoir *IsingReservoir::IsingFactory::create(gsl_rng *RNG, Constants constants) {\n return new IsingReservoir(RNG,constants,dimension);\n}\nAlternate the step type.#include \"Ising.h\"\n#include \n#include \n\n#define SQUARED(x) x*x\n\nnamespace ising {\n inline int s(char x,char y,char z) {\n return (x<<2) + (y<<1) + (z);\n }\n \n inline int boundsCheck(int x, const int max) {\n if (x < 0) {\n return max + x;\n }\n return x % max;\n }\n}\n\nusing namespace ising;\n\nint IsingReservoir::interactWithBit(int bit) {\n if (currentState->bit != bit) {\n currentState=currentState->bitFlipState;\n }\n \n assert(ceil(constants.tau)>0 &&\n \"Figure out how tau converts to discrete time.\");\n int iterations = ceil(constants.tau);\n \n for (int k = 0; kisingStep();\n this->wheelStep();\n }\n \n return currentState->bit;\n}\n\ninline int IsingReservoir::isingStep() {\n int row = 0;\n int column = (currentStepType == odd ? row + 1 : row) % 2;\n while (rowisingSide); k++) {\n int row = (int)(k % this->isingSide);\n int column = (int)(k \/ this->isingSide);\n \n \/\/Randomize the cells.\n this->cells[column][row] = gsl_rng_uniform_int(RNG,2);\n }\n \n \/\/ The metropolis algorithm!\n for (int k=0; k neighbors(4);\n for (int k = 0; k<4; k++) {\n Coordinate neighbor;\n switch (k) {\n case 0: \/\/ North\n neighbor.x = c.x;\n neighbor.y = c.y - 1;\n break;\n \n case 1: \/\/ South\n neighbor.x = c.x;\n neighbor.y = c.y + 1;\n break;\n \n case 2: \/\/ East\n neighbor.x = c.x - 1;\n neighbor.y = c.y;\n break;\n \n case 3: \/\/ West\n neighbor.x = c.x + 1;\n neighbor.y = c.y;\n break;\n \n default: \/\/ We should never be here.\n assert(0 && \"Unreachable.\");\n break;\n }\n neighbor.x = boundsCheck(neighbor.x, isingSide);\n neighbor.y = boundsCheck(neighbor.y, isingSide);\n neighbors.push_back(neighbor);\n }\n return neighbors;\n}\n \nIsingReservoir::~IsingReservoir() {\n for (int k=0; kisingSide; k++) {\n delete [] cells[k];\n }\n delete [] cells;\n}\n\nIsingReservoir::IsingReservoir(gsl_rng *RNG, Constants constants, int IS) : Reservoir(constants), isingSide(IS) {\n setupStateTable();\n this->cells = new char *[IS];\n for (int k=0; kcells[k]=new char[IS];\n }\n this->initializeCellsWithRNG(RNG);\n}\n\ninline void IsingReservoir::setupStateTable() {\n \/\/TODO: Custom states. This is goofy.\n \/\/Source: http:\/\/imgur.com\/FF5TBQh\n \n #define init(XX,StateXX) \\\n TransitionTable XX;\\\n for (char k=0; k<8; k++) \\\n XX[k]=&StateXX;\n init(A1,StateA1);\n A1[s(0,0,1)] = &StateB1;\n A1[s(1,0,1)] = &StateB1;\n transitions[&StateA1]=A1;\n \n init(B1,StateB1);\n B1[s(0,0,1)] = &StateA1;\n B1[s(1,0,1)] = &StateA1;\n B1[s(1,1,1)] = &StateC1;\n B1[s(0,1,1)] = &StateC1;\n transitions[&StateB1]=B1;\n \n init(C1,StateC1);\n C1[s(0,1,1)] = &StateB1;\n C1[s(1,1,1)] = &StateB1;\n C1[s(0,0,1)] = &StateA0;\n C1[s(0,0,0)] = &StateA0;\n transitions[&StateC1]=C1;\n \n init(A0,StateA0);\n A0[s(0,1,0)] = &StateC1;\n A0[s(0,1,1)] = &StateC1;\n A0[s(1,0,1)] = &StateB0;\n A0[s(0,0,1)] = &StateB0;\n transitions[&StateA0]=A0;\n \n init(B0,StateB0);\n B0[s(0,0,1)] = &StateB0;\n B0[s(1,0,1)] = &StateB0;\n B0[s(1,1,1)] = &StateA0;\n B0[s(0,1,1)] = &StateA0;\n transitions[&StateB0] = B0;\n \n init(C0,StateC0);\n C0[s(1,1,1)] = &StateB0;\n C0[s(0,1,1)] = &StateB0;\n transitions[&StateC0] = C0;\n \/\/TODO: TEST ME.\n}\n\nReservoir *IsingReservoir::IsingFactory::create(gsl_rng *RNG, Constants constants) {\n return new IsingReservoir(RNG,constants,dimension);\n}\n<|endoftext|>"} {"text":"#ifndef MANIFOLDS_FUNCTIONS_POLY_COMPOS_SIMPLIFICATIONS_HH\n#define MANIFOLDS_FUNCTIONS_POLY_COMPOS_SIMPLIFICATIONS_HH\n\nnamespace manifolds {\n\n template \n struct Simplification<\n Addition, 0,\n typename std::enable_if<\n is_stateless::value>::type>\n {\n typedef Composition<\n Polynomial>,\n A> type;\n static type Combine(Addition a)\n {\n#ifdef PRINT_SIMPLIFIES\n std::cout << \"Simplifying addition of function by itself\\n\";\n#endif\n type b = {GetPolynomial(0.0,2.0), A()};\n return b;\n }\n };\n\n template \n struct Simplification<\n Multiplication, 0,\n typename std::enable_if::value>::type>\n {\n typedef Composition<\n Polynomial>,A> type;\n\n static type Combine(Multiplication)\n {\n#ifdef PRINT_SIMPLIFIES\n std::cout << \"Simplifying multiplication of function \"\n\t\"by itself\\n\";\n#endif\n return {GetPolynomial(0,0,1), A()};\n }\n };\n\n template \n struct Simplification<\n Multiplication,\n\t\t Composition>, 0,\n typename std::enable_if<\n and_...>::value &&\n (!std::is_same::value ||\n !is_stateless::value ||\n !is_stateless::value) &&\n !std::is_same<\n\ttypename Simplification>::type,\n\tMultiplication\n\t>::value>::type>\n {\n typedef Composition<\n typename Simplification<\n\tMultiplication>::type,\n Args...> type;\n\n static type Combine(Multiplication,\n\t\t\tComposition> a)\n {\n#ifdef PRINT_SIMPLIFIES\n std::cout << \"Simplifying multipication of composition of \"\n\t\"simplifiable functions\\n\";\n#endif\n auto first = std::get<0>(std::get<0>(a.GetFunctions()).\n\t\t\t GetFunctions());\n auto second = std::get<0>(std::get<1>(a.GetFunctions()).\n\t\t\t\tGetFunctions());\n Multiplication\n\tm(first,second);\n auto s = Simplify(m);\n return {s, Args()...};\n }\n };\n\n template \n struct Simplification<\n Addition>, T>, T>, 0,\n typename std::enable_if::value>::type>\n {\n static const int new_order = 2 > order ? 2 : order;\n typedef Composition>, T> type;\n template \n static auto Add(A a, B b)\n {\n return Addition(a,b);\n }\n static type Combine(Addition>, T>, T> a)\n {\n#ifdef PRINT_SIMPLIFIES\n std::cout << \"Simplifying addition of composed polynomial \"\n\t\"by inner function\\n\";\n#endif\n auto p = std::get<0>(std::get<0>(a.GetFunctions()).\n\t\t\t GetFunctions());\n return Simplify(Add(GetPolynomial(0,1), p))(T());\n }\n };\n\n template \n struct Simplification<\n Multiplication>, T>, T>, 0,\n typename std::enable_if::value>::type>\n {\n static const int new_order = 1 + order;\n typedef Composition>, T> type;\n\n template \n static auto Mult(A a, B b)\n {\n return Simplify(Multiplication(a,b));\n }\n\n static type Combine(Multiplication>, T>, T> a)\n {\n#ifdef PRINT_SIMPLIFIES\n std::cout << \"Simplifying multiplication of composed \"\n\t\"polynomial by inner function\\n\";\n#endif\n auto m =\n\tMult(GetPolynomial(0,1),\n\t std::get<0>(std::get<0>\n\t\t\t (a.GetFunctions()).\n\t\t\t GetFunctions()));\n T t;\n return m(t);\n }\n };\n\n template